prompt
stringclasses
1 value
completions
listlengths
1
63.8k
labels
listlengths
1
63.8k
source
stringclasses
1 value
other_info
stringlengths
2.06k
101k
index
int64
0
6.83k
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * FreeRDP: A Remote Desktop Protocol Implementation\n * Print Virtual Channel\n *\n * Copyright 2010-2011 Vic Lee\n * Copyright 2015 Thincast Technologies GmbH\n * Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>\n * Copyright 2016 Armin Novak <armin.novak@gmail.com>\n * Copyright 2016 David PHAM-VAN <d.phamvan@inuvika.com>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */", "#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif", "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>", "#include <winpr/crt.h>\n#include <winpr/string.h>\n#include <winpr/synch.h>\n#include <winpr/thread.h>\n#include <winpr/stream.h>\n#include <winpr/interlocked.h>\n#include <winpr/path.h>", "#include <freerdp/channels/rdpdr.h>\n#include <freerdp/crypto/crypto.h>", "#include \"../printer.h\"", "#include <freerdp/client/printer.h>", "#include <freerdp/channels/log.h>", "#define TAG CHANNELS_TAG(\"printer.client\")", "typedef struct _PRINTER_DEVICE PRINTER_DEVICE;\nstruct _PRINTER_DEVICE\n{\n\tDEVICE device;", "\trdpPrinter* printer;", "\tWINPR_PSLIST_HEADER pIrpList;", "\tHANDLE event;\n\tHANDLE stopEvent;", "\tHANDLE thread;\n\trdpContext* rdpcontext;\n\tchar port[64];\n};", "typedef enum\n{\n\tPRN_CONF_PORT = 0,\n\tPRN_CONF_PNP = 1,\n\tPRN_CONF_DRIVER = 2,\n\tPRN_CONF_DATA = 3\n} prn_conf_t;", "static const char* filemap[] = { \"PortDosName\", \"PnPName\", \"DriverName\",\n\t \"CachedPrinterConfigData\" };", "static char* get_printer_config_path(const rdpSettings* settings, const WCHAR* name, size_t length)\n{\n\tchar* dir = GetCombinedPath(settings->ConfigPath, \"printers\");\n\tchar* bname = crypto_base64_encode((const BYTE*)name, (int)length);\n\tchar* config = GetCombinedPath(dir, bname);", "\tif (config && !PathFileExistsA(config))\n\t{\n\t\tif (!PathMakePathA(config, NULL))\n\t\t{\n\t\t\tfree(config);\n\t\t\tconfig = NULL;\n\t\t}\n\t}", "\tfree(dir);\n\tfree(bname);\n\treturn config;\n}", "static BOOL printer_write_setting(const char* path, prn_conf_t type, const void* data,\n size_t length)\n{\n\tDWORD written = 0;\n\tBOOL rc = FALSE;\n\tHANDLE file;\n\tsize_t b64len;\n\tchar* base64 = NULL;\n\tconst char* name = filemap[type];\n\tchar* abs = GetCombinedPath(path, name);", "\tif (!abs)\n\t\treturn FALSE;", "\tfile = CreateFileA(abs, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\n\tfree(abs);", "\tif (file == INVALID_HANDLE_VALUE)\n\t\treturn FALSE;", "\tif (length > 0)\n\t{\n\t\tbase64 = crypto_base64_encode(data, length);", "\t\tif (!base64)\n\t\t\tgoto fail;", "\t\t/* base64 char represents 6bit -> 4*(n/3) is the length which is\n\t\t * always smaller than 2*n */\n\t\tb64len = strnlen(base64, 2 * length);\n\t\trc = WriteFile(file, base64, b64len, &written, NULL);", "\t\tif (b64len != written)\n\t\t\trc = FALSE;\n\t}\n\telse\n\t\trc = TRUE;", "fail:\n\tCloseHandle(file);\n\tfree(base64);\n\treturn rc;\n}", "static BOOL printer_config_valid(const char* path)\n{\n\tif (!path)\n\t\treturn FALSE;", "\tif (!PathFileExistsA(path))\n\t\treturn FALSE;", "\treturn TRUE;\n}", "static BOOL printer_read_setting(const char* path, prn_conf_t type, void** data, UINT32* length)\n{\n\tDWORD lowSize, highSize;\n\tDWORD read = 0;\n\tBOOL rc = FALSE;\n\tHANDLE file;\n\tchar* fdata = NULL;\n\tconst char* name = filemap[type];\n\tchar* abs = GetCombinedPath(path, name);", "\tif (!abs)\n\t\treturn FALSE;", "\tfile = CreateFileA(abs, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);\n\tfree(abs);", "\tif (file == INVALID_HANDLE_VALUE)\n\t\treturn FALSE;", "\tlowSize = GetFileSize(file, &highSize);", "\tif ((lowSize == INVALID_FILE_SIZE) || (highSize != 0))\n\t\tgoto fail;", "\tif (lowSize != 0)\n\t{\n\t\tfdata = malloc(lowSize);", "\t\tif (!fdata)\n\t\t\tgoto fail;", "\t\trc = ReadFile(file, fdata, lowSize, &read, NULL);", "\t\tif (lowSize != read)\n\t\t\trc = FALSE;\n\t}", "fail:\n\tCloseHandle(file);", "\tif (rc && (lowSize <= INT_MAX))\n\t{\n\t\tint blen = 0;\n\t\tcrypto_base64_decode(fdata, (int)lowSize, (BYTE**)data, &blen);", "\t\tif (*data && (blen > 0))\n\t\t\t*length = (UINT32)blen;\n\t\telse\n\t\t{\n\t\t\trc = FALSE;\n\t\t\t*length = 0;\n\t\t}\n\t}\n\telse\n\t{\n\t\t*length = 0;\n\t\t*data = NULL;\n\t}", "\tfree(fdata);\n\treturn rc;\n}", "static BOOL printer_save_to_config(const rdpSettings* settings, const char* PortDosName,\n size_t PortDosNameLen, const WCHAR* PnPName, size_t PnPNameLen,\n const WCHAR* DriverName, size_t DriverNameLen,\n const WCHAR* PrinterName, size_t PrintNameLen,\n const BYTE* CachedPrinterConfigData, size_t CacheFieldsLen)\n{\n\tBOOL rc = FALSE;\n\tchar* path = get_printer_config_path(settings, PrinterName, PrintNameLen);", "\tif (!path)\n\t\tgoto fail;", "\tif (!printer_write_setting(path, PRN_CONF_PORT, PortDosName, PortDosNameLen))\n\t\tgoto fail;", "\tif (!printer_write_setting(path, PRN_CONF_PNP, PnPName, PnPNameLen))\n\t\tgoto fail;", "\tif (!printer_write_setting(path, PRN_CONF_DRIVER, DriverName, DriverNameLen))\n\t\tgoto fail;", "\tif (!printer_write_setting(path, PRN_CONF_DATA, CachedPrinterConfigData, CacheFieldsLen))\n\t\tgoto fail;", "fail:\n\tfree(path);\n\treturn rc;\n}", "static BOOL printer_update_to_config(const rdpSettings* settings, const WCHAR* name, size_t length,\n const BYTE* data, size_t datalen)\n{\n\tBOOL rc = FALSE;\n\tchar* path = get_printer_config_path(settings, name, length);\n\trc = printer_write_setting(path, PRN_CONF_DATA, data, datalen);\n\tfree(path);\n\treturn rc;\n}", "static BOOL printer_remove_config(const rdpSettings* settings, const WCHAR* name, size_t length)\n{\n\tBOOL rc = FALSE;\n\tchar* path = get_printer_config_path(settings, name, length);", "\tif (!printer_config_valid(path))\n\t\tgoto fail;", "\trc = RemoveDirectoryA(path);\nfail:\n\tfree(path);\n\treturn rc;\n}", "static BOOL printer_move_config(const rdpSettings* settings, const WCHAR* oldName, size_t oldLength,\n const WCHAR* newName, size_t newLength)\n{\n\tBOOL rc = FALSE;\n\tchar* oldPath = get_printer_config_path(settings, oldName, oldLength);\n\tchar* newPath = get_printer_config_path(settings, newName, newLength);", "\tif (printer_config_valid(oldPath))\n\t\trc = MoveFileA(oldPath, newPath);", "\tfree(oldPath);\n\tfree(newPath);\n\treturn rc;\n}", "static BOOL printer_load_from_config(const rdpSettings* settings, rdpPrinter* printer,\n PRINTER_DEVICE* printer_dev)\n{\n\tBOOL res = FALSE;\n\tWCHAR* wname = NULL;\n\tsize_t wlen;\n\tchar* path = NULL;\n\tint rc;\n\tUINT32 flags = 0;\n\tvoid* DriverName = NULL;\n\tUINT32 DriverNameLen = 0;\n\tvoid* PnPName = NULL;\n\tUINT32 PnPNameLen = 0;\n\tvoid* CachedPrinterConfigData = NULL;\n\tUINT32 CachedFieldsLen = 0;\n\tUINT32 PrinterNameLen = 0;", "\tif (!settings || !printer)\n\t\treturn FALSE;", "\trc = ConvertToUnicode(CP_UTF8, 0, printer->name, -1, &wname, 0);", "\tif (rc <= 0)\n\t\tgoto fail;", "\twlen = _wcslen(wname) + 1;\n\tpath = get_printer_config_path(settings, wname, wlen * sizeof(WCHAR));\n\tPrinterNameLen = (wlen + 1) * sizeof(WCHAR);", "\tif (!path)\n\t\tgoto fail;", "\tif (printer->is_default)\n\t\tflags |= RDPDR_PRINTER_ANNOUNCE_FLAG_DEFAULTPRINTER;", "\tif (!printer_read_setting(path, PRN_CONF_PNP, &PnPName, &PnPNameLen))\n\t{\n\t}", "\tif (!printer_read_setting(path, PRN_CONF_DRIVER, &DriverName, &DriverNameLen))\n\t{\n\t\tDriverNameLen =\n\t\t ConvertToUnicode(CP_UTF8, 0, printer->driver, -1, (LPWSTR*)&DriverName, 0) * 2 + 1;\n\t}", "\tif (!printer_read_setting(path, PRN_CONF_DATA, &CachedPrinterConfigData, &CachedFieldsLen))\n\t{\n\t}", "\tStream_SetPosition(printer_dev->device.data, 0);", "\tif (!Stream_EnsureRemainingCapacity(printer_dev->device.data, 24))\n\t\tgoto fail;", "\tStream_Write_UINT32(printer_dev->device.data, flags);\n\tStream_Write_UINT32(printer_dev->device.data, 0); /* CodePage, reserved */\n\tStream_Write_UINT32(printer_dev->device.data, PnPNameLen); /* PnPNameLen */\n\tStream_Write_UINT32(printer_dev->device.data, DriverNameLen);\n\tStream_Write_UINT32(printer_dev->device.data, PrinterNameLen);\n\tStream_Write_UINT32(printer_dev->device.data, CachedFieldsLen);", "\tif (!Stream_EnsureRemainingCapacity(printer_dev->device.data, PnPNameLen))\n\t\tgoto fail;", "\tif (PnPNameLen > 0)\n\t\tStream_Write(printer_dev->device.data, PnPName, PnPNameLen);", "\tif (!Stream_EnsureRemainingCapacity(printer_dev->device.data, DriverNameLen))\n\t\tgoto fail;", "\tStream_Write(printer_dev->device.data, DriverName, DriverNameLen);", "\tif (!Stream_EnsureRemainingCapacity(printer_dev->device.data, PrinterNameLen))\n\t\tgoto fail;", "\tStream_Write(printer_dev->device.data, wname, PrinterNameLen);", "\tif (!Stream_EnsureRemainingCapacity(printer_dev->device.data, CachedFieldsLen))\n\t\tgoto fail;", "\tStream_Write(printer_dev->device.data, CachedPrinterConfigData, CachedFieldsLen);\n\tres = TRUE;\nfail:\n\tfree(path);\n\tfree(wname);\n\tfree(PnPName);\n\tfree(DriverName);\n\tfree(CachedPrinterConfigData);\n\treturn res;\n}", "static BOOL printer_save_default_config(const rdpSettings* settings, rdpPrinter* printer)\n{\n\tBOOL res = FALSE;\n\tWCHAR* wname = NULL;\n\tWCHAR* driver = NULL;\n\tsize_t wlen, dlen;\n\tchar* path = NULL;\n\tint rc;", "\tif (!settings || !printer)\n\t\treturn FALSE;", "\trc = ConvertToUnicode(CP_UTF8, 0, printer->name, -1, &wname, 0);", "\tif (rc <= 0)\n\t\tgoto fail;", "\trc = ConvertToUnicode(CP_UTF8, 0, printer->driver, -1, &driver, 0);", "\tif (rc <= 0)\n\t\tgoto fail;", "\twlen = _wcslen(wname) + 1;\n\tdlen = _wcslen(driver) + 1;\n\tpath = get_printer_config_path(settings, wname, wlen * sizeof(WCHAR));", "\tif (!path)\n\t\tgoto fail;", "\tif (dlen > 1)\n\t{\n\t\tif (!printer_write_setting(path, PRN_CONF_DRIVER, driver, dlen * sizeof(WCHAR)))\n\t\t\tgoto fail;\n\t}", "\tres = TRUE;\nfail:\n\tfree(path);\n\tfree(wname);\n\tfree(driver);\n\treturn res;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT printer_process_irp_create(PRINTER_DEVICE* printer_dev, IRP* irp)\n{\n\trdpPrintJob* printjob = NULL;", "\tif (printer_dev->printer)\n\t\tprintjob =\n\t\t printer_dev->printer->CreatePrintJob(printer_dev->printer, irp->devman->id_sequence++);", "\tif (printjob)\n\t{\n\t\tStream_Write_UINT32(irp->output, printjob->id); /* FileId */\n\t}\n\telse\n\t{\n\t\tStream_Write_UINT32(irp->output, 0); /* FileId */\n\t\tirp->IoStatus = STATUS_PRINT_QUEUE_FULL;\n\t}", "\treturn irp->Complete(irp);\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT printer_process_irp_close(PRINTER_DEVICE* printer_dev, IRP* irp)\n{\n\trdpPrintJob* printjob = NULL;", "\tif (printer_dev->printer)\n\t\tprintjob = printer_dev->printer->FindPrintJob(printer_dev->printer, irp->FileId);", "\tif (!printjob)\n\t{\n\t\tirp->IoStatus = STATUS_UNSUCCESSFUL;\n\t}\n\telse\n\t{\n\t\tprintjob->Close(printjob);\n\t}", "\tStream_Zero(irp->output, 4); /* Padding(4) */\n\treturn irp->Complete(irp);\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT printer_process_irp_write(PRINTER_DEVICE* printer_dev, IRP* irp)\n{\n\tUINT32 Length;\n\tUINT64 Offset;\n\trdpPrintJob* printjob = NULL;\n\tUINT error = CHANNEL_RC_OK;", "", "\tStream_Read_UINT32(irp->input, Length);\n\tStream_Read_UINT64(irp->input, Offset);\n\tStream_Seek(irp->input, 20); /* Padding */", "", "\tif (printer_dev->printer)\n\t\tprintjob = printer_dev->printer->FindPrintJob(printer_dev->printer, irp->FileId);", "\tif (!printjob)\n\t{\n\t\tirp->IoStatus = STATUS_UNSUCCESSFUL;\n\t\tLength = 0;\n\t}\n\telse\n\t{", "\t\terror = printjob->Write(printjob, Stream_Pointer(irp->input), Length);", "\t}", "\tif (error)\n\t{\n\t\tWLog_ERR(TAG, \"printjob->Write failed with error %\" PRIu32 \"!\", error);\n\t\treturn error;\n\t}", "\tStream_Write_UINT32(irp->output, Length);\n\tStream_Write_UINT8(irp->output, 0); /* Padding */\n\treturn irp->Complete(irp);\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT printer_process_irp_device_control(PRINTER_DEVICE* printer_dev, IRP* irp)\n{\n\tStream_Write_UINT32(irp->output, 0); /* OutputBufferLength */\n\treturn irp->Complete(irp);\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT printer_process_irp(PRINTER_DEVICE* printer_dev, IRP* irp)\n{\n\tUINT error;", "\tswitch (irp->MajorFunction)\n\t{\n\t\tcase IRP_MJ_CREATE:\n\t\t\tif ((error = printer_process_irp_create(printer_dev, irp)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"printer_process_irp_create failed with error %\" PRIu32 \"!\", error);\n\t\t\t\treturn error;\n\t\t\t}", "\t\t\tbreak;", "\t\tcase IRP_MJ_CLOSE:\n\t\t\tif ((error = printer_process_irp_close(printer_dev, irp)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"printer_process_irp_close failed with error %\" PRIu32 \"!\", error);\n\t\t\t\treturn error;\n\t\t\t}", "\t\t\tbreak;", "\t\tcase IRP_MJ_WRITE:\n\t\t\tif ((error = printer_process_irp_write(printer_dev, irp)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"printer_process_irp_write failed with error %\" PRIu32 \"!\", error);\n\t\t\t\treturn error;\n\t\t\t}", "\t\t\tbreak;", "\t\tcase IRP_MJ_DEVICE_CONTROL:\n\t\t\tif ((error = printer_process_irp_device_control(printer_dev, irp)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"printer_process_irp_device_control failed with error %\" PRIu32 \"!\",\n\t\t\t\t error);\n\t\t\t\treturn error;\n\t\t\t}", "\t\t\tbreak;", "\t\tdefault:\n\t\t\tirp->IoStatus = STATUS_NOT_SUPPORTED;\n\t\t\treturn irp->Complete(irp);\n\t\t\tbreak;\n\t}", "\treturn CHANNEL_RC_OK;\n}", "static DWORD WINAPI printer_thread_func(LPVOID arg)\n{\n\tIRP* irp;\n\tPRINTER_DEVICE* printer_dev = (PRINTER_DEVICE*)arg;\n\tHANDLE obj[] = { printer_dev->event, printer_dev->stopEvent };\n\tUINT error = CHANNEL_RC_OK;", "\twhile (1)\n\t{\n\t\tDWORD rc = WaitForMultipleObjects(2, obj, FALSE, INFINITE);", "\t\tif (rc == WAIT_FAILED)\n\t\t{\n\t\t\terror = GetLastError();\n\t\t\tWLog_ERR(TAG, \"WaitForMultipleObjects failed with error %\" PRIu32 \"!\", error);\n\t\t\tbreak;\n\t\t}", "\t\tif (rc == WAIT_OBJECT_0 + 1)\n\t\t\tbreak;\n\t\telse if (rc != WAIT_OBJECT_0)\n\t\t\tcontinue;", "\t\tResetEvent(printer_dev->event);\n\t\tirp = (IRP*)InterlockedPopEntrySList(printer_dev->pIrpList);", "\t\tif (irp == NULL)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"InterlockedPopEntrySList failed!\");\n\t\t\terror = ERROR_INTERNAL_ERROR;\n\t\t\tbreak;\n\t\t}", "\t\tif ((error = printer_process_irp(printer_dev, irp)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"printer_process_irp failed with error %\" PRIu32 \"!\", error);\n\t\t\tbreak;\n\t\t}\n\t}", "\tif (error && printer_dev->rdpcontext)\n\t\tsetChannelError(printer_dev->rdpcontext, error, \"printer_thread_func reported an error\");", "\tExitThread(error);\n\treturn error;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT printer_irp_request(DEVICE* device, IRP* irp)\n{\n\tPRINTER_DEVICE* printer_dev = (PRINTER_DEVICE*)device;\n\tInterlockedPushEntrySList(printer_dev->pIrpList, &(irp->ItemEntry));\n\tSetEvent(printer_dev->event);\n\treturn CHANNEL_RC_OK;\n}", "static UINT printer_custom_component(DEVICE* device, UINT16 component, UINT16 packetId, wStream* s)\n{\n\tUINT32 eventID;\n\tPRINTER_DEVICE* printer_dev = (PRINTER_DEVICE*)device;\n\tconst rdpSettings* settings = printer_dev->rdpcontext->settings;", "\tif (component != RDPDR_CTYP_PRN)\n\t\treturn ERROR_INVALID_DATA;", "\tif (Stream_GetRemainingLength(s) < 4)\n\t\treturn ERROR_INVALID_DATA;", "\tStream_Read_UINT32(s, eventID);", "\tswitch (packetId)\n\t{\n\t\tcase PAKID_PRN_CACHE_DATA:\n\t\t\tswitch (eventID)\n\t\t\t{\n\t\t\t\tcase RDPDR_ADD_PRINTER_EVENT:\n\t\t\t\t{\n\t\t\t\t\tchar PortDosName[8];\n\t\t\t\t\tUINT32 PnPNameLen, DriverNameLen, PrintNameLen, CacheFieldsLen;\n\t\t\t\t\tconst WCHAR *PnPName, *DriverName, *PrinterName;\n\t\t\t\t\tconst BYTE* CachedPrinterConfigData;", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < 24)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tStream_Read(s, PortDosName, sizeof(PortDosName));\n\t\t\t\t\tStream_Read_UINT32(s, PnPNameLen);\n\t\t\t\t\tStream_Read_UINT32(s, DriverNameLen);\n\t\t\t\t\tStream_Read_UINT32(s, PrintNameLen);\n\t\t\t\t\tStream_Read_UINT32(s, CacheFieldsLen);", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < PnPNameLen)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tPnPName = (const WCHAR*)Stream_Pointer(s);\n\t\t\t\t\tStream_Seek(s, PnPNameLen);", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < DriverNameLen)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tDriverName = (const WCHAR*)Stream_Pointer(s);\n\t\t\t\t\tStream_Seek(s, DriverNameLen);", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < PrintNameLen)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tPrinterName = (const WCHAR*)Stream_Pointer(s);\n\t\t\t\t\tStream_Seek(s, PrintNameLen);", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < CacheFieldsLen)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tCachedPrinterConfigData = Stream_Pointer(s);\n\t\t\t\t\tStream_Seek(s, CacheFieldsLen);", "\t\t\t\t\tif (!printer_save_to_config(settings, PortDosName, sizeof(PortDosName), PnPName,\n\t\t\t\t\t PnPNameLen, DriverName, DriverNameLen, PrinterName,\n\t\t\t\t\t PrintNameLen, CachedPrinterConfigData,\n\t\t\t\t\t CacheFieldsLen))\n\t\t\t\t\t\treturn ERROR_INTERNAL_ERROR;\n\t\t\t\t}\n\t\t\t\tbreak;", "\t\t\t\tcase RDPDR_UPDATE_PRINTER_EVENT:\n\t\t\t\t{\n\t\t\t\t\tUINT32 PrinterNameLen, ConfigDataLen;\n\t\t\t\t\tconst WCHAR* PrinterName;\n\t\t\t\t\tconst BYTE* ConfigData;", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < 8)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tStream_Read_UINT32(s, PrinterNameLen);\n\t\t\t\t\tStream_Read_UINT32(s, ConfigDataLen);", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < PrinterNameLen)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tPrinterName = (const WCHAR*)Stream_Pointer(s);\n\t\t\t\t\tStream_Seek(s, PrinterNameLen);", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < ConfigDataLen)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tConfigData = Stream_Pointer(s);\n\t\t\t\t\tStream_Seek(s, ConfigDataLen);", "\t\t\t\t\tif (!printer_update_to_config(settings, PrinterName, PrinterNameLen, ConfigData,\n\t\t\t\t\t ConfigDataLen))\n\t\t\t\t\t\treturn ERROR_INTERNAL_ERROR;\n\t\t\t\t}\n\t\t\t\tbreak;", "\t\t\t\tcase RDPDR_DELETE_PRINTER_EVENT:\n\t\t\t\t{\n\t\t\t\t\tUINT32 PrinterNameLen;\n\t\t\t\t\tconst WCHAR* PrinterName;", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < 4)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tStream_Read_UINT32(s, PrinterNameLen);", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < PrinterNameLen)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tPrinterName = (const WCHAR*)Stream_Pointer(s);\n\t\t\t\t\tStream_Seek(s, PrinterNameLen);\n\t\t\t\t\tprinter_remove_config(settings, PrinterName, PrinterNameLen);\n\t\t\t\t}\n\t\t\t\tbreak;", "\t\t\t\tcase RDPDR_RENAME_PRINTER_EVENT:\n\t\t\t\t{\n\t\t\t\t\tUINT32 OldPrinterNameLen, NewPrinterNameLen;\n\t\t\t\t\tconst WCHAR* OldPrinterName;\n\t\t\t\t\tconst WCHAR* NewPrinterName;", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < 8)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tStream_Read_UINT32(s, OldPrinterNameLen);\n\t\t\t\t\tStream_Read_UINT32(s, NewPrinterNameLen);", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < OldPrinterNameLen)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tOldPrinterName = (const WCHAR*)Stream_Pointer(s);\n\t\t\t\t\tStream_Seek(s, OldPrinterNameLen);", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < NewPrinterNameLen)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tNewPrinterName = (const WCHAR*)Stream_Pointer(s);\n\t\t\t\t\tStream_Seek(s, NewPrinterNameLen);", "\t\t\t\t\tif (!printer_move_config(settings, OldPrinterName, OldPrinterNameLen,\n\t\t\t\t\t NewPrinterName, NewPrinterNameLen))\n\t\t\t\t\t\treturn ERROR_INTERNAL_ERROR;\n\t\t\t\t}\n\t\t\t\tbreak;", "\t\t\t\tdefault:\n\t\t\t\t\tWLog_ERR(TAG, \"Unknown cache data eventID: 0x%08\" PRIX32 \"\", eventID);\n\t\t\t\t\treturn ERROR_INVALID_DATA;\n\t\t\t}", "\t\t\tbreak;", "\t\tcase PAKID_PRN_USING_XPS:\n\t\t{\n\t\t\tUINT32 flags;", "\t\t\tif (Stream_GetRemainingLength(s) < 4)\n\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\tStream_Read_UINT32(s, flags);\n\t\t\tWLog_ERR(TAG,\n\t\t\t \"Ignoring unhandled message PAKID_PRN_USING_XPS [printerID=%08\" PRIx32\n\t\t\t \", flags=%08\" PRIx32 \"]\",\n\t\t\t eventID, flags);\n\t\t}\n\t\tbreak;", "\t\tdefault:\n\t\t\tWLog_ERR(TAG, \"Unknown printing component packetID: 0x%04\" PRIX16 \"\", packetId);\n\t\t\treturn ERROR_INVALID_DATA;\n\t}", "\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT printer_free(DEVICE* device)\n{\n\tIRP* irp;\n\tPRINTER_DEVICE* printer_dev = (PRINTER_DEVICE*)device;\n\tUINT error;\n\tSetEvent(printer_dev->stopEvent);", "\tif (WaitForSingleObject(printer_dev->thread, INFINITE) == WAIT_FAILED)\n\t{\n\t\terror = GetLastError();\n\t\tWLog_ERR(TAG, \"WaitForSingleObject failed with error %\" PRIu32 \"\", error);", "\t\t/* The analyzer is confused by this premature return value.\n\t\t * Since this case can not be handled gracefully silence the\n\t\t * analyzer here. */\n#ifndef __clang_analyzer__\n\t\treturn error;\n#endif\n\t}", "\twhile ((irp = (IRP*)InterlockedPopEntrySList(printer_dev->pIrpList)) != NULL)\n\t\tirp->Discard(irp);", "\tCloseHandle(printer_dev->thread);\n\tCloseHandle(printer_dev->stopEvent);\n\tCloseHandle(printer_dev->event);\n\t_aligned_free(printer_dev->pIrpList);", "\tif (printer_dev->printer)\n\t\tprinter_dev->printer->ReleaseRef(printer_dev->printer);", "\tStream_Free(printer_dev->device.data, TRUE);\n\tfree(printer_dev);\n\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT printer_register(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints, rdpPrinter* printer)\n{\n\tPRINTER_DEVICE* printer_dev;\n\tUINT error = ERROR_INTERNAL_ERROR;\n\tprinter_dev = (PRINTER_DEVICE*)calloc(1, sizeof(PRINTER_DEVICE));", "\tif (!printer_dev)\n\t{\n\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\treturn CHANNEL_RC_NO_MEMORY;\n\t}", "\tprinter_dev->device.data = Stream_New(NULL, 1024);", "\tif (!printer_dev->device.data)\n\t\tgoto error_out;", "\tsprintf_s(printer_dev->port, sizeof(printer_dev->port), \"PRN%\" PRIdz, printer->id);\n\tprinter_dev->device.type = RDPDR_DTYP_PRINT;\n\tprinter_dev->device.name = printer_dev->port;\n\tprinter_dev->device.IRPRequest = printer_irp_request;\n\tprinter_dev->device.CustomComponentRequest = printer_custom_component;\n\tprinter_dev->device.Free = printer_free;\n\tprinter_dev->rdpcontext = pEntryPoints->rdpcontext;\n\tprinter_dev->printer = printer;\n\tprinter_dev->pIrpList = (WINPR_PSLIST_HEADER)_aligned_malloc(sizeof(WINPR_SLIST_HEADER),\n\t MEMORY_ALLOCATION_ALIGNMENT);", "\tif (!printer_dev->pIrpList)\n\t{\n\t\tWLog_ERR(TAG, \"_aligned_malloc failed!\");\n\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\tgoto error_out;\n\t}", "\tif (!printer_load_from_config(pEntryPoints->rdpcontext->settings, printer, printer_dev))\n\t\tgoto error_out;", "\tInitializeSListHead(printer_dev->pIrpList);", "\tif (!(printer_dev->event = CreateEvent(NULL, TRUE, FALSE, NULL)))\n\t{\n\t\tWLog_ERR(TAG, \"CreateEvent failed!\");\n\t\terror = ERROR_INTERNAL_ERROR;\n\t\tgoto error_out;\n\t}", "\tif (!(printer_dev->stopEvent = CreateEvent(NULL, TRUE, FALSE, NULL)))\n\t{\n\t\tWLog_ERR(TAG, \"CreateEvent failed!\");\n\t\terror = ERROR_INTERNAL_ERROR;\n\t\tgoto error_out;\n\t}", "\tif ((error = pEntryPoints->RegisterDevice(pEntryPoints->devman, (DEVICE*)printer_dev)))\n\t{\n\t\tWLog_ERR(TAG, \"RegisterDevice failed with error %\" PRIu32 \"!\", error);\n\t\tgoto error_out;\n\t}", "\tif (!(printer_dev->thread =\n\t CreateThread(NULL, 0, printer_thread_func, (void*)printer_dev, 0, NULL)))\n\t{\n\t\tWLog_ERR(TAG, \"CreateThread failed!\");\n\t\terror = ERROR_INTERNAL_ERROR;\n\t\tgoto error_out;\n\t}", "\tprinter->AddRef(printer);\n\treturn CHANNEL_RC_OK;\nerror_out:\n\tprinter_free(&printer_dev->device);\n\treturn error;\n}", "static rdpPrinterDriver* printer_load_backend(const char* backend)\n{\n\ttypedef rdpPrinterDriver* (*backend_load_t)(void);\n\tunion {\n\t\tPVIRTUALCHANNELENTRY entry;\n\t\tbackend_load_t backend;\n\t} fktconv;", "\tfktconv.entry = freerdp_load_channel_addin_entry(\"printer\", backend, NULL, 0);\n\tif (!fktconv.entry)\n\t\treturn NULL;", "\treturn fktconv.backend();\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nUINT\n#ifdef BUILTIN_CHANNELS\nprinter_DeviceServiceEntry\n#else\n FREERDP_API\n DeviceServiceEntry\n#endif\n (PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints)\n{\n\tint i;\n\tchar* name;\n\tchar* driver_name;\n\tBOOL default_backend = TRUE;\n\tRDPDR_PRINTER* device = NULL;\n\trdpPrinterDriver* driver = NULL;\n\tUINT error = CHANNEL_RC_OK;", "\tif (!pEntryPoints || !pEntryPoints->device)\n\t\treturn ERROR_INVALID_PARAMETER;", "\tdevice = (RDPDR_PRINTER*)pEntryPoints->device;\n\tname = device->Name;\n\tdriver_name = device->DriverName;", "\t/* Secondary argument is one of the following:\n\t *\n\t * <driver_name> ... name of a printer driver\n\t * <driver_name>:<backend_name> ... name of a printer driver and local printer backend to use\n\t */\n\tif (driver_name)\n\t{\n\t\tchar* sep = strstr(driver_name, \":\");\n\t\tif (sep)\n\t\t{\n\t\t\tconst char* backend = sep + 1;\n\t\t\t*sep = '\\0';\n\t\t\tdriver = printer_load_backend(backend);\n\t\t\tdefault_backend = FALSE;\n\t\t}\n\t}", "\tif (!driver && default_backend)\n\t{\n\t\tconst char* backend =\n#if defined(WITH_CUPS)\n\t\t \"cups\"\n#elif defined(_WIN32)\n\t\t \"win\"\n#else\n\t\t \"\"\n#endif\n\t\t ;", "\t\tdriver = printer_load_backend(backend);\n\t}", "\tif (!driver)\n\t{\n\t\tWLog_ERR(TAG, \"Could not get a printer driver!\");\n\t\treturn CHANNEL_RC_INITIALIZATION_ERROR;\n\t}", "\tif (name && name[0])\n\t{\n\t\trdpPrinter* printer = driver->GetPrinter(driver, name, driver_name);", "\t\tif (!printer)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"Could not get printer %s!\", name);\n\t\t\terror = CHANNEL_RC_INITIALIZATION_ERROR;\n\t\t\tgoto fail;\n\t\t}", "\t\tif (!printer_save_default_config(pEntryPoints->rdpcontext->settings, printer))\n\t\t{\n\t\t\terror = CHANNEL_RC_INITIALIZATION_ERROR;\n\t\t\tprinter->ReleaseRef(printer);\n\t\t\tgoto fail;\n\t\t}", "\t\tif ((error = printer_register(pEntryPoints, printer)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"printer_register failed with error %\" PRIu32 \"!\", error);\n\t\t\tprinter->ReleaseRef(printer);\n\t\t\tgoto fail;\n\t\t}\n\t}\n\telse\n\t{\n\t\trdpPrinter** printers = driver->EnumPrinters(driver);\n\t\trdpPrinter** current = printers;", "\t\tfor (i = 0; current[i]; i++)\n\t\t{\n\t\t\trdpPrinter* printer = current[i];", "\t\t\tif ((error = printer_register(pEntryPoints, printer)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"printer_register failed with error %\" PRIu32 \"!\", error);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}", "\t\tdriver->ReleaseEnumPrinters(printers);\n\t}", "fail:\n\tdriver->ReleaseRef(driver);", "\treturn error;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [357, 496, 447, 322, 308, 1001], "buggy_code_start_loc": [333, 480, 447, 145, 307, 94], "filenames": ["channels/drive/client/drive_main.c", "channels/printer/client/printer_main.c", "channels/rdpei/client/rdpei_main.c", "channels/serial/client/serial_main.c", "libfreerdp/core/gateway/rdg.c", "libfreerdp/core/nego.c"], "fixing_code_end_loc": [361, 502, 451, 327, 309, 1013], "fixing_code_start_loc": [334, 481, 448, 145, 307, 94], "message": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:freerdp:freerdp:*:*:*:*:*:*:*:*", "matchCriteriaId": "5C5F8D57-1D22-42B4-9E08-9131F7BE8FA5", "versionEndExcluding": "2.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "B620311B-34A3-48A6-82DF-6F078D7A4493", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0."}, {"lang": "es", "value": "En FreeRDP versiones anteriores a 2.1.0, se presenta una lectura fuera de l\u00edmite en las funciones de irp (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). Esto ha sido corregido en la versi\u00f3n 2.1.0."}], "evaluatorComment": null, "id": "CVE-2020-11089", "lastModified": "2022-07-19T11:52:15.420", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:L/I:L/A:L", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 2.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-05-29T20:15:11.017", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2020-07/msg00080.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/795842f4096501fcefc1a7f535ccc8132feb31d7"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/security/advisories/GHSA-hfc7-c5gv-8c2h"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-125"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, "type": "CWE-125"}
320
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * FreeRDP: A Remote Desktop Protocol Implementation\n * Print Virtual Channel\n *\n * Copyright 2010-2011 Vic Lee\n * Copyright 2015 Thincast Technologies GmbH\n * Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>\n * Copyright 2016 Armin Novak <armin.novak@gmail.com>\n * Copyright 2016 David PHAM-VAN <d.phamvan@inuvika.com>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */", "#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif", "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>", "#include <winpr/crt.h>\n#include <winpr/string.h>\n#include <winpr/synch.h>\n#include <winpr/thread.h>\n#include <winpr/stream.h>\n#include <winpr/interlocked.h>\n#include <winpr/path.h>", "#include <freerdp/channels/rdpdr.h>\n#include <freerdp/crypto/crypto.h>", "#include \"../printer.h\"", "#include <freerdp/client/printer.h>", "#include <freerdp/channels/log.h>", "#define TAG CHANNELS_TAG(\"printer.client\")", "typedef struct _PRINTER_DEVICE PRINTER_DEVICE;\nstruct _PRINTER_DEVICE\n{\n\tDEVICE device;", "\trdpPrinter* printer;", "\tWINPR_PSLIST_HEADER pIrpList;", "\tHANDLE event;\n\tHANDLE stopEvent;", "\tHANDLE thread;\n\trdpContext* rdpcontext;\n\tchar port[64];\n};", "typedef enum\n{\n\tPRN_CONF_PORT = 0,\n\tPRN_CONF_PNP = 1,\n\tPRN_CONF_DRIVER = 2,\n\tPRN_CONF_DATA = 3\n} prn_conf_t;", "static const char* filemap[] = { \"PortDosName\", \"PnPName\", \"DriverName\",\n\t \"CachedPrinterConfigData\" };", "static char* get_printer_config_path(const rdpSettings* settings, const WCHAR* name, size_t length)\n{\n\tchar* dir = GetCombinedPath(settings->ConfigPath, \"printers\");\n\tchar* bname = crypto_base64_encode((const BYTE*)name, (int)length);\n\tchar* config = GetCombinedPath(dir, bname);", "\tif (config && !PathFileExistsA(config))\n\t{\n\t\tif (!PathMakePathA(config, NULL))\n\t\t{\n\t\t\tfree(config);\n\t\t\tconfig = NULL;\n\t\t}\n\t}", "\tfree(dir);\n\tfree(bname);\n\treturn config;\n}", "static BOOL printer_write_setting(const char* path, prn_conf_t type, const void* data,\n size_t length)\n{\n\tDWORD written = 0;\n\tBOOL rc = FALSE;\n\tHANDLE file;\n\tsize_t b64len;\n\tchar* base64 = NULL;\n\tconst char* name = filemap[type];\n\tchar* abs = GetCombinedPath(path, name);", "\tif (!abs)\n\t\treturn FALSE;", "\tfile = CreateFileA(abs, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\n\tfree(abs);", "\tif (file == INVALID_HANDLE_VALUE)\n\t\treturn FALSE;", "\tif (length > 0)\n\t{\n\t\tbase64 = crypto_base64_encode(data, length);", "\t\tif (!base64)\n\t\t\tgoto fail;", "\t\t/* base64 char represents 6bit -> 4*(n/3) is the length which is\n\t\t * always smaller than 2*n */\n\t\tb64len = strnlen(base64, 2 * length);\n\t\trc = WriteFile(file, base64, b64len, &written, NULL);", "\t\tif (b64len != written)\n\t\t\trc = FALSE;\n\t}\n\telse\n\t\trc = TRUE;", "fail:\n\tCloseHandle(file);\n\tfree(base64);\n\treturn rc;\n}", "static BOOL printer_config_valid(const char* path)\n{\n\tif (!path)\n\t\treturn FALSE;", "\tif (!PathFileExistsA(path))\n\t\treturn FALSE;", "\treturn TRUE;\n}", "static BOOL printer_read_setting(const char* path, prn_conf_t type, void** data, UINT32* length)\n{\n\tDWORD lowSize, highSize;\n\tDWORD read = 0;\n\tBOOL rc = FALSE;\n\tHANDLE file;\n\tchar* fdata = NULL;\n\tconst char* name = filemap[type];\n\tchar* abs = GetCombinedPath(path, name);", "\tif (!abs)\n\t\treturn FALSE;", "\tfile = CreateFileA(abs, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);\n\tfree(abs);", "\tif (file == INVALID_HANDLE_VALUE)\n\t\treturn FALSE;", "\tlowSize = GetFileSize(file, &highSize);", "\tif ((lowSize == INVALID_FILE_SIZE) || (highSize != 0))\n\t\tgoto fail;", "\tif (lowSize != 0)\n\t{\n\t\tfdata = malloc(lowSize);", "\t\tif (!fdata)\n\t\t\tgoto fail;", "\t\trc = ReadFile(file, fdata, lowSize, &read, NULL);", "\t\tif (lowSize != read)\n\t\t\trc = FALSE;\n\t}", "fail:\n\tCloseHandle(file);", "\tif (rc && (lowSize <= INT_MAX))\n\t{\n\t\tint blen = 0;\n\t\tcrypto_base64_decode(fdata, (int)lowSize, (BYTE**)data, &blen);", "\t\tif (*data && (blen > 0))\n\t\t\t*length = (UINT32)blen;\n\t\telse\n\t\t{\n\t\t\trc = FALSE;\n\t\t\t*length = 0;\n\t\t}\n\t}\n\telse\n\t{\n\t\t*length = 0;\n\t\t*data = NULL;\n\t}", "\tfree(fdata);\n\treturn rc;\n}", "static BOOL printer_save_to_config(const rdpSettings* settings, const char* PortDosName,\n size_t PortDosNameLen, const WCHAR* PnPName, size_t PnPNameLen,\n const WCHAR* DriverName, size_t DriverNameLen,\n const WCHAR* PrinterName, size_t PrintNameLen,\n const BYTE* CachedPrinterConfigData, size_t CacheFieldsLen)\n{\n\tBOOL rc = FALSE;\n\tchar* path = get_printer_config_path(settings, PrinterName, PrintNameLen);", "\tif (!path)\n\t\tgoto fail;", "\tif (!printer_write_setting(path, PRN_CONF_PORT, PortDosName, PortDosNameLen))\n\t\tgoto fail;", "\tif (!printer_write_setting(path, PRN_CONF_PNP, PnPName, PnPNameLen))\n\t\tgoto fail;", "\tif (!printer_write_setting(path, PRN_CONF_DRIVER, DriverName, DriverNameLen))\n\t\tgoto fail;", "\tif (!printer_write_setting(path, PRN_CONF_DATA, CachedPrinterConfigData, CacheFieldsLen))\n\t\tgoto fail;", "fail:\n\tfree(path);\n\treturn rc;\n}", "static BOOL printer_update_to_config(const rdpSettings* settings, const WCHAR* name, size_t length,\n const BYTE* data, size_t datalen)\n{\n\tBOOL rc = FALSE;\n\tchar* path = get_printer_config_path(settings, name, length);\n\trc = printer_write_setting(path, PRN_CONF_DATA, data, datalen);\n\tfree(path);\n\treturn rc;\n}", "static BOOL printer_remove_config(const rdpSettings* settings, const WCHAR* name, size_t length)\n{\n\tBOOL rc = FALSE;\n\tchar* path = get_printer_config_path(settings, name, length);", "\tif (!printer_config_valid(path))\n\t\tgoto fail;", "\trc = RemoveDirectoryA(path);\nfail:\n\tfree(path);\n\treturn rc;\n}", "static BOOL printer_move_config(const rdpSettings* settings, const WCHAR* oldName, size_t oldLength,\n const WCHAR* newName, size_t newLength)\n{\n\tBOOL rc = FALSE;\n\tchar* oldPath = get_printer_config_path(settings, oldName, oldLength);\n\tchar* newPath = get_printer_config_path(settings, newName, newLength);", "\tif (printer_config_valid(oldPath))\n\t\trc = MoveFileA(oldPath, newPath);", "\tfree(oldPath);\n\tfree(newPath);\n\treturn rc;\n}", "static BOOL printer_load_from_config(const rdpSettings* settings, rdpPrinter* printer,\n PRINTER_DEVICE* printer_dev)\n{\n\tBOOL res = FALSE;\n\tWCHAR* wname = NULL;\n\tsize_t wlen;\n\tchar* path = NULL;\n\tint rc;\n\tUINT32 flags = 0;\n\tvoid* DriverName = NULL;\n\tUINT32 DriverNameLen = 0;\n\tvoid* PnPName = NULL;\n\tUINT32 PnPNameLen = 0;\n\tvoid* CachedPrinterConfigData = NULL;\n\tUINT32 CachedFieldsLen = 0;\n\tUINT32 PrinterNameLen = 0;", "\tif (!settings || !printer)\n\t\treturn FALSE;", "\trc = ConvertToUnicode(CP_UTF8, 0, printer->name, -1, &wname, 0);", "\tif (rc <= 0)\n\t\tgoto fail;", "\twlen = _wcslen(wname) + 1;\n\tpath = get_printer_config_path(settings, wname, wlen * sizeof(WCHAR));\n\tPrinterNameLen = (wlen + 1) * sizeof(WCHAR);", "\tif (!path)\n\t\tgoto fail;", "\tif (printer->is_default)\n\t\tflags |= RDPDR_PRINTER_ANNOUNCE_FLAG_DEFAULTPRINTER;", "\tif (!printer_read_setting(path, PRN_CONF_PNP, &PnPName, &PnPNameLen))\n\t{\n\t}", "\tif (!printer_read_setting(path, PRN_CONF_DRIVER, &DriverName, &DriverNameLen))\n\t{\n\t\tDriverNameLen =\n\t\t ConvertToUnicode(CP_UTF8, 0, printer->driver, -1, (LPWSTR*)&DriverName, 0) * 2 + 1;\n\t}", "\tif (!printer_read_setting(path, PRN_CONF_DATA, &CachedPrinterConfigData, &CachedFieldsLen))\n\t{\n\t}", "\tStream_SetPosition(printer_dev->device.data, 0);", "\tif (!Stream_EnsureRemainingCapacity(printer_dev->device.data, 24))\n\t\tgoto fail;", "\tStream_Write_UINT32(printer_dev->device.data, flags);\n\tStream_Write_UINT32(printer_dev->device.data, 0); /* CodePage, reserved */\n\tStream_Write_UINT32(printer_dev->device.data, PnPNameLen); /* PnPNameLen */\n\tStream_Write_UINT32(printer_dev->device.data, DriverNameLen);\n\tStream_Write_UINT32(printer_dev->device.data, PrinterNameLen);\n\tStream_Write_UINT32(printer_dev->device.data, CachedFieldsLen);", "\tif (!Stream_EnsureRemainingCapacity(printer_dev->device.data, PnPNameLen))\n\t\tgoto fail;", "\tif (PnPNameLen > 0)\n\t\tStream_Write(printer_dev->device.data, PnPName, PnPNameLen);", "\tif (!Stream_EnsureRemainingCapacity(printer_dev->device.data, DriverNameLen))\n\t\tgoto fail;", "\tStream_Write(printer_dev->device.data, DriverName, DriverNameLen);", "\tif (!Stream_EnsureRemainingCapacity(printer_dev->device.data, PrinterNameLen))\n\t\tgoto fail;", "\tStream_Write(printer_dev->device.data, wname, PrinterNameLen);", "\tif (!Stream_EnsureRemainingCapacity(printer_dev->device.data, CachedFieldsLen))\n\t\tgoto fail;", "\tStream_Write(printer_dev->device.data, CachedPrinterConfigData, CachedFieldsLen);\n\tres = TRUE;\nfail:\n\tfree(path);\n\tfree(wname);\n\tfree(PnPName);\n\tfree(DriverName);\n\tfree(CachedPrinterConfigData);\n\treturn res;\n}", "static BOOL printer_save_default_config(const rdpSettings* settings, rdpPrinter* printer)\n{\n\tBOOL res = FALSE;\n\tWCHAR* wname = NULL;\n\tWCHAR* driver = NULL;\n\tsize_t wlen, dlen;\n\tchar* path = NULL;\n\tint rc;", "\tif (!settings || !printer)\n\t\treturn FALSE;", "\trc = ConvertToUnicode(CP_UTF8, 0, printer->name, -1, &wname, 0);", "\tif (rc <= 0)\n\t\tgoto fail;", "\trc = ConvertToUnicode(CP_UTF8, 0, printer->driver, -1, &driver, 0);", "\tif (rc <= 0)\n\t\tgoto fail;", "\twlen = _wcslen(wname) + 1;\n\tdlen = _wcslen(driver) + 1;\n\tpath = get_printer_config_path(settings, wname, wlen * sizeof(WCHAR));", "\tif (!path)\n\t\tgoto fail;", "\tif (dlen > 1)\n\t{\n\t\tif (!printer_write_setting(path, PRN_CONF_DRIVER, driver, dlen * sizeof(WCHAR)))\n\t\t\tgoto fail;\n\t}", "\tres = TRUE;\nfail:\n\tfree(path);\n\tfree(wname);\n\tfree(driver);\n\treturn res;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT printer_process_irp_create(PRINTER_DEVICE* printer_dev, IRP* irp)\n{\n\trdpPrintJob* printjob = NULL;", "\tif (printer_dev->printer)\n\t\tprintjob =\n\t\t printer_dev->printer->CreatePrintJob(printer_dev->printer, irp->devman->id_sequence++);", "\tif (printjob)\n\t{\n\t\tStream_Write_UINT32(irp->output, printjob->id); /* FileId */\n\t}\n\telse\n\t{\n\t\tStream_Write_UINT32(irp->output, 0); /* FileId */\n\t\tirp->IoStatus = STATUS_PRINT_QUEUE_FULL;\n\t}", "\treturn irp->Complete(irp);\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT printer_process_irp_close(PRINTER_DEVICE* printer_dev, IRP* irp)\n{\n\trdpPrintJob* printjob = NULL;", "\tif (printer_dev->printer)\n\t\tprintjob = printer_dev->printer->FindPrintJob(printer_dev->printer, irp->FileId);", "\tif (!printjob)\n\t{\n\t\tirp->IoStatus = STATUS_UNSUCCESSFUL;\n\t}\n\telse\n\t{\n\t\tprintjob->Close(printjob);\n\t}", "\tStream_Zero(irp->output, 4); /* Padding(4) */\n\treturn irp->Complete(irp);\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT printer_process_irp_write(PRINTER_DEVICE* printer_dev, IRP* irp)\n{\n\tUINT32 Length;\n\tUINT64 Offset;\n\trdpPrintJob* printjob = NULL;\n\tUINT error = CHANNEL_RC_OK;", "\tvoid* ptr;", "\tif (Stream_GetRemainingLength(irp->input) < 32)\n\t\treturn ERROR_INVALID_DATA;", "\tStream_Read_UINT32(irp->input, Length);\n\tStream_Read_UINT64(irp->input, Offset);\n\tStream_Seek(irp->input, 20); /* Padding */", "\tptr = Stream_Pointer(irp->input);\n\tif (!Stream_SafeSeek(irp->input, Length))\n\t\treturn ERROR_INVALID_DATA;", "\tif (printer_dev->printer)\n\t\tprintjob = printer_dev->printer->FindPrintJob(printer_dev->printer, irp->FileId);", "\tif (!printjob)\n\t{\n\t\tirp->IoStatus = STATUS_UNSUCCESSFUL;\n\t\tLength = 0;\n\t}\n\telse\n\t{", "\t\terror = printjob->Write(printjob, ptr, Length);", "\t}", "\tif (error)\n\t{\n\t\tWLog_ERR(TAG, \"printjob->Write failed with error %\" PRIu32 \"!\", error);\n\t\treturn error;\n\t}", "\tStream_Write_UINT32(irp->output, Length);\n\tStream_Write_UINT8(irp->output, 0); /* Padding */\n\treturn irp->Complete(irp);\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT printer_process_irp_device_control(PRINTER_DEVICE* printer_dev, IRP* irp)\n{\n\tStream_Write_UINT32(irp->output, 0); /* OutputBufferLength */\n\treturn irp->Complete(irp);\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT printer_process_irp(PRINTER_DEVICE* printer_dev, IRP* irp)\n{\n\tUINT error;", "\tswitch (irp->MajorFunction)\n\t{\n\t\tcase IRP_MJ_CREATE:\n\t\t\tif ((error = printer_process_irp_create(printer_dev, irp)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"printer_process_irp_create failed with error %\" PRIu32 \"!\", error);\n\t\t\t\treturn error;\n\t\t\t}", "\t\t\tbreak;", "\t\tcase IRP_MJ_CLOSE:\n\t\t\tif ((error = printer_process_irp_close(printer_dev, irp)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"printer_process_irp_close failed with error %\" PRIu32 \"!\", error);\n\t\t\t\treturn error;\n\t\t\t}", "\t\t\tbreak;", "\t\tcase IRP_MJ_WRITE:\n\t\t\tif ((error = printer_process_irp_write(printer_dev, irp)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"printer_process_irp_write failed with error %\" PRIu32 \"!\", error);\n\t\t\t\treturn error;\n\t\t\t}", "\t\t\tbreak;", "\t\tcase IRP_MJ_DEVICE_CONTROL:\n\t\t\tif ((error = printer_process_irp_device_control(printer_dev, irp)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"printer_process_irp_device_control failed with error %\" PRIu32 \"!\",\n\t\t\t\t error);\n\t\t\t\treturn error;\n\t\t\t}", "\t\t\tbreak;", "\t\tdefault:\n\t\t\tirp->IoStatus = STATUS_NOT_SUPPORTED;\n\t\t\treturn irp->Complete(irp);\n\t\t\tbreak;\n\t}", "\treturn CHANNEL_RC_OK;\n}", "static DWORD WINAPI printer_thread_func(LPVOID arg)\n{\n\tIRP* irp;\n\tPRINTER_DEVICE* printer_dev = (PRINTER_DEVICE*)arg;\n\tHANDLE obj[] = { printer_dev->event, printer_dev->stopEvent };\n\tUINT error = CHANNEL_RC_OK;", "\twhile (1)\n\t{\n\t\tDWORD rc = WaitForMultipleObjects(2, obj, FALSE, INFINITE);", "\t\tif (rc == WAIT_FAILED)\n\t\t{\n\t\t\terror = GetLastError();\n\t\t\tWLog_ERR(TAG, \"WaitForMultipleObjects failed with error %\" PRIu32 \"!\", error);\n\t\t\tbreak;\n\t\t}", "\t\tif (rc == WAIT_OBJECT_0 + 1)\n\t\t\tbreak;\n\t\telse if (rc != WAIT_OBJECT_0)\n\t\t\tcontinue;", "\t\tResetEvent(printer_dev->event);\n\t\tirp = (IRP*)InterlockedPopEntrySList(printer_dev->pIrpList);", "\t\tif (irp == NULL)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"InterlockedPopEntrySList failed!\");\n\t\t\terror = ERROR_INTERNAL_ERROR;\n\t\t\tbreak;\n\t\t}", "\t\tif ((error = printer_process_irp(printer_dev, irp)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"printer_process_irp failed with error %\" PRIu32 \"!\", error);\n\t\t\tbreak;\n\t\t}\n\t}", "\tif (error && printer_dev->rdpcontext)\n\t\tsetChannelError(printer_dev->rdpcontext, error, \"printer_thread_func reported an error\");", "\tExitThread(error);\n\treturn error;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT printer_irp_request(DEVICE* device, IRP* irp)\n{\n\tPRINTER_DEVICE* printer_dev = (PRINTER_DEVICE*)device;\n\tInterlockedPushEntrySList(printer_dev->pIrpList, &(irp->ItemEntry));\n\tSetEvent(printer_dev->event);\n\treturn CHANNEL_RC_OK;\n}", "static UINT printer_custom_component(DEVICE* device, UINT16 component, UINT16 packetId, wStream* s)\n{\n\tUINT32 eventID;\n\tPRINTER_DEVICE* printer_dev = (PRINTER_DEVICE*)device;\n\tconst rdpSettings* settings = printer_dev->rdpcontext->settings;", "\tif (component != RDPDR_CTYP_PRN)\n\t\treturn ERROR_INVALID_DATA;", "\tif (Stream_GetRemainingLength(s) < 4)\n\t\treturn ERROR_INVALID_DATA;", "\tStream_Read_UINT32(s, eventID);", "\tswitch (packetId)\n\t{\n\t\tcase PAKID_PRN_CACHE_DATA:\n\t\t\tswitch (eventID)\n\t\t\t{\n\t\t\t\tcase RDPDR_ADD_PRINTER_EVENT:\n\t\t\t\t{\n\t\t\t\t\tchar PortDosName[8];\n\t\t\t\t\tUINT32 PnPNameLen, DriverNameLen, PrintNameLen, CacheFieldsLen;\n\t\t\t\t\tconst WCHAR *PnPName, *DriverName, *PrinterName;\n\t\t\t\t\tconst BYTE* CachedPrinterConfigData;", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < 24)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tStream_Read(s, PortDosName, sizeof(PortDosName));\n\t\t\t\t\tStream_Read_UINT32(s, PnPNameLen);\n\t\t\t\t\tStream_Read_UINT32(s, DriverNameLen);\n\t\t\t\t\tStream_Read_UINT32(s, PrintNameLen);\n\t\t\t\t\tStream_Read_UINT32(s, CacheFieldsLen);", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < PnPNameLen)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tPnPName = (const WCHAR*)Stream_Pointer(s);\n\t\t\t\t\tStream_Seek(s, PnPNameLen);", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < DriverNameLen)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tDriverName = (const WCHAR*)Stream_Pointer(s);\n\t\t\t\t\tStream_Seek(s, DriverNameLen);", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < PrintNameLen)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tPrinterName = (const WCHAR*)Stream_Pointer(s);\n\t\t\t\t\tStream_Seek(s, PrintNameLen);", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < CacheFieldsLen)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tCachedPrinterConfigData = Stream_Pointer(s);\n\t\t\t\t\tStream_Seek(s, CacheFieldsLen);", "\t\t\t\t\tif (!printer_save_to_config(settings, PortDosName, sizeof(PortDosName), PnPName,\n\t\t\t\t\t PnPNameLen, DriverName, DriverNameLen, PrinterName,\n\t\t\t\t\t PrintNameLen, CachedPrinterConfigData,\n\t\t\t\t\t CacheFieldsLen))\n\t\t\t\t\t\treturn ERROR_INTERNAL_ERROR;\n\t\t\t\t}\n\t\t\t\tbreak;", "\t\t\t\tcase RDPDR_UPDATE_PRINTER_EVENT:\n\t\t\t\t{\n\t\t\t\t\tUINT32 PrinterNameLen, ConfigDataLen;\n\t\t\t\t\tconst WCHAR* PrinterName;\n\t\t\t\t\tconst BYTE* ConfigData;", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < 8)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tStream_Read_UINT32(s, PrinterNameLen);\n\t\t\t\t\tStream_Read_UINT32(s, ConfigDataLen);", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < PrinterNameLen)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tPrinterName = (const WCHAR*)Stream_Pointer(s);\n\t\t\t\t\tStream_Seek(s, PrinterNameLen);", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < ConfigDataLen)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tConfigData = Stream_Pointer(s);\n\t\t\t\t\tStream_Seek(s, ConfigDataLen);", "\t\t\t\t\tif (!printer_update_to_config(settings, PrinterName, PrinterNameLen, ConfigData,\n\t\t\t\t\t ConfigDataLen))\n\t\t\t\t\t\treturn ERROR_INTERNAL_ERROR;\n\t\t\t\t}\n\t\t\t\tbreak;", "\t\t\t\tcase RDPDR_DELETE_PRINTER_EVENT:\n\t\t\t\t{\n\t\t\t\t\tUINT32 PrinterNameLen;\n\t\t\t\t\tconst WCHAR* PrinterName;", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < 4)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tStream_Read_UINT32(s, PrinterNameLen);", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < PrinterNameLen)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tPrinterName = (const WCHAR*)Stream_Pointer(s);\n\t\t\t\t\tStream_Seek(s, PrinterNameLen);\n\t\t\t\t\tprinter_remove_config(settings, PrinterName, PrinterNameLen);\n\t\t\t\t}\n\t\t\t\tbreak;", "\t\t\t\tcase RDPDR_RENAME_PRINTER_EVENT:\n\t\t\t\t{\n\t\t\t\t\tUINT32 OldPrinterNameLen, NewPrinterNameLen;\n\t\t\t\t\tconst WCHAR* OldPrinterName;\n\t\t\t\t\tconst WCHAR* NewPrinterName;", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < 8)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tStream_Read_UINT32(s, OldPrinterNameLen);\n\t\t\t\t\tStream_Read_UINT32(s, NewPrinterNameLen);", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < OldPrinterNameLen)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tOldPrinterName = (const WCHAR*)Stream_Pointer(s);\n\t\t\t\t\tStream_Seek(s, OldPrinterNameLen);", "\t\t\t\t\tif (Stream_GetRemainingLength(s) < NewPrinterNameLen)\n\t\t\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\t\t\tNewPrinterName = (const WCHAR*)Stream_Pointer(s);\n\t\t\t\t\tStream_Seek(s, NewPrinterNameLen);", "\t\t\t\t\tif (!printer_move_config(settings, OldPrinterName, OldPrinterNameLen,\n\t\t\t\t\t NewPrinterName, NewPrinterNameLen))\n\t\t\t\t\t\treturn ERROR_INTERNAL_ERROR;\n\t\t\t\t}\n\t\t\t\tbreak;", "\t\t\t\tdefault:\n\t\t\t\t\tWLog_ERR(TAG, \"Unknown cache data eventID: 0x%08\" PRIX32 \"\", eventID);\n\t\t\t\t\treturn ERROR_INVALID_DATA;\n\t\t\t}", "\t\t\tbreak;", "\t\tcase PAKID_PRN_USING_XPS:\n\t\t{\n\t\t\tUINT32 flags;", "\t\t\tif (Stream_GetRemainingLength(s) < 4)\n\t\t\t\treturn ERROR_INVALID_DATA;", "\t\t\tStream_Read_UINT32(s, flags);\n\t\t\tWLog_ERR(TAG,\n\t\t\t \"Ignoring unhandled message PAKID_PRN_USING_XPS [printerID=%08\" PRIx32\n\t\t\t \", flags=%08\" PRIx32 \"]\",\n\t\t\t eventID, flags);\n\t\t}\n\t\tbreak;", "\t\tdefault:\n\t\t\tWLog_ERR(TAG, \"Unknown printing component packetID: 0x%04\" PRIX16 \"\", packetId);\n\t\t\treturn ERROR_INVALID_DATA;\n\t}", "\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT printer_free(DEVICE* device)\n{\n\tIRP* irp;\n\tPRINTER_DEVICE* printer_dev = (PRINTER_DEVICE*)device;\n\tUINT error;\n\tSetEvent(printer_dev->stopEvent);", "\tif (WaitForSingleObject(printer_dev->thread, INFINITE) == WAIT_FAILED)\n\t{\n\t\terror = GetLastError();\n\t\tWLog_ERR(TAG, \"WaitForSingleObject failed with error %\" PRIu32 \"\", error);", "\t\t/* The analyzer is confused by this premature return value.\n\t\t * Since this case can not be handled gracefully silence the\n\t\t * analyzer here. */\n#ifndef __clang_analyzer__\n\t\treturn error;\n#endif\n\t}", "\twhile ((irp = (IRP*)InterlockedPopEntrySList(printer_dev->pIrpList)) != NULL)\n\t\tirp->Discard(irp);", "\tCloseHandle(printer_dev->thread);\n\tCloseHandle(printer_dev->stopEvent);\n\tCloseHandle(printer_dev->event);\n\t_aligned_free(printer_dev->pIrpList);", "\tif (printer_dev->printer)\n\t\tprinter_dev->printer->ReleaseRef(printer_dev->printer);", "\tStream_Free(printer_dev->device.data, TRUE);\n\tfree(printer_dev);\n\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT printer_register(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints, rdpPrinter* printer)\n{\n\tPRINTER_DEVICE* printer_dev;\n\tUINT error = ERROR_INTERNAL_ERROR;\n\tprinter_dev = (PRINTER_DEVICE*)calloc(1, sizeof(PRINTER_DEVICE));", "\tif (!printer_dev)\n\t{\n\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\treturn CHANNEL_RC_NO_MEMORY;\n\t}", "\tprinter_dev->device.data = Stream_New(NULL, 1024);", "\tif (!printer_dev->device.data)\n\t\tgoto error_out;", "\tsprintf_s(printer_dev->port, sizeof(printer_dev->port), \"PRN%\" PRIdz, printer->id);\n\tprinter_dev->device.type = RDPDR_DTYP_PRINT;\n\tprinter_dev->device.name = printer_dev->port;\n\tprinter_dev->device.IRPRequest = printer_irp_request;\n\tprinter_dev->device.CustomComponentRequest = printer_custom_component;\n\tprinter_dev->device.Free = printer_free;\n\tprinter_dev->rdpcontext = pEntryPoints->rdpcontext;\n\tprinter_dev->printer = printer;\n\tprinter_dev->pIrpList = (WINPR_PSLIST_HEADER)_aligned_malloc(sizeof(WINPR_SLIST_HEADER),\n\t MEMORY_ALLOCATION_ALIGNMENT);", "\tif (!printer_dev->pIrpList)\n\t{\n\t\tWLog_ERR(TAG, \"_aligned_malloc failed!\");\n\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\tgoto error_out;\n\t}", "\tif (!printer_load_from_config(pEntryPoints->rdpcontext->settings, printer, printer_dev))\n\t\tgoto error_out;", "\tInitializeSListHead(printer_dev->pIrpList);", "\tif (!(printer_dev->event = CreateEvent(NULL, TRUE, FALSE, NULL)))\n\t{\n\t\tWLog_ERR(TAG, \"CreateEvent failed!\");\n\t\terror = ERROR_INTERNAL_ERROR;\n\t\tgoto error_out;\n\t}", "\tif (!(printer_dev->stopEvent = CreateEvent(NULL, TRUE, FALSE, NULL)))\n\t{\n\t\tWLog_ERR(TAG, \"CreateEvent failed!\");\n\t\terror = ERROR_INTERNAL_ERROR;\n\t\tgoto error_out;\n\t}", "\tif ((error = pEntryPoints->RegisterDevice(pEntryPoints->devman, (DEVICE*)printer_dev)))\n\t{\n\t\tWLog_ERR(TAG, \"RegisterDevice failed with error %\" PRIu32 \"!\", error);\n\t\tgoto error_out;\n\t}", "\tif (!(printer_dev->thread =\n\t CreateThread(NULL, 0, printer_thread_func, (void*)printer_dev, 0, NULL)))\n\t{\n\t\tWLog_ERR(TAG, \"CreateThread failed!\");\n\t\terror = ERROR_INTERNAL_ERROR;\n\t\tgoto error_out;\n\t}", "\tprinter->AddRef(printer);\n\treturn CHANNEL_RC_OK;\nerror_out:\n\tprinter_free(&printer_dev->device);\n\treturn error;\n}", "static rdpPrinterDriver* printer_load_backend(const char* backend)\n{\n\ttypedef rdpPrinterDriver* (*backend_load_t)(void);\n\tunion {\n\t\tPVIRTUALCHANNELENTRY entry;\n\t\tbackend_load_t backend;\n\t} fktconv;", "\tfktconv.entry = freerdp_load_channel_addin_entry(\"printer\", backend, NULL, 0);\n\tif (!fktconv.entry)\n\t\treturn NULL;", "\treturn fktconv.backend();\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nUINT\n#ifdef BUILTIN_CHANNELS\nprinter_DeviceServiceEntry\n#else\n FREERDP_API\n DeviceServiceEntry\n#endif\n (PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints)\n{\n\tint i;\n\tchar* name;\n\tchar* driver_name;\n\tBOOL default_backend = TRUE;\n\tRDPDR_PRINTER* device = NULL;\n\trdpPrinterDriver* driver = NULL;\n\tUINT error = CHANNEL_RC_OK;", "\tif (!pEntryPoints || !pEntryPoints->device)\n\t\treturn ERROR_INVALID_PARAMETER;", "\tdevice = (RDPDR_PRINTER*)pEntryPoints->device;\n\tname = device->Name;\n\tdriver_name = device->DriverName;", "\t/* Secondary argument is one of the following:\n\t *\n\t * <driver_name> ... name of a printer driver\n\t * <driver_name>:<backend_name> ... name of a printer driver and local printer backend to use\n\t */\n\tif (driver_name)\n\t{\n\t\tchar* sep = strstr(driver_name, \":\");\n\t\tif (sep)\n\t\t{\n\t\t\tconst char* backend = sep + 1;\n\t\t\t*sep = '\\0';\n\t\t\tdriver = printer_load_backend(backend);\n\t\t\tdefault_backend = FALSE;\n\t\t}\n\t}", "\tif (!driver && default_backend)\n\t{\n\t\tconst char* backend =\n#if defined(WITH_CUPS)\n\t\t \"cups\"\n#elif defined(_WIN32)\n\t\t \"win\"\n#else\n\t\t \"\"\n#endif\n\t\t ;", "\t\tdriver = printer_load_backend(backend);\n\t}", "\tif (!driver)\n\t{\n\t\tWLog_ERR(TAG, \"Could not get a printer driver!\");\n\t\treturn CHANNEL_RC_INITIALIZATION_ERROR;\n\t}", "\tif (name && name[0])\n\t{\n\t\trdpPrinter* printer = driver->GetPrinter(driver, name, driver_name);", "\t\tif (!printer)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"Could not get printer %s!\", name);\n\t\t\terror = CHANNEL_RC_INITIALIZATION_ERROR;\n\t\t\tgoto fail;\n\t\t}", "\t\tif (!printer_save_default_config(pEntryPoints->rdpcontext->settings, printer))\n\t\t{\n\t\t\terror = CHANNEL_RC_INITIALIZATION_ERROR;\n\t\t\tprinter->ReleaseRef(printer);\n\t\t\tgoto fail;\n\t\t}", "\t\tif ((error = printer_register(pEntryPoints, printer)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"printer_register failed with error %\" PRIu32 \"!\", error);\n\t\t\tprinter->ReleaseRef(printer);\n\t\t\tgoto fail;\n\t\t}\n\t}\n\telse\n\t{\n\t\trdpPrinter** printers = driver->EnumPrinters(driver);\n\t\trdpPrinter** current = printers;", "\t\tfor (i = 0; current[i]; i++)\n\t\t{\n\t\t\trdpPrinter* printer = current[i];", "\t\t\tif ((error = printer_register(pEntryPoints, printer)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"printer_register failed with error %\" PRIu32 \"!\", error);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}", "\t\tdriver->ReleaseEnumPrinters(printers);\n\t}", "fail:\n\tdriver->ReleaseRef(driver);", "\treturn error;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [357, 496, 447, 322, 308, 1001], "buggy_code_start_loc": [333, 480, 447, 145, 307, 94], "filenames": ["channels/drive/client/drive_main.c", "channels/printer/client/printer_main.c", "channels/rdpei/client/rdpei_main.c", "channels/serial/client/serial_main.c", "libfreerdp/core/gateway/rdg.c", "libfreerdp/core/nego.c"], "fixing_code_end_loc": [361, 502, 451, 327, 309, 1013], "fixing_code_start_loc": [334, 481, 448, 145, 307, 94], "message": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:freerdp:freerdp:*:*:*:*:*:*:*:*", "matchCriteriaId": "5C5F8D57-1D22-42B4-9E08-9131F7BE8FA5", "versionEndExcluding": "2.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "B620311B-34A3-48A6-82DF-6F078D7A4493", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0."}, {"lang": "es", "value": "En FreeRDP versiones anteriores a 2.1.0, se presenta una lectura fuera de l\u00edmite en las funciones de irp (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). Esto ha sido corregido en la versi\u00f3n 2.1.0."}], "evaluatorComment": null, "id": "CVE-2020-11089", "lastModified": "2022-07-19T11:52:15.420", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:L/I:L/A:L", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 2.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-05-29T20:15:11.017", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2020-07/msg00080.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/795842f4096501fcefc1a7f535ccc8132feb31d7"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/security/advisories/GHSA-hfc7-c5gv-8c2h"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-125"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, "type": "CWE-125"}
320
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * FreeRDP: A Remote Desktop Protocol Implementation\n * Input Virtual Channel Extension\n *\n * Copyright 2013 Marc-Andre Moreau <marcandre.moreau@gmail.com>\n * Copyright 2015 Thincast Technologies GmbH\n * Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */", "#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif", "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>", "#include <winpr/crt.h>\n#include <winpr/synch.h>\n#include <winpr/thread.h>\n#include <winpr/stream.h>\n#include <winpr/sysinfo.h>\n#include <winpr/cmdline.h>\n#include <winpr/collections.h>", "#include <freerdp/addin.h>\n#include <freerdp/freerdp.h>", "#include \"rdpei_common.h\"", "#include \"rdpei_main.h\"", "/**\n * Touch Input\n * http://msdn.microsoft.com/en-us/library/windows/desktop/dd562197/\n *\n * Windows Touch Input\n * http://msdn.microsoft.com/en-us/library/windows/desktop/dd317321/\n *\n * Input: Touch injection sample\n * http://code.msdn.microsoft.com/windowsdesktop/Touch-Injection-Sample-444d9bf7\n *\n * Pointer Input Message Reference\n * http://msdn.microsoft.com/en-us/library/hh454916/\n *\n * POINTER_INFO Structure\n * http://msdn.microsoft.com/en-us/library/hh454907/\n *\n * POINTER_TOUCH_INFO Structure\n * http://msdn.microsoft.com/en-us/library/hh454910/\n */", "#define MAX_CONTACTS 512", "struct _RDPEI_CHANNEL_CALLBACK\n{\n\tIWTSVirtualChannelCallback iface;", "\tIWTSPlugin* plugin;\n\tIWTSVirtualChannelManager* channel_mgr;\n\tIWTSVirtualChannel* channel;\n};\ntypedef struct _RDPEI_CHANNEL_CALLBACK RDPEI_CHANNEL_CALLBACK;", "struct _RDPEI_LISTENER_CALLBACK\n{\n\tIWTSListenerCallback iface;", "\tIWTSPlugin* plugin;\n\tIWTSVirtualChannelManager* channel_mgr;\n\tRDPEI_CHANNEL_CALLBACK* channel_callback;\n};\ntypedef struct _RDPEI_LISTENER_CALLBACK RDPEI_LISTENER_CALLBACK;", "struct _RDPEI_PLUGIN\n{\n\tIWTSPlugin iface;", "\tIWTSListener* listener;\n\tRDPEI_LISTENER_CALLBACK* listener_callback;", "\tRdpeiClientContext* context;", "\tint version;\n\tUINT16 maxTouchContacts;\n\tUINT64 currentFrameTime;\n\tUINT64 previousFrameTime;\n\tRDPINPUT_TOUCH_FRAME frame;\n\tRDPINPUT_CONTACT_DATA contacts[MAX_CONTACTS];\n\tRDPINPUT_CONTACT_POINT* contactPoints;", "\trdpContext* rdpcontext;\n};\ntypedef struct _RDPEI_PLUGIN RDPEI_PLUGIN;", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_send_frame(RdpeiClientContext* context);", "#ifdef WITH_DEBUG_RDPEI\nstatic const char* rdpei_eventid_string(UINT16 event)\n{\n\tswitch (event)\n\t{\n\t\tcase EVENTID_SC_READY:\n\t\t\treturn \"EVENTID_SC_READY\";\n\t\tcase EVENTID_CS_READY:\n\t\t\treturn \"EVENTID_CS_READY\";\n\t\tcase EVENTID_TOUCH:\n\t\t\treturn \"EVENTID_TOUCH\";\n\t\tcase EVENTID_SUSPEND_TOUCH:\n\t\t\treturn \"EVENTID_SUSPEND_TOUCH\";\n\t\tcase EVENTID_RESUME_TOUCH:\n\t\t\treturn \"EVENTID_RESUME_TOUCH\";\n\t\tcase EVENTID_DISMISS_HOVERING_CONTACT:\n\t\t\treturn \"EVENTID_DISMISS_HOVERING_CONTACT\";\n\t\tdefault:\n\t\t\treturn \"EVENTID_UNKNOWN\";\n\t}\n}\n#endif", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_add_frame(RdpeiClientContext* context)\n{\n\tint i;\n\tRDPINPUT_CONTACT_DATA* contact;\n\tRDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle;\n\trdpei->frame.contactCount = 0;", "\tfor (i = 0; i < rdpei->maxTouchContacts; i++)\n\t{\n\t\tcontact = (RDPINPUT_CONTACT_DATA*)&(rdpei->contactPoints[i].data);", "\t\tif (rdpei->contactPoints[i].dirty)\n\t\t{\n\t\t\tCopyMemory(&(rdpei->contacts[rdpei->frame.contactCount]), contact,\n\t\t\t sizeof(RDPINPUT_CONTACT_DATA));\n\t\t\trdpei->contactPoints[i].dirty = FALSE;\n\t\t\trdpei->frame.contactCount++;\n\t\t}\n\t\telse if (rdpei->contactPoints[i].active)\n\t\t{\n\t\t\tif (contact->contactFlags & CONTACT_FLAG_DOWN)\n\t\t\t{\n\t\t\t\tcontact->contactFlags = CONTACT_FLAG_UPDATE;\n\t\t\t\tcontact->contactFlags |= CONTACT_FLAG_INRANGE;\n\t\t\t\tcontact->contactFlags |= CONTACT_FLAG_INCONTACT;\n\t\t\t}", "\t\t\tCopyMemory(&(rdpei->contacts[rdpei->frame.contactCount]), contact,\n\t\t\t sizeof(RDPINPUT_CONTACT_DATA));\n\t\t\trdpei->frame.contactCount++;\n\t\t}\n\t}", "\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_send_pdu(RDPEI_CHANNEL_CALLBACK* callback, wStream* s, UINT16 eventId,\n UINT32 pduLength)\n{\n\tUINT status;\n\tStream_SetPosition(s, 0);\n\tStream_Write_UINT16(s, eventId); /* eventId (2 bytes) */\n\tStream_Write_UINT32(s, pduLength); /* pduLength (4 bytes) */\n\tStream_SetPosition(s, Stream_Length(s));\n\tstatus = callback->channel->Write(callback->channel, (UINT32)Stream_Length(s), Stream_Buffer(s),\n\t NULL);\n#ifdef WITH_DEBUG_RDPEI\n\tWLog_DBG(TAG,\n\t \"rdpei_send_pdu: eventId: %\" PRIu16 \" (%s) length: %\" PRIu32 \" status: %\" PRIu32 \"\",\n\t eventId, rdpei_eventid_string(eventId), pduLength, status);\n#endif\n\treturn status;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_send_cs_ready_pdu(RDPEI_CHANNEL_CALLBACK* callback)\n{\n\tUINT status;\n\twStream* s;\n\tUINT32 flags;\n\tUINT32 pduLength;\n\tRDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)callback->plugin;\n\tflags = 0;\n\tflags |= READY_FLAGS_SHOW_TOUCH_VISUALS;\n\t// flags |= READY_FLAGS_DISABLE_TIMESTAMP_INJECTION;\n\tpduLength = RDPINPUT_HEADER_LENGTH + 10;\n\ts = Stream_New(NULL, pduLength);", "\tif (!s)\n\t{\n\t\tWLog_ERR(TAG, \"Stream_New failed!\");\n\t\treturn CHANNEL_RC_NO_MEMORY;\n\t}", "\tStream_Seek(s, RDPINPUT_HEADER_LENGTH);\n\tStream_Write_UINT32(s, flags); /* flags (4 bytes) */\n\tStream_Write_UINT32(s, RDPINPUT_PROTOCOL_V10); /* protocolVersion (4 bytes) */\n\tStream_Write_UINT16(s, rdpei->maxTouchContacts); /* maxTouchContacts (2 bytes) */\n\tStream_SealLength(s);\n\tstatus = rdpei_send_pdu(callback, s, EVENTID_CS_READY, pduLength);\n\tStream_Free(s, TRUE);\n\treturn status;\n}", "static void rdpei_print_contact_flags(UINT32 contactFlags)\n{\n\tif (contactFlags & CONTACT_FLAG_DOWN)\n\t\tWLog_DBG(TAG, \" CONTACT_FLAG_DOWN\");", "\tif (contactFlags & CONTACT_FLAG_UPDATE)\n\t\tWLog_DBG(TAG, \" CONTACT_FLAG_UPDATE\");", "\tif (contactFlags & CONTACT_FLAG_UP)\n\t\tWLog_DBG(TAG, \" CONTACT_FLAG_UP\");", "\tif (contactFlags & CONTACT_FLAG_INRANGE)\n\t\tWLog_DBG(TAG, \" CONTACT_FLAG_INRANGE\");", "\tif (contactFlags & CONTACT_FLAG_INCONTACT)\n\t\tWLog_DBG(TAG, \" CONTACT_FLAG_INCONTACT\");", "\tif (contactFlags & CONTACT_FLAG_CANCELED)\n\t\tWLog_DBG(TAG, \" CONTACT_FLAG_CANCELED\");\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_write_touch_frame(wStream* s, RDPINPUT_TOUCH_FRAME* frame)\n{\n\tUINT32 index;\n\tint rectSize = 2;\n\tRDPINPUT_CONTACT_DATA* contact;\n#ifdef WITH_DEBUG_RDPEI\n\tWLog_DBG(TAG, \"contactCount: %\" PRIu32 \"\", frame->contactCount);\n\tWLog_DBG(TAG, \"frameOffset: 0x%016\" PRIX64 \"\", frame->frameOffset);\n#endif\n\trdpei_write_2byte_unsigned(s,\n\t frame->contactCount); /* contactCount (TWO_BYTE_UNSIGNED_INTEGER) */\n\t/**\n\t * the time offset from the previous frame (in microseconds).\n\t * If this is the first frame being transmitted then this field MUST be set to zero.\n\t */\n\trdpei_write_8byte_unsigned(s, frame->frameOffset *\n\t 1000); /* frameOffset (EIGHT_BYTE_UNSIGNED_INTEGER) */", "\tif (!Stream_EnsureRemainingCapacity(s, (size_t)frame->contactCount * 64))\n\t{\n\t\tWLog_ERR(TAG, \"Stream_EnsureRemainingCapacity failed!\");\n\t\treturn CHANNEL_RC_NO_MEMORY;\n\t}", "\tfor (index = 0; index < frame->contactCount; index++)\n\t{\n\t\tcontact = &frame->contacts[index];\n\t\tcontact->fieldsPresent |= CONTACT_DATA_CONTACTRECT_PRESENT;\n\t\tcontact->contactRectLeft = contact->x - rectSize;\n\t\tcontact->contactRectTop = contact->y - rectSize;\n\t\tcontact->contactRectRight = contact->x + rectSize;\n\t\tcontact->contactRectBottom = contact->y + rectSize;\n#ifdef WITH_DEBUG_RDPEI\n\t\tWLog_DBG(TAG, \"contact[%\" PRIu32 \"].contactId: %\" PRIu32 \"\", index, contact->contactId);\n\t\tWLog_DBG(TAG, \"contact[%\" PRIu32 \"].fieldsPresent: %\" PRIu32 \"\", index,\n\t\t contact->fieldsPresent);\n\t\tWLog_DBG(TAG, \"contact[%\" PRIu32 \"].x: %\" PRId32 \"\", index, contact->x);\n\t\tWLog_DBG(TAG, \"contact[%\" PRIu32 \"].y: %\" PRId32 \"\", index, contact->y);\n\t\tWLog_DBG(TAG, \"contact[%\" PRIu32 \"].contactFlags: 0x%08\" PRIX32 \"\", index,\n\t\t contact->contactFlags);\n\t\trdpei_print_contact_flags(contact->contactFlags);\n#endif\n\t\tStream_Write_UINT8(s, contact->contactId); /* contactId (1 byte) */\n\t\t/* fieldsPresent (TWO_BYTE_UNSIGNED_INTEGER) */\n\t\trdpei_write_2byte_unsigned(s, contact->fieldsPresent);\n\t\trdpei_write_4byte_signed(s, contact->x); /* x (FOUR_BYTE_SIGNED_INTEGER) */\n\t\trdpei_write_4byte_signed(s, contact->y); /* y (FOUR_BYTE_SIGNED_INTEGER) */\n\t\t/* contactFlags (FOUR_BYTE_UNSIGNED_INTEGER) */\n\t\trdpei_write_4byte_unsigned(s, contact->contactFlags);", "\t\tif (contact->fieldsPresent & CONTACT_DATA_CONTACTRECT_PRESENT)\n\t\t{\n\t\t\t/* contactRectLeft (TWO_BYTE_SIGNED_INTEGER) */\n\t\t\trdpei_write_2byte_signed(s, contact->contactRectLeft);\n\t\t\t/* contactRectTop (TWO_BYTE_SIGNED_INTEGER) */\n\t\t\trdpei_write_2byte_signed(s, contact->contactRectTop);\n\t\t\t/* contactRectRight (TWO_BYTE_SIGNED_INTEGER) */\n\t\t\trdpei_write_2byte_signed(s, contact->contactRectRight);\n\t\t\t/* contactRectBottom (TWO_BYTE_SIGNED_INTEGER) */\n\t\t\trdpei_write_2byte_signed(s, contact->contactRectBottom);\n\t\t}", "\t\tif (contact->fieldsPresent & CONTACT_DATA_ORIENTATION_PRESENT)\n\t\t{\n\t\t\t/* orientation (FOUR_BYTE_UNSIGNED_INTEGER) */\n\t\t\trdpei_write_4byte_unsigned(s, contact->orientation);\n\t\t}", "\t\tif (contact->fieldsPresent & CONTACT_DATA_PRESSURE_PRESENT)\n\t\t{\n\t\t\t/* pressure (FOUR_BYTE_UNSIGNED_INTEGER) */\n\t\t\trdpei_write_4byte_unsigned(s, contact->pressure);\n\t\t}\n\t}", "\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_send_touch_event_pdu(RDPEI_CHANNEL_CALLBACK* callback,\n RDPINPUT_TOUCH_FRAME* frame)\n{\n\tUINT status;\n\twStream* s;\n\tUINT32 pduLength;\n\tpduLength = 64 + (frame->contactCount * 64);\n\ts = Stream_New(NULL, pduLength);", "\tif (!s)\n\t{\n\t\tWLog_ERR(TAG, \"Stream_New failed!\");\n\t\treturn CHANNEL_RC_NO_MEMORY;\n\t}", "\tStream_Seek(s, RDPINPUT_HEADER_LENGTH);\n\t/**\n\t * the time that has elapsed (in milliseconds) from when the oldest touch frame\n\t * was generated to when it was encoded for transmission by the client.\n\t */\n\trdpei_write_4byte_unsigned(\n\t s, (UINT32)frame->frameOffset); /* encodeTime (FOUR_BYTE_UNSIGNED_INTEGER) */\n\trdpei_write_2byte_unsigned(s, 1); /* (frameCount) TWO_BYTE_UNSIGNED_INTEGER */", "\tif ((status = rdpei_write_touch_frame(s, frame)))\n\t{\n\t\tWLog_ERR(TAG, \"rdpei_write_touch_frame failed with error %\" PRIu32 \"!\", status);\n\t\tStream_Free(s, TRUE);\n\t\treturn status;\n\t}", "\tStream_SealLength(s);\n\tpduLength = Stream_Length(s);\n\tstatus = rdpei_send_pdu(callback, s, EVENTID_TOUCH, pduLength);\n\tStream_Free(s, TRUE);\n\treturn status;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_recv_sc_ready_pdu(RDPEI_CHANNEL_CALLBACK* callback, wStream* s)\n{\n\tUINT32 protocolVersion;\n\tStream_Read_UINT32(s, protocolVersion); /* protocolVersion (4 bytes) */\n#if 0", "\tif (protocolVersion != RDPINPUT_PROTOCOL_V10)\n\t{\n\t\tWLog_ERR(TAG, \"Unknown [MS-RDPEI] protocolVersion: 0x%08\"PRIX32\"\", protocolVersion);\n\t\treturn -1;\n\t}", "#endif\n\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_recv_suspend_touch_pdu(RDPEI_CHANNEL_CALLBACK* callback, wStream* s)\n{\n\tRdpeiClientContext* rdpei = (RdpeiClientContext*)callback->plugin->pInterface;\n\tUINT error = CHANNEL_RC_OK;\n\tIFCALLRET(rdpei->SuspendTouch, error, rdpei);", "\tif (error)\n\t\tWLog_ERR(TAG, \"rdpei->SuspendTouch failed with error %\" PRIu32 \"!\", error);", "\treturn error;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_recv_resume_touch_pdu(RDPEI_CHANNEL_CALLBACK* callback, wStream* s)\n{\n\tRdpeiClientContext* rdpei = (RdpeiClientContext*)callback->plugin->pInterface;\n\tUINT error = CHANNEL_RC_OK;\n\tIFCALLRET(rdpei->ResumeTouch, error, rdpei);", "\tif (error)\n\t\tWLog_ERR(TAG, \"rdpei->ResumeTouch failed with error %\" PRIu32 \"!\", error);", "\treturn error;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_recv_pdu(RDPEI_CHANNEL_CALLBACK* callback, wStream* s)\n{\n\tUINT16 eventId;\n\tUINT32 pduLength;\n\tUINT error;", "", "\tStream_Read_UINT16(s, eventId); /* eventId (2 bytes) */\n\tStream_Read_UINT32(s, pduLength); /* pduLength (4 bytes) */\n#ifdef WITH_DEBUG_RDPEI\n\tWLog_DBG(TAG, \"rdpei_recv_pdu: eventId: %\" PRIu16 \" (%s) length: %\" PRIu32 \"\", eventId,\n\t rdpei_eventid_string(eventId), pduLength);\n#endif", "\tswitch (eventId)\n\t{\n\t\tcase EVENTID_SC_READY:\n\t\t\tif ((error = rdpei_recv_sc_ready_pdu(callback, s)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"rdpei_recv_sc_ready_pdu failed with error %\" PRIu32 \"!\", error);\n\t\t\t\treturn error;\n\t\t\t}", "\t\t\tif ((error = rdpei_send_cs_ready_pdu(callback)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"rdpei_send_cs_ready_pdu failed with error %\" PRIu32 \"!\", error);\n\t\t\t\treturn error;\n\t\t\t}", "\t\t\tbreak;", "\t\tcase EVENTID_SUSPEND_TOUCH:\n\t\t\tif ((error = rdpei_recv_suspend_touch_pdu(callback, s)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"rdpei_recv_suspend_touch_pdu failed with error %\" PRIu32 \"!\", error);\n\t\t\t\treturn error;\n\t\t\t}", "\t\t\tbreak;", "\t\tcase EVENTID_RESUME_TOUCH:\n\t\t\tif ((error = rdpei_recv_resume_touch_pdu(callback, s)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"rdpei_recv_resume_touch_pdu failed with error %\" PRIu32 \"!\", error);\n\t\t\t\treturn error;\n\t\t\t}", "\t\t\tbreak;", "\t\tdefault:\n\t\t\tbreak;\n\t}", "\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_on_data_received(IWTSVirtualChannelCallback* pChannelCallback, wStream* data)\n{\n\tRDPEI_CHANNEL_CALLBACK* callback = (RDPEI_CHANNEL_CALLBACK*)pChannelCallback;\n\treturn rdpei_recv_pdu(callback, data);\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_on_close(IWTSVirtualChannelCallback* pChannelCallback)\n{\n\tRDPEI_CHANNEL_CALLBACK* callback = (RDPEI_CHANNEL_CALLBACK*)pChannelCallback;\n\tfree(callback);\n\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_on_new_channel_connection(IWTSListenerCallback* pListenerCallback,\n IWTSVirtualChannel* pChannel, BYTE* Data,\n BOOL* pbAccept, IWTSVirtualChannelCallback** ppCallback)\n{\n\tRDPEI_CHANNEL_CALLBACK* callback;\n\tRDPEI_LISTENER_CALLBACK* listener_callback = (RDPEI_LISTENER_CALLBACK*)pListenerCallback;\n\tcallback = (RDPEI_CHANNEL_CALLBACK*)calloc(1, sizeof(RDPEI_CHANNEL_CALLBACK));", "\tif (!callback)\n\t{\n\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\treturn CHANNEL_RC_NO_MEMORY;\n\t}", "\tcallback->iface.OnDataReceived = rdpei_on_data_received;\n\tcallback->iface.OnClose = rdpei_on_close;\n\tcallback->plugin = listener_callback->plugin;\n\tcallback->channel_mgr = listener_callback->channel_mgr;\n\tcallback->channel = pChannel;\n\tlistener_callback->channel_callback = callback;\n\t*ppCallback = (IWTSVirtualChannelCallback*)callback;\n\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_plugin_initialize(IWTSPlugin* pPlugin, IWTSVirtualChannelManager* pChannelMgr)\n{\n\tUINT error;\n\tRDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)pPlugin;\n\trdpei->listener_callback = (RDPEI_LISTENER_CALLBACK*)calloc(1, sizeof(RDPEI_LISTENER_CALLBACK));", "\tif (!rdpei->listener_callback)\n\t{\n\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\treturn CHANNEL_RC_NO_MEMORY;\n\t}", "\trdpei->listener_callback->iface.OnNewChannelConnection = rdpei_on_new_channel_connection;\n\trdpei->listener_callback->plugin = pPlugin;\n\trdpei->listener_callback->channel_mgr = pChannelMgr;", "\tif ((error = pChannelMgr->CreateListener(pChannelMgr, RDPEI_DVC_CHANNEL_NAME, 0,\n\t (IWTSListenerCallback*)rdpei->listener_callback,\n\t &(rdpei->listener))))\n\t{\n\t\tWLog_ERR(TAG, \"ChannelMgr->CreateListener failed with error %\" PRIu32 \"!\", error);\n\t\tgoto error_out;\n\t}", "\trdpei->listener->pInterface = rdpei->iface.pInterface;", "\treturn error;\nerror_out:\n\tfree(rdpei->listener_callback);\n\treturn error;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_plugin_terminated(IWTSPlugin* pPlugin)\n{\n\tRDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)pPlugin;", "\tif (!pPlugin)\n\t\treturn ERROR_INVALID_PARAMETER;", "\tfree(rdpei->listener_callback);\n\tfree(rdpei->context);\n\tfree(rdpei);\n\treturn CHANNEL_RC_OK;\n}", "/**\n * Channel Client Interface\n */", "static int rdpei_get_version(RdpeiClientContext* context)\n{\n\tRDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle;\n\treturn rdpei->version;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nUINT rdpei_send_frame(RdpeiClientContext* context)\n{\n\tUINT64 currentTime;\n\tRDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle;\n\tRDPEI_CHANNEL_CALLBACK* callback = rdpei->listener_callback->channel_callback;\n\tUINT error;\n\tcurrentTime = GetTickCount64();", "\tif (!rdpei->previousFrameTime && !rdpei->currentFrameTime)\n\t{\n\t\trdpei->currentFrameTime = currentTime;\n\t\trdpei->frame.frameOffset = 0;\n\t}\n\telse\n\t{\n\t\trdpei->currentFrameTime = currentTime;\n\t\trdpei->frame.frameOffset = rdpei->currentFrameTime - rdpei->previousFrameTime;\n\t}", "\tif ((error = rdpei_send_touch_event_pdu(callback, &rdpei->frame)))\n\t{\n\t\tWLog_ERR(TAG, \"rdpei_send_touch_event_pdu failed with error %\" PRIu32 \"!\", error);\n\t\treturn error;\n\t}", "\trdpei->previousFrameTime = rdpei->currentFrameTime;\n\trdpei->frame.contactCount = 0;\n\treturn error;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_add_contact(RdpeiClientContext* context, const RDPINPUT_CONTACT_DATA* contact)\n{\n\tUINT error;\n\tRDPINPUT_CONTACT_POINT* contactPoint;\n\tRDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle;", "\tcontactPoint = (RDPINPUT_CONTACT_POINT*)&rdpei->contactPoints[contact->contactId];\n\tCopyMemory(&(contactPoint->data), contact, sizeof(RDPINPUT_CONTACT_DATA));\n\tcontactPoint->dirty = TRUE;", "\terror = rdpei_add_frame(context);\n\tif (error != CHANNEL_RC_OK)\n\t{\n\t\tWLog_ERR(TAG, \"rdpei_add_frame failed with error %\" PRIu32 \"!\", error);\n\t\treturn error;\n\t}", "\tif (rdpei->frame.contactCount > 0)\n\t{\n\t\terror = rdpei_send_frame(context);\n\t\tif (error != CHANNEL_RC_OK)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"rdpei_send_frame failed with error %\" PRIu32 \"!\", error);\n\t\t\treturn error;\n\t\t}\n\t}\n\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_touch_begin(RdpeiClientContext* context, int externalId, int x, int y,\n int* contactId)\n{\n\tunsigned int i;\n\tINT64 contactIdlocal = -1;\n\tRDPINPUT_CONTACT_DATA contact;\n\tRDPINPUT_CONTACT_POINT* contactPoint = NULL;\n\tRDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle;\n\tUINT error = CHANNEL_RC_OK;", "\t/* Create a new contact point in an empty slot */", "\tfor (i = 0; i < rdpei->maxTouchContacts; i++)\n\t{\n\t\tcontactPoint = (RDPINPUT_CONTACT_POINT*)&rdpei->contactPoints[i];", "\t\tif (!contactPoint->active)\n\t\t{\n\t\t\tcontactPoint->contactId = i;\n\t\t\tcontactIdlocal = contactPoint->contactId;\n\t\t\tcontactPoint->externalId = externalId;\n\t\t\tcontactPoint->active = TRUE;\n\t\t\tcontactPoint->state = RDPINPUT_CONTACT_STATE_ENGAGED;\n\t\t\tbreak;\n\t\t}\n\t}", "\tif (contactIdlocal >= 0)\n\t{\n\t\tZeroMemory(&contact, sizeof(RDPINPUT_CONTACT_DATA));\n\t\tcontactPoint->lastX = x;\n\t\tcontactPoint->lastY = y;\n\t\tcontact.x = x;\n\t\tcontact.y = y;\n\t\tcontact.contactId = (UINT32)contactIdlocal;\n\t\tcontact.contactFlags |= CONTACT_FLAG_DOWN;\n\t\tcontact.contactFlags |= CONTACT_FLAG_INRANGE;\n\t\tcontact.contactFlags |= CONTACT_FLAG_INCONTACT;\n\t\terror = context->AddContact(context, &contact);\n\t}", "\t*contactId = contactIdlocal;\n\treturn error;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_touch_update(RdpeiClientContext* context, int externalId, int x, int y,\n int* contactId)\n{\n\tunsigned int i;\n\tint contactIdlocal = -1;\n\tRDPINPUT_CONTACT_DATA contact;\n\tRDPINPUT_CONTACT_POINT* contactPoint = NULL;\n\tRDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle;\n\tUINT error = CHANNEL_RC_OK;", "\tfor (i = 0; i < rdpei->maxTouchContacts; i++)\n\t{\n\t\tcontactPoint = (RDPINPUT_CONTACT_POINT*)&rdpei->contactPoints[i];", "\t\tif (!contactPoint->active)\n\t\t\tcontinue;", "\t\tif (contactPoint->externalId == externalId)\n\t\t{\n\t\t\tcontactIdlocal = contactPoint->contactId;\n\t\t\tbreak;\n\t\t}\n\t}", "\tif (contactIdlocal >= 0)\n\t{\n\t\tZeroMemory(&contact, sizeof(RDPINPUT_CONTACT_DATA));\n\t\tcontactPoint->lastX = x;\n\t\tcontactPoint->lastY = y;\n\t\tcontact.x = x;\n\t\tcontact.y = y;\n\t\tcontact.contactId = (UINT32)contactIdlocal;\n\t\tcontact.contactFlags |= CONTACT_FLAG_UPDATE;\n\t\tcontact.contactFlags |= CONTACT_FLAG_INRANGE;\n\t\tcontact.contactFlags |= CONTACT_FLAG_INCONTACT;\n\t\terror = context->AddContact(context, &contact);\n\t}", "\t*contactId = contactIdlocal;\n\treturn error;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_touch_end(RdpeiClientContext* context, int externalId, int x, int y,\n int* contactId)\n{\n\tunsigned int i;\n\tint contactIdlocal = -1;\n\tint tempvalue;\n\tRDPINPUT_CONTACT_DATA contact;\n\tRDPINPUT_CONTACT_POINT* contactPoint = NULL;\n\tRDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle;\n\tUINT error;", "\tfor (i = 0; i < rdpei->maxTouchContacts; i++)\n\t{\n\t\tcontactPoint = (RDPINPUT_CONTACT_POINT*)&rdpei->contactPoints[i];", "\t\tif (!contactPoint->active)\n\t\t\tcontinue;", "\t\tif (contactPoint->externalId == externalId)\n\t\t{\n\t\t\tcontactIdlocal = contactPoint->contactId;\n\t\t\tbreak;\n\t\t}\n\t}", "\tif (contactIdlocal >= 0)\n\t{\n\t\tZeroMemory(&contact, sizeof(RDPINPUT_CONTACT_DATA));", "\t\tif ((contactPoint->lastX != x) && (contactPoint->lastY != y))\n\t\t{\n\t\t\tif ((error = context->TouchUpdate(context, externalId, x, y, &tempvalue)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"context->TouchUpdate failed with error %\" PRIu32 \"!\", error);\n\t\t\t\treturn error;\n\t\t\t}\n\t\t}", "\t\tcontact.x = x;\n\t\tcontact.y = y;\n\t\tcontact.contactId = (UINT32)contactIdlocal;\n\t\tcontact.contactFlags |= CONTACT_FLAG_UP;", "\t\tif ((error = context->AddContact(context, &contact)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"context->AddContact failed with error %\" PRIu32 \"!\", error);\n\t\t\treturn error;\n\t\t}", "\t\tcontactPoint->externalId = 0;\n\t\tcontactPoint->active = FALSE;\n\t\tcontactPoint->flags = 0;\n\t\tcontactPoint->contactId = 0;\n\t\tcontactPoint->state = RDPINPUT_CONTACT_STATE_OUT_OF_RANGE;\n\t}", "\t*contactId = contactIdlocal;\n\treturn CHANNEL_RC_OK;\n}", "#ifdef BUILTIN_CHANNELS\n#define DVCPluginEntry rdpei_DVCPluginEntry\n#else\n#define DVCPluginEntry FREERDP_API DVCPluginEntry\n#endif", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nUINT DVCPluginEntry(IDRDYNVC_ENTRY_POINTS* pEntryPoints)\n{\n\tUINT error;\n\tRDPEI_PLUGIN* rdpei = NULL;\n\tRdpeiClientContext* context = NULL;\n\trdpei = (RDPEI_PLUGIN*)pEntryPoints->GetPlugin(pEntryPoints, \"rdpei\");", "\tif (!rdpei)\n\t{\n\t\tsize_t size;\n\t\trdpei = (RDPEI_PLUGIN*)calloc(1, sizeof(RDPEI_PLUGIN));", "\t\tif (!rdpei)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}", "\t\trdpei->iface.Initialize = rdpei_plugin_initialize;\n\t\trdpei->iface.Connected = NULL;\n\t\trdpei->iface.Disconnected = NULL;\n\t\trdpei->iface.Terminated = rdpei_plugin_terminated;\n\t\trdpei->version = 1;\n\t\trdpei->currentFrameTime = 0;\n\t\trdpei->previousFrameTime = 0;\n\t\trdpei->frame.contacts = (RDPINPUT_CONTACT_DATA*)rdpei->contacts;\n\t\trdpei->maxTouchContacts = 10;\n\t\tsize = rdpei->maxTouchContacts * sizeof(RDPINPUT_CONTACT_POINT);\n\t\trdpei->contactPoints = (RDPINPUT_CONTACT_POINT*)calloc(1, size);\n\t\trdpei->rdpcontext =\n\t\t ((freerdp*)((rdpSettings*)pEntryPoints->GetRdpSettings(pEntryPoints))->instance)\n\t\t ->context;", "\t\tif (!rdpei->contactPoints)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\tgoto error_out;\n\t\t}", "\t\tcontext = (RdpeiClientContext*)calloc(1, sizeof(RdpeiClientContext));", "\t\tif (!context)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\tgoto error_out;\n\t\t}", "\t\tcontext->handle = (void*)rdpei;\n\t\tcontext->GetVersion = rdpei_get_version;\n\t\tcontext->AddContact = rdpei_add_contact;\n\t\tcontext->TouchBegin = rdpei_touch_begin;\n\t\tcontext->TouchUpdate = rdpei_touch_update;\n\t\tcontext->TouchEnd = rdpei_touch_end;\n\t\trdpei->iface.pInterface = (void*)context;", "\t\tif ((error = pEntryPoints->RegisterPlugin(pEntryPoints, \"rdpei\", (IWTSPlugin*)rdpei)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"EntryPoints->RegisterPlugin failed with error %\" PRIu32 \"!\", error);\n\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\tgoto error_out;\n\t\t}", "\t\trdpei->context = context;\n\t}", "\treturn CHANNEL_RC_OK;\nerror_out:\n\tfree(context);\n\tfree(rdpei->contactPoints);\n\tfree(rdpei);\n\treturn error;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [357, 496, 447, 322, 308, 1001], "buggy_code_start_loc": [333, 480, 447, 145, 307, 94], "filenames": ["channels/drive/client/drive_main.c", "channels/printer/client/printer_main.c", "channels/rdpei/client/rdpei_main.c", "channels/serial/client/serial_main.c", "libfreerdp/core/gateway/rdg.c", "libfreerdp/core/nego.c"], "fixing_code_end_loc": [361, 502, 451, 327, 309, 1013], "fixing_code_start_loc": [334, 481, 448, 145, 307, 94], "message": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:freerdp:freerdp:*:*:*:*:*:*:*:*", "matchCriteriaId": "5C5F8D57-1D22-42B4-9E08-9131F7BE8FA5", "versionEndExcluding": "2.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "B620311B-34A3-48A6-82DF-6F078D7A4493", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0."}, {"lang": "es", "value": "En FreeRDP versiones anteriores a 2.1.0, se presenta una lectura fuera de l\u00edmite en las funciones de irp (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). Esto ha sido corregido en la versi\u00f3n 2.1.0."}], "evaluatorComment": null, "id": "CVE-2020-11089", "lastModified": "2022-07-19T11:52:15.420", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:L/I:L/A:L", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 2.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-05-29T20:15:11.017", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2020-07/msg00080.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/795842f4096501fcefc1a7f535ccc8132feb31d7"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/security/advisories/GHSA-hfc7-c5gv-8c2h"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-125"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, "type": "CWE-125"}
320
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * FreeRDP: A Remote Desktop Protocol Implementation\n * Input Virtual Channel Extension\n *\n * Copyright 2013 Marc-Andre Moreau <marcandre.moreau@gmail.com>\n * Copyright 2015 Thincast Technologies GmbH\n * Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */", "#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif", "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>", "#include <winpr/crt.h>\n#include <winpr/synch.h>\n#include <winpr/thread.h>\n#include <winpr/stream.h>\n#include <winpr/sysinfo.h>\n#include <winpr/cmdline.h>\n#include <winpr/collections.h>", "#include <freerdp/addin.h>\n#include <freerdp/freerdp.h>", "#include \"rdpei_common.h\"", "#include \"rdpei_main.h\"", "/**\n * Touch Input\n * http://msdn.microsoft.com/en-us/library/windows/desktop/dd562197/\n *\n * Windows Touch Input\n * http://msdn.microsoft.com/en-us/library/windows/desktop/dd317321/\n *\n * Input: Touch injection sample\n * http://code.msdn.microsoft.com/windowsdesktop/Touch-Injection-Sample-444d9bf7\n *\n * Pointer Input Message Reference\n * http://msdn.microsoft.com/en-us/library/hh454916/\n *\n * POINTER_INFO Structure\n * http://msdn.microsoft.com/en-us/library/hh454907/\n *\n * POINTER_TOUCH_INFO Structure\n * http://msdn.microsoft.com/en-us/library/hh454910/\n */", "#define MAX_CONTACTS 512", "struct _RDPEI_CHANNEL_CALLBACK\n{\n\tIWTSVirtualChannelCallback iface;", "\tIWTSPlugin* plugin;\n\tIWTSVirtualChannelManager* channel_mgr;\n\tIWTSVirtualChannel* channel;\n};\ntypedef struct _RDPEI_CHANNEL_CALLBACK RDPEI_CHANNEL_CALLBACK;", "struct _RDPEI_LISTENER_CALLBACK\n{\n\tIWTSListenerCallback iface;", "\tIWTSPlugin* plugin;\n\tIWTSVirtualChannelManager* channel_mgr;\n\tRDPEI_CHANNEL_CALLBACK* channel_callback;\n};\ntypedef struct _RDPEI_LISTENER_CALLBACK RDPEI_LISTENER_CALLBACK;", "struct _RDPEI_PLUGIN\n{\n\tIWTSPlugin iface;", "\tIWTSListener* listener;\n\tRDPEI_LISTENER_CALLBACK* listener_callback;", "\tRdpeiClientContext* context;", "\tint version;\n\tUINT16 maxTouchContacts;\n\tUINT64 currentFrameTime;\n\tUINT64 previousFrameTime;\n\tRDPINPUT_TOUCH_FRAME frame;\n\tRDPINPUT_CONTACT_DATA contacts[MAX_CONTACTS];\n\tRDPINPUT_CONTACT_POINT* contactPoints;", "\trdpContext* rdpcontext;\n};\ntypedef struct _RDPEI_PLUGIN RDPEI_PLUGIN;", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_send_frame(RdpeiClientContext* context);", "#ifdef WITH_DEBUG_RDPEI\nstatic const char* rdpei_eventid_string(UINT16 event)\n{\n\tswitch (event)\n\t{\n\t\tcase EVENTID_SC_READY:\n\t\t\treturn \"EVENTID_SC_READY\";\n\t\tcase EVENTID_CS_READY:\n\t\t\treturn \"EVENTID_CS_READY\";\n\t\tcase EVENTID_TOUCH:\n\t\t\treturn \"EVENTID_TOUCH\";\n\t\tcase EVENTID_SUSPEND_TOUCH:\n\t\t\treturn \"EVENTID_SUSPEND_TOUCH\";\n\t\tcase EVENTID_RESUME_TOUCH:\n\t\t\treturn \"EVENTID_RESUME_TOUCH\";\n\t\tcase EVENTID_DISMISS_HOVERING_CONTACT:\n\t\t\treturn \"EVENTID_DISMISS_HOVERING_CONTACT\";\n\t\tdefault:\n\t\t\treturn \"EVENTID_UNKNOWN\";\n\t}\n}\n#endif", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_add_frame(RdpeiClientContext* context)\n{\n\tint i;\n\tRDPINPUT_CONTACT_DATA* contact;\n\tRDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle;\n\trdpei->frame.contactCount = 0;", "\tfor (i = 0; i < rdpei->maxTouchContacts; i++)\n\t{\n\t\tcontact = (RDPINPUT_CONTACT_DATA*)&(rdpei->contactPoints[i].data);", "\t\tif (rdpei->contactPoints[i].dirty)\n\t\t{\n\t\t\tCopyMemory(&(rdpei->contacts[rdpei->frame.contactCount]), contact,\n\t\t\t sizeof(RDPINPUT_CONTACT_DATA));\n\t\t\trdpei->contactPoints[i].dirty = FALSE;\n\t\t\trdpei->frame.contactCount++;\n\t\t}\n\t\telse if (rdpei->contactPoints[i].active)\n\t\t{\n\t\t\tif (contact->contactFlags & CONTACT_FLAG_DOWN)\n\t\t\t{\n\t\t\t\tcontact->contactFlags = CONTACT_FLAG_UPDATE;\n\t\t\t\tcontact->contactFlags |= CONTACT_FLAG_INRANGE;\n\t\t\t\tcontact->contactFlags |= CONTACT_FLAG_INCONTACT;\n\t\t\t}", "\t\t\tCopyMemory(&(rdpei->contacts[rdpei->frame.contactCount]), contact,\n\t\t\t sizeof(RDPINPUT_CONTACT_DATA));\n\t\t\trdpei->frame.contactCount++;\n\t\t}\n\t}", "\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_send_pdu(RDPEI_CHANNEL_CALLBACK* callback, wStream* s, UINT16 eventId,\n UINT32 pduLength)\n{\n\tUINT status;\n\tStream_SetPosition(s, 0);\n\tStream_Write_UINT16(s, eventId); /* eventId (2 bytes) */\n\tStream_Write_UINT32(s, pduLength); /* pduLength (4 bytes) */\n\tStream_SetPosition(s, Stream_Length(s));\n\tstatus = callback->channel->Write(callback->channel, (UINT32)Stream_Length(s), Stream_Buffer(s),\n\t NULL);\n#ifdef WITH_DEBUG_RDPEI\n\tWLog_DBG(TAG,\n\t \"rdpei_send_pdu: eventId: %\" PRIu16 \" (%s) length: %\" PRIu32 \" status: %\" PRIu32 \"\",\n\t eventId, rdpei_eventid_string(eventId), pduLength, status);\n#endif\n\treturn status;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_send_cs_ready_pdu(RDPEI_CHANNEL_CALLBACK* callback)\n{\n\tUINT status;\n\twStream* s;\n\tUINT32 flags;\n\tUINT32 pduLength;\n\tRDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)callback->plugin;\n\tflags = 0;\n\tflags |= READY_FLAGS_SHOW_TOUCH_VISUALS;\n\t// flags |= READY_FLAGS_DISABLE_TIMESTAMP_INJECTION;\n\tpduLength = RDPINPUT_HEADER_LENGTH + 10;\n\ts = Stream_New(NULL, pduLength);", "\tif (!s)\n\t{\n\t\tWLog_ERR(TAG, \"Stream_New failed!\");\n\t\treturn CHANNEL_RC_NO_MEMORY;\n\t}", "\tStream_Seek(s, RDPINPUT_HEADER_LENGTH);\n\tStream_Write_UINT32(s, flags); /* flags (4 bytes) */\n\tStream_Write_UINT32(s, RDPINPUT_PROTOCOL_V10); /* protocolVersion (4 bytes) */\n\tStream_Write_UINT16(s, rdpei->maxTouchContacts); /* maxTouchContacts (2 bytes) */\n\tStream_SealLength(s);\n\tstatus = rdpei_send_pdu(callback, s, EVENTID_CS_READY, pduLength);\n\tStream_Free(s, TRUE);\n\treturn status;\n}", "static void rdpei_print_contact_flags(UINT32 contactFlags)\n{\n\tif (contactFlags & CONTACT_FLAG_DOWN)\n\t\tWLog_DBG(TAG, \" CONTACT_FLAG_DOWN\");", "\tif (contactFlags & CONTACT_FLAG_UPDATE)\n\t\tWLog_DBG(TAG, \" CONTACT_FLAG_UPDATE\");", "\tif (contactFlags & CONTACT_FLAG_UP)\n\t\tWLog_DBG(TAG, \" CONTACT_FLAG_UP\");", "\tif (contactFlags & CONTACT_FLAG_INRANGE)\n\t\tWLog_DBG(TAG, \" CONTACT_FLAG_INRANGE\");", "\tif (contactFlags & CONTACT_FLAG_INCONTACT)\n\t\tWLog_DBG(TAG, \" CONTACT_FLAG_INCONTACT\");", "\tif (contactFlags & CONTACT_FLAG_CANCELED)\n\t\tWLog_DBG(TAG, \" CONTACT_FLAG_CANCELED\");\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_write_touch_frame(wStream* s, RDPINPUT_TOUCH_FRAME* frame)\n{\n\tUINT32 index;\n\tint rectSize = 2;\n\tRDPINPUT_CONTACT_DATA* contact;\n#ifdef WITH_DEBUG_RDPEI\n\tWLog_DBG(TAG, \"contactCount: %\" PRIu32 \"\", frame->contactCount);\n\tWLog_DBG(TAG, \"frameOffset: 0x%016\" PRIX64 \"\", frame->frameOffset);\n#endif\n\trdpei_write_2byte_unsigned(s,\n\t frame->contactCount); /* contactCount (TWO_BYTE_UNSIGNED_INTEGER) */\n\t/**\n\t * the time offset from the previous frame (in microseconds).\n\t * If this is the first frame being transmitted then this field MUST be set to zero.\n\t */\n\trdpei_write_8byte_unsigned(s, frame->frameOffset *\n\t 1000); /* frameOffset (EIGHT_BYTE_UNSIGNED_INTEGER) */", "\tif (!Stream_EnsureRemainingCapacity(s, (size_t)frame->contactCount * 64))\n\t{\n\t\tWLog_ERR(TAG, \"Stream_EnsureRemainingCapacity failed!\");\n\t\treturn CHANNEL_RC_NO_MEMORY;\n\t}", "\tfor (index = 0; index < frame->contactCount; index++)\n\t{\n\t\tcontact = &frame->contacts[index];\n\t\tcontact->fieldsPresent |= CONTACT_DATA_CONTACTRECT_PRESENT;\n\t\tcontact->contactRectLeft = contact->x - rectSize;\n\t\tcontact->contactRectTop = contact->y - rectSize;\n\t\tcontact->contactRectRight = contact->x + rectSize;\n\t\tcontact->contactRectBottom = contact->y + rectSize;\n#ifdef WITH_DEBUG_RDPEI\n\t\tWLog_DBG(TAG, \"contact[%\" PRIu32 \"].contactId: %\" PRIu32 \"\", index, contact->contactId);\n\t\tWLog_DBG(TAG, \"contact[%\" PRIu32 \"].fieldsPresent: %\" PRIu32 \"\", index,\n\t\t contact->fieldsPresent);\n\t\tWLog_DBG(TAG, \"contact[%\" PRIu32 \"].x: %\" PRId32 \"\", index, contact->x);\n\t\tWLog_DBG(TAG, \"contact[%\" PRIu32 \"].y: %\" PRId32 \"\", index, contact->y);\n\t\tWLog_DBG(TAG, \"contact[%\" PRIu32 \"].contactFlags: 0x%08\" PRIX32 \"\", index,\n\t\t contact->contactFlags);\n\t\trdpei_print_contact_flags(contact->contactFlags);\n#endif\n\t\tStream_Write_UINT8(s, contact->contactId); /* contactId (1 byte) */\n\t\t/* fieldsPresent (TWO_BYTE_UNSIGNED_INTEGER) */\n\t\trdpei_write_2byte_unsigned(s, contact->fieldsPresent);\n\t\trdpei_write_4byte_signed(s, contact->x); /* x (FOUR_BYTE_SIGNED_INTEGER) */\n\t\trdpei_write_4byte_signed(s, contact->y); /* y (FOUR_BYTE_SIGNED_INTEGER) */\n\t\t/* contactFlags (FOUR_BYTE_UNSIGNED_INTEGER) */\n\t\trdpei_write_4byte_unsigned(s, contact->contactFlags);", "\t\tif (contact->fieldsPresent & CONTACT_DATA_CONTACTRECT_PRESENT)\n\t\t{\n\t\t\t/* contactRectLeft (TWO_BYTE_SIGNED_INTEGER) */\n\t\t\trdpei_write_2byte_signed(s, contact->contactRectLeft);\n\t\t\t/* contactRectTop (TWO_BYTE_SIGNED_INTEGER) */\n\t\t\trdpei_write_2byte_signed(s, contact->contactRectTop);\n\t\t\t/* contactRectRight (TWO_BYTE_SIGNED_INTEGER) */\n\t\t\trdpei_write_2byte_signed(s, contact->contactRectRight);\n\t\t\t/* contactRectBottom (TWO_BYTE_SIGNED_INTEGER) */\n\t\t\trdpei_write_2byte_signed(s, contact->contactRectBottom);\n\t\t}", "\t\tif (contact->fieldsPresent & CONTACT_DATA_ORIENTATION_PRESENT)\n\t\t{\n\t\t\t/* orientation (FOUR_BYTE_UNSIGNED_INTEGER) */\n\t\t\trdpei_write_4byte_unsigned(s, contact->orientation);\n\t\t}", "\t\tif (contact->fieldsPresent & CONTACT_DATA_PRESSURE_PRESENT)\n\t\t{\n\t\t\t/* pressure (FOUR_BYTE_UNSIGNED_INTEGER) */\n\t\t\trdpei_write_4byte_unsigned(s, contact->pressure);\n\t\t}\n\t}", "\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_send_touch_event_pdu(RDPEI_CHANNEL_CALLBACK* callback,\n RDPINPUT_TOUCH_FRAME* frame)\n{\n\tUINT status;\n\twStream* s;\n\tUINT32 pduLength;\n\tpduLength = 64 + (frame->contactCount * 64);\n\ts = Stream_New(NULL, pduLength);", "\tif (!s)\n\t{\n\t\tWLog_ERR(TAG, \"Stream_New failed!\");\n\t\treturn CHANNEL_RC_NO_MEMORY;\n\t}", "\tStream_Seek(s, RDPINPUT_HEADER_LENGTH);\n\t/**\n\t * the time that has elapsed (in milliseconds) from when the oldest touch frame\n\t * was generated to when it was encoded for transmission by the client.\n\t */\n\trdpei_write_4byte_unsigned(\n\t s, (UINT32)frame->frameOffset); /* encodeTime (FOUR_BYTE_UNSIGNED_INTEGER) */\n\trdpei_write_2byte_unsigned(s, 1); /* (frameCount) TWO_BYTE_UNSIGNED_INTEGER */", "\tif ((status = rdpei_write_touch_frame(s, frame)))\n\t{\n\t\tWLog_ERR(TAG, \"rdpei_write_touch_frame failed with error %\" PRIu32 \"!\", status);\n\t\tStream_Free(s, TRUE);\n\t\treturn status;\n\t}", "\tStream_SealLength(s);\n\tpduLength = Stream_Length(s);\n\tstatus = rdpei_send_pdu(callback, s, EVENTID_TOUCH, pduLength);\n\tStream_Free(s, TRUE);\n\treturn status;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_recv_sc_ready_pdu(RDPEI_CHANNEL_CALLBACK* callback, wStream* s)\n{\n\tUINT32 protocolVersion;\n\tStream_Read_UINT32(s, protocolVersion); /* protocolVersion (4 bytes) */\n#if 0", "\tif (protocolVersion != RDPINPUT_PROTOCOL_V10)\n\t{\n\t\tWLog_ERR(TAG, \"Unknown [MS-RDPEI] protocolVersion: 0x%08\"PRIX32\"\", protocolVersion);\n\t\treturn -1;\n\t}", "#endif\n\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_recv_suspend_touch_pdu(RDPEI_CHANNEL_CALLBACK* callback, wStream* s)\n{\n\tRdpeiClientContext* rdpei = (RdpeiClientContext*)callback->plugin->pInterface;\n\tUINT error = CHANNEL_RC_OK;\n\tIFCALLRET(rdpei->SuspendTouch, error, rdpei);", "\tif (error)\n\t\tWLog_ERR(TAG, \"rdpei->SuspendTouch failed with error %\" PRIu32 \"!\", error);", "\treturn error;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_recv_resume_touch_pdu(RDPEI_CHANNEL_CALLBACK* callback, wStream* s)\n{\n\tRdpeiClientContext* rdpei = (RdpeiClientContext*)callback->plugin->pInterface;\n\tUINT error = CHANNEL_RC_OK;\n\tIFCALLRET(rdpei->ResumeTouch, error, rdpei);", "\tif (error)\n\t\tWLog_ERR(TAG, \"rdpei->ResumeTouch failed with error %\" PRIu32 \"!\", error);", "\treturn error;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_recv_pdu(RDPEI_CHANNEL_CALLBACK* callback, wStream* s)\n{\n\tUINT16 eventId;\n\tUINT32 pduLength;\n\tUINT error;", "\tif (Stream_GetRemainingLength(s) < 6)\n\t\treturn ERROR_INVALID_DATA;\n", "\tStream_Read_UINT16(s, eventId); /* eventId (2 bytes) */\n\tStream_Read_UINT32(s, pduLength); /* pduLength (4 bytes) */\n#ifdef WITH_DEBUG_RDPEI\n\tWLog_DBG(TAG, \"rdpei_recv_pdu: eventId: %\" PRIu16 \" (%s) length: %\" PRIu32 \"\", eventId,\n\t rdpei_eventid_string(eventId), pduLength);\n#endif", "\tswitch (eventId)\n\t{\n\t\tcase EVENTID_SC_READY:\n\t\t\tif ((error = rdpei_recv_sc_ready_pdu(callback, s)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"rdpei_recv_sc_ready_pdu failed with error %\" PRIu32 \"!\", error);\n\t\t\t\treturn error;\n\t\t\t}", "\t\t\tif ((error = rdpei_send_cs_ready_pdu(callback)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"rdpei_send_cs_ready_pdu failed with error %\" PRIu32 \"!\", error);\n\t\t\t\treturn error;\n\t\t\t}", "\t\t\tbreak;", "\t\tcase EVENTID_SUSPEND_TOUCH:\n\t\t\tif ((error = rdpei_recv_suspend_touch_pdu(callback, s)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"rdpei_recv_suspend_touch_pdu failed with error %\" PRIu32 \"!\", error);\n\t\t\t\treturn error;\n\t\t\t}", "\t\t\tbreak;", "\t\tcase EVENTID_RESUME_TOUCH:\n\t\t\tif ((error = rdpei_recv_resume_touch_pdu(callback, s)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"rdpei_recv_resume_touch_pdu failed with error %\" PRIu32 \"!\", error);\n\t\t\t\treturn error;\n\t\t\t}", "\t\t\tbreak;", "\t\tdefault:\n\t\t\tbreak;\n\t}", "\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_on_data_received(IWTSVirtualChannelCallback* pChannelCallback, wStream* data)\n{\n\tRDPEI_CHANNEL_CALLBACK* callback = (RDPEI_CHANNEL_CALLBACK*)pChannelCallback;\n\treturn rdpei_recv_pdu(callback, data);\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_on_close(IWTSVirtualChannelCallback* pChannelCallback)\n{\n\tRDPEI_CHANNEL_CALLBACK* callback = (RDPEI_CHANNEL_CALLBACK*)pChannelCallback;\n\tfree(callback);\n\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_on_new_channel_connection(IWTSListenerCallback* pListenerCallback,\n IWTSVirtualChannel* pChannel, BYTE* Data,\n BOOL* pbAccept, IWTSVirtualChannelCallback** ppCallback)\n{\n\tRDPEI_CHANNEL_CALLBACK* callback;\n\tRDPEI_LISTENER_CALLBACK* listener_callback = (RDPEI_LISTENER_CALLBACK*)pListenerCallback;\n\tcallback = (RDPEI_CHANNEL_CALLBACK*)calloc(1, sizeof(RDPEI_CHANNEL_CALLBACK));", "\tif (!callback)\n\t{\n\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\treturn CHANNEL_RC_NO_MEMORY;\n\t}", "\tcallback->iface.OnDataReceived = rdpei_on_data_received;\n\tcallback->iface.OnClose = rdpei_on_close;\n\tcallback->plugin = listener_callback->plugin;\n\tcallback->channel_mgr = listener_callback->channel_mgr;\n\tcallback->channel = pChannel;\n\tlistener_callback->channel_callback = callback;\n\t*ppCallback = (IWTSVirtualChannelCallback*)callback;\n\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_plugin_initialize(IWTSPlugin* pPlugin, IWTSVirtualChannelManager* pChannelMgr)\n{\n\tUINT error;\n\tRDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)pPlugin;\n\trdpei->listener_callback = (RDPEI_LISTENER_CALLBACK*)calloc(1, sizeof(RDPEI_LISTENER_CALLBACK));", "\tif (!rdpei->listener_callback)\n\t{\n\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\treturn CHANNEL_RC_NO_MEMORY;\n\t}", "\trdpei->listener_callback->iface.OnNewChannelConnection = rdpei_on_new_channel_connection;\n\trdpei->listener_callback->plugin = pPlugin;\n\trdpei->listener_callback->channel_mgr = pChannelMgr;", "\tif ((error = pChannelMgr->CreateListener(pChannelMgr, RDPEI_DVC_CHANNEL_NAME, 0,\n\t (IWTSListenerCallback*)rdpei->listener_callback,\n\t &(rdpei->listener))))\n\t{\n\t\tWLog_ERR(TAG, \"ChannelMgr->CreateListener failed with error %\" PRIu32 \"!\", error);\n\t\tgoto error_out;\n\t}", "\trdpei->listener->pInterface = rdpei->iface.pInterface;", "\treturn error;\nerror_out:\n\tfree(rdpei->listener_callback);\n\treturn error;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_plugin_terminated(IWTSPlugin* pPlugin)\n{\n\tRDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)pPlugin;", "\tif (!pPlugin)\n\t\treturn ERROR_INVALID_PARAMETER;", "\tfree(rdpei->listener_callback);\n\tfree(rdpei->context);\n\tfree(rdpei);\n\treturn CHANNEL_RC_OK;\n}", "/**\n * Channel Client Interface\n */", "static int rdpei_get_version(RdpeiClientContext* context)\n{\n\tRDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle;\n\treturn rdpei->version;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nUINT rdpei_send_frame(RdpeiClientContext* context)\n{\n\tUINT64 currentTime;\n\tRDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle;\n\tRDPEI_CHANNEL_CALLBACK* callback = rdpei->listener_callback->channel_callback;\n\tUINT error;\n\tcurrentTime = GetTickCount64();", "\tif (!rdpei->previousFrameTime && !rdpei->currentFrameTime)\n\t{\n\t\trdpei->currentFrameTime = currentTime;\n\t\trdpei->frame.frameOffset = 0;\n\t}\n\telse\n\t{\n\t\trdpei->currentFrameTime = currentTime;\n\t\trdpei->frame.frameOffset = rdpei->currentFrameTime - rdpei->previousFrameTime;\n\t}", "\tif ((error = rdpei_send_touch_event_pdu(callback, &rdpei->frame)))\n\t{\n\t\tWLog_ERR(TAG, \"rdpei_send_touch_event_pdu failed with error %\" PRIu32 \"!\", error);\n\t\treturn error;\n\t}", "\trdpei->previousFrameTime = rdpei->currentFrameTime;\n\trdpei->frame.contactCount = 0;\n\treturn error;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_add_contact(RdpeiClientContext* context, const RDPINPUT_CONTACT_DATA* contact)\n{\n\tUINT error;\n\tRDPINPUT_CONTACT_POINT* contactPoint;\n\tRDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle;", "\tcontactPoint = (RDPINPUT_CONTACT_POINT*)&rdpei->contactPoints[contact->contactId];\n\tCopyMemory(&(contactPoint->data), contact, sizeof(RDPINPUT_CONTACT_DATA));\n\tcontactPoint->dirty = TRUE;", "\terror = rdpei_add_frame(context);\n\tif (error != CHANNEL_RC_OK)\n\t{\n\t\tWLog_ERR(TAG, \"rdpei_add_frame failed with error %\" PRIu32 \"!\", error);\n\t\treturn error;\n\t}", "\tif (rdpei->frame.contactCount > 0)\n\t{\n\t\terror = rdpei_send_frame(context);\n\t\tif (error != CHANNEL_RC_OK)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"rdpei_send_frame failed with error %\" PRIu32 \"!\", error);\n\t\t\treturn error;\n\t\t}\n\t}\n\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_touch_begin(RdpeiClientContext* context, int externalId, int x, int y,\n int* contactId)\n{\n\tunsigned int i;\n\tINT64 contactIdlocal = -1;\n\tRDPINPUT_CONTACT_DATA contact;\n\tRDPINPUT_CONTACT_POINT* contactPoint = NULL;\n\tRDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle;\n\tUINT error = CHANNEL_RC_OK;", "\t/* Create a new contact point in an empty slot */", "\tfor (i = 0; i < rdpei->maxTouchContacts; i++)\n\t{\n\t\tcontactPoint = (RDPINPUT_CONTACT_POINT*)&rdpei->contactPoints[i];", "\t\tif (!contactPoint->active)\n\t\t{\n\t\t\tcontactPoint->contactId = i;\n\t\t\tcontactIdlocal = contactPoint->contactId;\n\t\t\tcontactPoint->externalId = externalId;\n\t\t\tcontactPoint->active = TRUE;\n\t\t\tcontactPoint->state = RDPINPUT_CONTACT_STATE_ENGAGED;\n\t\t\tbreak;\n\t\t}\n\t}", "\tif (contactIdlocal >= 0)\n\t{\n\t\tZeroMemory(&contact, sizeof(RDPINPUT_CONTACT_DATA));\n\t\tcontactPoint->lastX = x;\n\t\tcontactPoint->lastY = y;\n\t\tcontact.x = x;\n\t\tcontact.y = y;\n\t\tcontact.contactId = (UINT32)contactIdlocal;\n\t\tcontact.contactFlags |= CONTACT_FLAG_DOWN;\n\t\tcontact.contactFlags |= CONTACT_FLAG_INRANGE;\n\t\tcontact.contactFlags |= CONTACT_FLAG_INCONTACT;\n\t\terror = context->AddContact(context, &contact);\n\t}", "\t*contactId = contactIdlocal;\n\treturn error;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_touch_update(RdpeiClientContext* context, int externalId, int x, int y,\n int* contactId)\n{\n\tunsigned int i;\n\tint contactIdlocal = -1;\n\tRDPINPUT_CONTACT_DATA contact;\n\tRDPINPUT_CONTACT_POINT* contactPoint = NULL;\n\tRDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle;\n\tUINT error = CHANNEL_RC_OK;", "\tfor (i = 0; i < rdpei->maxTouchContacts; i++)\n\t{\n\t\tcontactPoint = (RDPINPUT_CONTACT_POINT*)&rdpei->contactPoints[i];", "\t\tif (!contactPoint->active)\n\t\t\tcontinue;", "\t\tif (contactPoint->externalId == externalId)\n\t\t{\n\t\t\tcontactIdlocal = contactPoint->contactId;\n\t\t\tbreak;\n\t\t}\n\t}", "\tif (contactIdlocal >= 0)\n\t{\n\t\tZeroMemory(&contact, sizeof(RDPINPUT_CONTACT_DATA));\n\t\tcontactPoint->lastX = x;\n\t\tcontactPoint->lastY = y;\n\t\tcontact.x = x;\n\t\tcontact.y = y;\n\t\tcontact.contactId = (UINT32)contactIdlocal;\n\t\tcontact.contactFlags |= CONTACT_FLAG_UPDATE;\n\t\tcontact.contactFlags |= CONTACT_FLAG_INRANGE;\n\t\tcontact.contactFlags |= CONTACT_FLAG_INCONTACT;\n\t\terror = context->AddContact(context, &contact);\n\t}", "\t*contactId = contactIdlocal;\n\treturn error;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT rdpei_touch_end(RdpeiClientContext* context, int externalId, int x, int y,\n int* contactId)\n{\n\tunsigned int i;\n\tint contactIdlocal = -1;\n\tint tempvalue;\n\tRDPINPUT_CONTACT_DATA contact;\n\tRDPINPUT_CONTACT_POINT* contactPoint = NULL;\n\tRDPEI_PLUGIN* rdpei = (RDPEI_PLUGIN*)context->handle;\n\tUINT error;", "\tfor (i = 0; i < rdpei->maxTouchContacts; i++)\n\t{\n\t\tcontactPoint = (RDPINPUT_CONTACT_POINT*)&rdpei->contactPoints[i];", "\t\tif (!contactPoint->active)\n\t\t\tcontinue;", "\t\tif (contactPoint->externalId == externalId)\n\t\t{\n\t\t\tcontactIdlocal = contactPoint->contactId;\n\t\t\tbreak;\n\t\t}\n\t}", "\tif (contactIdlocal >= 0)\n\t{\n\t\tZeroMemory(&contact, sizeof(RDPINPUT_CONTACT_DATA));", "\t\tif ((contactPoint->lastX != x) && (contactPoint->lastY != y))\n\t\t{\n\t\t\tif ((error = context->TouchUpdate(context, externalId, x, y, &tempvalue)))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"context->TouchUpdate failed with error %\" PRIu32 \"!\", error);\n\t\t\t\treturn error;\n\t\t\t}\n\t\t}", "\t\tcontact.x = x;\n\t\tcontact.y = y;\n\t\tcontact.contactId = (UINT32)contactIdlocal;\n\t\tcontact.contactFlags |= CONTACT_FLAG_UP;", "\t\tif ((error = context->AddContact(context, &contact)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"context->AddContact failed with error %\" PRIu32 \"!\", error);\n\t\t\treturn error;\n\t\t}", "\t\tcontactPoint->externalId = 0;\n\t\tcontactPoint->active = FALSE;\n\t\tcontactPoint->flags = 0;\n\t\tcontactPoint->contactId = 0;\n\t\tcontactPoint->state = RDPINPUT_CONTACT_STATE_OUT_OF_RANGE;\n\t}", "\t*contactId = contactIdlocal;\n\treturn CHANNEL_RC_OK;\n}", "#ifdef BUILTIN_CHANNELS\n#define DVCPluginEntry rdpei_DVCPluginEntry\n#else\n#define DVCPluginEntry FREERDP_API DVCPluginEntry\n#endif", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nUINT DVCPluginEntry(IDRDYNVC_ENTRY_POINTS* pEntryPoints)\n{\n\tUINT error;\n\tRDPEI_PLUGIN* rdpei = NULL;\n\tRdpeiClientContext* context = NULL;\n\trdpei = (RDPEI_PLUGIN*)pEntryPoints->GetPlugin(pEntryPoints, \"rdpei\");", "\tif (!rdpei)\n\t{\n\t\tsize_t size;\n\t\trdpei = (RDPEI_PLUGIN*)calloc(1, sizeof(RDPEI_PLUGIN));", "\t\tif (!rdpei)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}", "\t\trdpei->iface.Initialize = rdpei_plugin_initialize;\n\t\trdpei->iface.Connected = NULL;\n\t\trdpei->iface.Disconnected = NULL;\n\t\trdpei->iface.Terminated = rdpei_plugin_terminated;\n\t\trdpei->version = 1;\n\t\trdpei->currentFrameTime = 0;\n\t\trdpei->previousFrameTime = 0;\n\t\trdpei->frame.contacts = (RDPINPUT_CONTACT_DATA*)rdpei->contacts;\n\t\trdpei->maxTouchContacts = 10;\n\t\tsize = rdpei->maxTouchContacts * sizeof(RDPINPUT_CONTACT_POINT);\n\t\trdpei->contactPoints = (RDPINPUT_CONTACT_POINT*)calloc(1, size);\n\t\trdpei->rdpcontext =\n\t\t ((freerdp*)((rdpSettings*)pEntryPoints->GetRdpSettings(pEntryPoints))->instance)\n\t\t ->context;", "\t\tif (!rdpei->contactPoints)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\tgoto error_out;\n\t\t}", "\t\tcontext = (RdpeiClientContext*)calloc(1, sizeof(RdpeiClientContext));", "\t\tif (!context)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\tgoto error_out;\n\t\t}", "\t\tcontext->handle = (void*)rdpei;\n\t\tcontext->GetVersion = rdpei_get_version;\n\t\tcontext->AddContact = rdpei_add_contact;\n\t\tcontext->TouchBegin = rdpei_touch_begin;\n\t\tcontext->TouchUpdate = rdpei_touch_update;\n\t\tcontext->TouchEnd = rdpei_touch_end;\n\t\trdpei->iface.pInterface = (void*)context;", "\t\tif ((error = pEntryPoints->RegisterPlugin(pEntryPoints, \"rdpei\", (IWTSPlugin*)rdpei)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"EntryPoints->RegisterPlugin failed with error %\" PRIu32 \"!\", error);\n\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\tgoto error_out;\n\t\t}", "\t\trdpei->context = context;\n\t}", "\treturn CHANNEL_RC_OK;\nerror_out:\n\tfree(context);\n\tfree(rdpei->contactPoints);\n\tfree(rdpei);\n\treturn error;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [357, 496, 447, 322, 308, 1001], "buggy_code_start_loc": [333, 480, 447, 145, 307, 94], "filenames": ["channels/drive/client/drive_main.c", "channels/printer/client/printer_main.c", "channels/rdpei/client/rdpei_main.c", "channels/serial/client/serial_main.c", "libfreerdp/core/gateway/rdg.c", "libfreerdp/core/nego.c"], "fixing_code_end_loc": [361, 502, 451, 327, 309, 1013], "fixing_code_start_loc": [334, 481, 448, 145, 307, 94], "message": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:freerdp:freerdp:*:*:*:*:*:*:*:*", "matchCriteriaId": "5C5F8D57-1D22-42B4-9E08-9131F7BE8FA5", "versionEndExcluding": "2.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "B620311B-34A3-48A6-82DF-6F078D7A4493", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0."}, {"lang": "es", "value": "En FreeRDP versiones anteriores a 2.1.0, se presenta una lectura fuera de l\u00edmite en las funciones de irp (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). Esto ha sido corregido en la versi\u00f3n 2.1.0."}], "evaluatorComment": null, "id": "CVE-2020-11089", "lastModified": "2022-07-19T11:52:15.420", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:L/I:L/A:L", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 2.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-05-29T20:15:11.017", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2020-07/msg00080.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/795842f4096501fcefc1a7f535ccc8132feb31d7"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/security/advisories/GHSA-hfc7-c5gv-8c2h"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-125"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, "type": "CWE-125"}
320
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * FreeRDP: A Remote Desktop Protocol Implementation\n * Serial Port Device Service Virtual Channel\n *\n * Copyright 2011 O.S. Systems Software Ltda.\n * Copyright 2011 Eduardo Fiss Beloni <beloni@ossystems.com.br>\n * Copyright 2014 Hewlett-Packard Development Company, L.P.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */", "#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif", "#include <assert.h>\n#include <errno.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>", "#include <winpr/collections.h>\n#include <winpr/comm.h>\n#include <winpr/crt.h>\n#include <winpr/stream.h>\n#include <winpr/synch.h>\n#include <winpr/thread.h>\n#include <winpr/wlog.h>", "#include <freerdp/freerdp.h>\n#include <freerdp/channels/rdpdr.h>\n#include <freerdp/channels/log.h>", "#define TAG CHANNELS_TAG(\"serial.client\")", "/* TODO: all #ifdef __linux__ could be removed once only some generic\n * functions will be used. Replace CommReadFile by ReadFile,\n * CommWriteFile by WriteFile etc.. */\n#if defined __linux__ && !defined ANDROID", "#define MAX_IRP_THREADS 5", "typedef struct _SERIAL_DEVICE SERIAL_DEVICE;", "struct _SERIAL_DEVICE\n{\n\tDEVICE device;\n\tBOOL permissive;\n\tSERIAL_DRIVER_ID ServerSerialDriverId;\n\tHANDLE* hComm;", "\twLog* log;\n\tHANDLE MainThread;\n\twMessageQueue* MainIrpQueue;", "\t/* one thread per pending IRP and indexed according their CompletionId */\n\twListDictionary* IrpThreads;\n\tUINT32 IrpThreadToBeTerminatedCount;\n\tCRITICAL_SECTION TerminatingIrpThreadsLock;\n\trdpContext* rdpcontext;\n};", "typedef struct _IRP_THREAD_DATA IRP_THREAD_DATA;", "struct _IRP_THREAD_DATA\n{\n\tSERIAL_DEVICE* serial;\n\tIRP* irp;\n};", "static UINT32 _GetLastErrorToIoStatus(SERIAL_DEVICE* serial)\n{\n\t/* http://msdn.microsoft.com/en-us/library/ff547466%28v=vs.85%29.aspx#generic_status_values_for_serial_device_control_requests\n\t */\n\tswitch (GetLastError())\n\t{\n\t\tcase ERROR_BAD_DEVICE:\n\t\t\treturn STATUS_INVALID_DEVICE_REQUEST;", "\t\tcase ERROR_CALL_NOT_IMPLEMENTED:\n\t\t\treturn STATUS_NOT_IMPLEMENTED;", "\t\tcase ERROR_CANCELLED:\n\t\t\treturn STATUS_CANCELLED;", "\t\tcase ERROR_INSUFFICIENT_BUFFER:\n\t\t\treturn STATUS_BUFFER_TOO_SMALL; /* NB: STATUS_BUFFER_SIZE_TOO_SMALL not defined */", "\t\tcase ERROR_INVALID_DEVICE_OBJECT_PARAMETER: /* eg: SerCx2.sys' _purge() */\n\t\t\treturn STATUS_INVALID_DEVICE_STATE;", "\t\tcase ERROR_INVALID_HANDLE:\n\t\t\treturn STATUS_INVALID_DEVICE_REQUEST;", "\t\tcase ERROR_INVALID_PARAMETER:\n\t\t\treturn STATUS_INVALID_PARAMETER;", "\t\tcase ERROR_IO_DEVICE:\n\t\t\treturn STATUS_IO_DEVICE_ERROR;", "\t\tcase ERROR_IO_PENDING:\n\t\t\treturn STATUS_PENDING;", "\t\tcase ERROR_NOT_SUPPORTED:\n\t\t\treturn STATUS_NOT_SUPPORTED;", "\t\tcase ERROR_TIMEOUT:\n\t\t\treturn STATUS_TIMEOUT;\n\t\t\t/* no default */\n\t}", "\tWLog_Print(serial->log, WLOG_DEBUG, \"unexpected last-error: 0x%08\" PRIX32 \"\", GetLastError());\n\treturn STATUS_UNSUCCESSFUL;\n}", "static UINT serial_process_irp_create(SERIAL_DEVICE* serial, IRP* irp)\n{\n\tDWORD DesiredAccess;\n\tDWORD SharedAccess;\n\tDWORD CreateDisposition;\n\tUINT32 PathLength;", "\tif (Stream_GetRemainingLength(irp->input) < 32)\n\t\treturn ERROR_INVALID_DATA;", "\tStream_Read_UINT32(irp->input, DesiredAccess); /* DesiredAccess (4 bytes) */\n\tStream_Seek_UINT64(irp->input); /* AllocationSize (8 bytes) */\n\tStream_Seek_UINT32(irp->input); /* FileAttributes (4 bytes) */\n\tStream_Read_UINT32(irp->input, SharedAccess); /* SharedAccess (4 bytes) */\n\tStream_Read_UINT32(irp->input, CreateDisposition); /* CreateDisposition (4 bytes) */\n\tStream_Seek_UINT32(irp->input); /* CreateOptions (4 bytes) */\n\tStream_Read_UINT32(irp->input, PathLength); /* PathLength (4 bytes) */\n", "\tif (Stream_GetRemainingLength(irp->input) < PathLength)", "\t\treturn ERROR_INVALID_DATA;\n", "\tStream_Seek(irp->input, PathLength); /* Path (variable) */", "\tassert(PathLength == 0); /* MS-RDPESP 2.2.2.2 */\n#ifndef _WIN32\n\t/* Windows 2012 server sends on a first call :\n\t * DesiredAccess = 0x00100080: SYNCHRONIZE | FILE_READ_ATTRIBUTES\n\t * SharedAccess = 0x00000007: FILE_SHARE_DELETE | FILE_SHARE_WRITE | FILE_SHARE_READ\n\t * CreateDisposition = 0x00000001: CREATE_NEW\n\t *\n\t * then Windows 2012 sends :\n\t * DesiredAccess = 0x00120089: SYNCHRONIZE | READ_CONTROL | FILE_READ_ATTRIBUTES |\n\t * FILE_READ_EA | FILE_READ_DATA SharedAccess = 0x00000007: FILE_SHARE_DELETE |\n\t * FILE_SHARE_WRITE | FILE_SHARE_READ CreateDisposition = 0x00000001: CREATE_NEW\n\t *\n\t * assert(DesiredAccess == (GENERIC_READ | GENERIC_WRITE));\n\t * assert(SharedAccess == 0);\n\t * assert(CreateDisposition == OPEN_EXISTING);\n\t *\n\t */\n\tWLog_Print(serial->log, WLOG_DEBUG,\n\t \"DesiredAccess: 0x%\" PRIX32 \", SharedAccess: 0x%\" PRIX32\n\t \", CreateDisposition: 0x%\" PRIX32 \"\",\n\t DesiredAccess, SharedAccess, CreateDisposition);\n\t/* FIXME: As of today only the flags below are supported by CommCreateFileA: */\n\tDesiredAccess = GENERIC_READ | GENERIC_WRITE;\n\tSharedAccess = 0;\n\tCreateDisposition = OPEN_EXISTING;\n#endif\n\tserial->hComm =\n\t CreateFile(serial->device.name, DesiredAccess, SharedAccess, NULL, /* SecurityAttributes */\n\t CreateDisposition, 0, /* FlagsAndAttributes */\n\t NULL); /* TemplateFile */", "\tif (!serial->hComm || (serial->hComm == INVALID_HANDLE_VALUE))\n\t{\n\t\tWLog_Print(serial->log, WLOG_WARN, \"CreateFile failure: %s last-error: 0x%08\" PRIX32 \"\",\n\t\t serial->device.name, GetLastError());\n\t\tirp->IoStatus = STATUS_UNSUCCESSFUL;\n\t\tgoto error_handle;\n\t}", "\t_comm_setServerSerialDriver(serial->hComm, serial->ServerSerialDriverId);\n\t_comm_set_permissive(serial->hComm, serial->permissive);\n\t/* NOTE: binary mode/raw mode required for the redirection. On\n\t * Linux, CommCreateFileA forces this setting.\n\t */\n\t/* ZeroMemory(&dcb, sizeof(DCB)); */\n\t/* dcb.DCBlength = sizeof(DCB); */\n\t/* GetCommState(serial->hComm, &dcb); */\n\t/* dcb.fBinary = TRUE; */\n\t/* SetCommState(serial->hComm, &dcb); */\n\tassert(irp->FileId == 0);\n\tirp->FileId = irp->devman->id_sequence++; /* FIXME: why not ((WINPR_COMM*)hComm)->fd? */\n\tirp->IoStatus = STATUS_SUCCESS;\n\tWLog_Print(serial->log, WLOG_DEBUG, \"%s (DeviceId: %\" PRIu32 \", FileId: %\" PRIu32 \") created.\",\n\t serial->device.name, irp->device->id, irp->FileId);\nerror_handle:\n\tStream_Write_UINT32(irp->output, irp->FileId); /* FileId (4 bytes) */\n\tStream_Write_UINT8(irp->output, 0); /* Information (1 byte) */\n\treturn CHANNEL_RC_OK;\n}", "static UINT serial_process_irp_close(SERIAL_DEVICE* serial, IRP* irp)\n{\n\tif (Stream_GetRemainingLength(irp->input) < 32)\n\t\treturn ERROR_INVALID_DATA;", "\tStream_Seek(irp->input, 32); /* Padding (32 bytes) */", "\tif (!CloseHandle(serial->hComm))\n\t{\n\t\tWLog_Print(serial->log, WLOG_WARN, \"CloseHandle failure: %s (%\" PRIu32 \") closed.\",\n\t\t serial->device.name, irp->device->id);\n\t\tirp->IoStatus = STATUS_UNSUCCESSFUL;\n\t\tgoto error_handle;\n\t}", "\tWLog_Print(serial->log, WLOG_DEBUG, \"%s (DeviceId: %\" PRIu32 \", FileId: %\" PRIu32 \") closed.\",\n\t serial->device.name, irp->device->id, irp->FileId);\n\tserial->hComm = NULL;\n\tirp->IoStatus = STATUS_SUCCESS;\nerror_handle:\n\tStream_Zero(irp->output, 5); /* Padding (5 bytes) */\n\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT serial_process_irp_read(SERIAL_DEVICE* serial, IRP* irp)\n{\n\tUINT32 Length;\n\tUINT64 Offset;\n\tBYTE* buffer = NULL;\n\tDWORD nbRead = 0;", "\tif (Stream_GetRemainingLength(irp->input) < 32)\n\t\treturn ERROR_INVALID_DATA;", "\tStream_Read_UINT32(irp->input, Length); /* Length (4 bytes) */\n\tStream_Read_UINT64(irp->input, Offset); /* Offset (8 bytes) */\n\tStream_Seek(irp->input, 20); /* Padding (20 bytes) */\n\tbuffer = (BYTE*)calloc(Length, sizeof(BYTE));", "\tif (buffer == NULL)\n\t{\n\t\tirp->IoStatus = STATUS_NO_MEMORY;\n\t\tgoto error_handle;\n\t}", "\t/* MS-RDPESP 3.2.5.1.4: If the Offset field is not set to 0, the value MUST be ignored\n\t * assert(Offset == 0);\n\t */\n\tWLog_Print(serial->log, WLOG_DEBUG, \"reading %\" PRIu32 \" bytes from %s\", Length,\n\t serial->device.name);", "\t/* FIXME: CommReadFile to be replaced by ReadFile */\n\tif (CommReadFile(serial->hComm, buffer, Length, &nbRead, NULL))\n\t{\n\t\tirp->IoStatus = STATUS_SUCCESS;\n\t}\n\telse\n\t{\n\t\tWLog_Print(serial->log, WLOG_DEBUG,\n\t\t \"read failure to %s, nbRead=%\" PRIu32 \", last-error: 0x%08\" PRIX32 \"\",\n\t\t serial->device.name, nbRead, GetLastError());\n\t\tirp->IoStatus = _GetLastErrorToIoStatus(serial);\n\t}", "\tWLog_Print(serial->log, WLOG_DEBUG, \"%\" PRIu32 \" bytes read from %s\", nbRead,\n\t serial->device.name);\nerror_handle:\n\tStream_Write_UINT32(irp->output, nbRead); /* Length (4 bytes) */", "\tif (nbRead > 0)\n\t{\n\t\tif (!Stream_EnsureRemainingCapacity(irp->output, nbRead))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"Stream_EnsureRemainingCapacity failed!\");\n\t\t\tfree(buffer);\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}", "\t\tStream_Write(irp->output, buffer, nbRead); /* ReadData */\n\t}", "\tfree(buffer);\n\treturn CHANNEL_RC_OK;\n}", "static UINT serial_process_irp_write(SERIAL_DEVICE* serial, IRP* irp)\n{\n\tUINT32 Length;\n\tUINT64 Offset;", "", "\tDWORD nbWritten = 0;", "\tif (Stream_GetRemainingLength(irp->input) < 32)\n\t\treturn ERROR_INVALID_DATA;", "\tStream_Read_UINT32(irp->input, Length); /* Length (4 bytes) */\n\tStream_Read_UINT64(irp->input, Offset); /* Offset (8 bytes) */", "\tStream_Seek(irp->input, 20); /* Padding (20 bytes) */", "\t/* MS-RDPESP 3.2.5.1.5: The Offset field is ignored\n\t * assert(Offset == 0);\n\t *\n\t * Using a serial printer, noticed though this field could be\n\t * set.\n\t */\n\tWLog_Print(serial->log, WLOG_DEBUG, \"writing %\" PRIu32 \" bytes to %s\", Length,\n\t serial->device.name);\n", "", "\t/* FIXME: CommWriteFile to be replaced by WriteFile */", "\tif (CommWriteFile(serial->hComm, Stream_Pointer(irp->input), Length, &nbWritten, NULL))", "\t{\n\t\tirp->IoStatus = STATUS_SUCCESS;\n\t}\n\telse\n\t{\n\t\tWLog_Print(serial->log, WLOG_DEBUG,\n\t\t \"write failure to %s, nbWritten=%\" PRIu32 \", last-error: 0x%08\" PRIX32 \"\",\n\t\t serial->device.name, nbWritten, GetLastError());\n\t\tirp->IoStatus = _GetLastErrorToIoStatus(serial);\n\t}", "\tWLog_Print(serial->log, WLOG_DEBUG, \"%\" PRIu32 \" bytes written to %s\", nbWritten,\n\t serial->device.name);\n\tStream_Write_UINT32(irp->output, nbWritten); /* Length (4 bytes) */\n\tStream_Write_UINT8(irp->output, 0); /* Padding (1 byte) */\n\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT serial_process_irp_device_control(SERIAL_DEVICE* serial, IRP* irp)\n{\n\tUINT32 IoControlCode;\n\tUINT32 InputBufferLength;\n\tBYTE* InputBuffer = NULL;\n\tUINT32 OutputBufferLength;\n\tBYTE* OutputBuffer = NULL;\n\tDWORD BytesReturned = 0;", "\tif (Stream_GetRemainingLength(irp->input) < 32)\n\t\treturn ERROR_INVALID_DATA;", "\tStream_Read_UINT32(irp->input, OutputBufferLength); /* OutputBufferLength (4 bytes) */\n\tStream_Read_UINT32(irp->input, InputBufferLength); /* InputBufferLength (4 bytes) */\n\tStream_Read_UINT32(irp->input, IoControlCode); /* IoControlCode (4 bytes) */\n\tStream_Seek(irp->input, 20); /* Padding (20 bytes) */", "\tif (Stream_GetRemainingLength(irp->input) < InputBufferLength)\n\t\treturn ERROR_INVALID_DATA;", "\tOutputBuffer = (BYTE*)calloc(OutputBufferLength, sizeof(BYTE));", "\tif (OutputBuffer == NULL)\n\t{\n\t\tirp->IoStatus = STATUS_NO_MEMORY;\n\t\tgoto error_handle;\n\t}", "\tInputBuffer = (BYTE*)calloc(InputBufferLength, sizeof(BYTE));", "\tif (InputBuffer == NULL)\n\t{\n\t\tirp->IoStatus = STATUS_NO_MEMORY;\n\t\tgoto error_handle;\n\t}", "\tStream_Read(irp->input, InputBuffer, InputBufferLength);\n\tWLog_Print(serial->log, WLOG_DEBUG,\n\t \"CommDeviceIoControl: CompletionId=%\" PRIu32 \", IoControlCode=[0x%\" PRIX32 \"] %s\",\n\t irp->CompletionId, IoControlCode, _comm_serial_ioctl_name(IoControlCode));", "\t/* FIXME: CommDeviceIoControl to be replaced by DeviceIoControl() */\n\tif (CommDeviceIoControl(serial->hComm, IoControlCode, InputBuffer, InputBufferLength,\n\t OutputBuffer, OutputBufferLength, &BytesReturned, NULL))\n\t{\n\t\t/* WLog_Print(serial->log, WLOG_DEBUG, \"CommDeviceIoControl: CompletionId=%\"PRIu32\",\n\t\t * IoControlCode=[0x%\"PRIX32\"] %s done\", irp->CompletionId, IoControlCode,\n\t\t * _comm_serial_ioctl_name(IoControlCode)); */\n\t\tirp->IoStatus = STATUS_SUCCESS;\n\t}\n\telse\n\t{\n\t\tWLog_Print(serial->log, WLOG_DEBUG,\n\t\t \"CommDeviceIoControl failure: IoControlCode=[0x%\" PRIX32\n\t\t \"] %s, last-error: 0x%08\" PRIX32 \"\",\n\t\t IoControlCode, _comm_serial_ioctl_name(IoControlCode), GetLastError());\n\t\tirp->IoStatus = _GetLastErrorToIoStatus(serial);\n\t}", "error_handle:\n\t/* FIXME: find out whether it's required or not to get\n\t * BytesReturned == OutputBufferLength when\n\t * CommDeviceIoControl returns FALSE */\n\tassert(OutputBufferLength == BytesReturned);\n\tStream_Write_UINT32(irp->output, BytesReturned); /* OutputBufferLength (4 bytes) */", "\tif (BytesReturned > 0)\n\t{\n\t\tif (!Stream_EnsureRemainingCapacity(irp->output, BytesReturned))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"Stream_EnsureRemainingCapacity failed!\");\n\t\t\tfree(InputBuffer);\n\t\t\tfree(OutputBuffer);\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}", "\t\tStream_Write(irp->output, OutputBuffer, BytesReturned); /* OutputBuffer */\n\t}", "\t/* FIXME: Why at least Windows 2008R2 gets lost with this\n\t * extra byte and likely on a IOCTL_SERIAL_SET_BAUD_RATE? The\n\t * extra byte is well required according MS-RDPEFS\n\t * 2.2.1.5.5 */\n\t/* else */\n\t/* { */\n\t/* \tStream_Write_UINT8(irp->output, 0); /\\* Padding (1 byte) *\\/ */\n\t/* } */\n\tfree(InputBuffer);\n\tfree(OutputBuffer);\n\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT serial_process_irp(SERIAL_DEVICE* serial, IRP* irp)\n{\n\tUINT error = CHANNEL_RC_OK;\n\tWLog_Print(serial->log, WLOG_DEBUG,\n\t \"IRP MajorFunction: 0x%08\" PRIX32 \" MinorFunction: 0x%08\" PRIX32 \"\\n\",\n\t irp->MajorFunction, irp->MinorFunction);", "\tswitch (irp->MajorFunction)\n\t{\n\t\tcase IRP_MJ_CREATE:\n\t\t\terror = serial_process_irp_create(serial, irp);\n\t\t\tbreak;", "\t\tcase IRP_MJ_CLOSE:\n\t\t\terror = serial_process_irp_close(serial, irp);\n\t\t\tbreak;", "\t\tcase IRP_MJ_READ:\n\t\t\tif ((error = serial_process_irp_read(serial, irp)))\n\t\t\t\tWLog_ERR(TAG, \"serial_process_irp_read failed with error %\" PRIu32 \"!\", error);", "\t\t\tbreak;", "\t\tcase IRP_MJ_WRITE:\n\t\t\terror = serial_process_irp_write(serial, irp);\n\t\t\tbreak;", "\t\tcase IRP_MJ_DEVICE_CONTROL:\n\t\t\tif ((error = serial_process_irp_device_control(serial, irp)))\n\t\t\t\tWLog_ERR(TAG, \"serial_process_irp_device_control failed with error %\" PRIu32 \"!\",\n\t\t\t\t error);", "\t\t\tbreak;", "\t\tdefault:\n\t\t\tirp->IoStatus = STATUS_NOT_SUPPORTED;\n\t\t\tbreak;\n\t}", "\treturn error;\n}", "static DWORD WINAPI irp_thread_func(LPVOID arg)\n{\n\tIRP_THREAD_DATA* data = (IRP_THREAD_DATA*)arg;\n\tUINT error;", "\t/* blocks until the end of the request */\n\tif ((error = serial_process_irp(data->serial, data->irp)))\n\t{\n\t\tWLog_ERR(TAG, \"serial_process_irp failed with error %\" PRIu32 \"\", error);\n\t\tgoto error_out;\n\t}", "\tEnterCriticalSection(&data->serial->TerminatingIrpThreadsLock);\n\tdata->serial->IrpThreadToBeTerminatedCount++;\n\terror = data->irp->Complete(data->irp);\n\tLeaveCriticalSection(&data->serial->TerminatingIrpThreadsLock);\nerror_out:", "\tif (error && data->serial->rdpcontext)\n\t\tsetChannelError(data->serial->rdpcontext, error, \"irp_thread_func reported an error\");", "\t/* NB: At this point, the server might already being reusing\n\t * the CompletionId whereas the thread is not yet\n\t * terminated */\n\tfree(data);\n\tExitThread(error);\n\treturn error;\n}", "static void create_irp_thread(SERIAL_DEVICE* serial, IRP* irp)\n{\n\tIRP_THREAD_DATA* data = NULL;\n\tHANDLE irpThread;\n\tHANDLE previousIrpThread;\n\tuintptr_t key;\n\t/* for a test/debug purpose, uncomment the code below to get a\n\t * single thread for all IRPs. NB: two IRPs could not be\n\t * processed at the same time, typically two concurent\n\t * Read/Write operations could block each other. */\n\t/* serial_process_irp(serial, irp); */\n\t/* irp->Complete(irp); */\n\t/* return; */\n\t/* NOTE: for good or bad, this implementation relies on the\n\t * server to avoid a flooding of requests. see also _purge().\n\t */\n\tEnterCriticalSection(&serial->TerminatingIrpThreadsLock);", "\twhile (serial->IrpThreadToBeTerminatedCount > 0)\n\t{\n\t\t/* Cleaning up termitating and pending irp\n\t\t * threads. See also: irp_thread_func() */\n\t\tHANDLE irpThread;\n\t\tULONG_PTR* ids;\n\t\tint i, nbIds;\n\t\tnbIds = ListDictionary_GetKeys(serial->IrpThreads, &ids);", "\t\tfor (i = 0; i < nbIds; i++)\n\t\t{\n\t\t\t/* Checking if ids[i] is terminating or pending */\n\t\t\tDWORD waitResult;\n\t\t\tULONG_PTR id = ids[i];\n\t\t\tirpThread = ListDictionary_GetItemValue(serial->IrpThreads, (void*)id);\n\t\t\t/* FIXME: not quite sure a zero timeout is a good thing to check whether a thread is\n\t\t\t * stil alived or not */\n\t\t\twaitResult = WaitForSingleObject(irpThread, 0);", "\t\t\tif (waitResult == WAIT_OBJECT_0)\n\t\t\t{\n\t\t\t\t/* terminating thread */\n\t\t\t\t/* WLog_Print(serial->log, WLOG_DEBUG, \"IRP thread with CompletionId=%\"PRIuz\"\n\t\t\t\t * naturally died\", id); */\n\t\t\t\tCloseHandle(irpThread);\n\t\t\t\tListDictionary_Remove(serial->IrpThreads, (void*)id);\n\t\t\t\tserial->IrpThreadToBeTerminatedCount--;\n\t\t\t}\n\t\t\telse if (waitResult != WAIT_TIMEOUT)\n\t\t\t{\n\t\t\t\t/* unexpected thread state */\n\t\t\t\tWLog_Print(serial->log, WLOG_WARN,\n\t\t\t\t \"WaitForSingleObject, got an unexpected result=0x%\" PRIX32 \"\\n\",\n\t\t\t\t waitResult);\n\t\t\t\tassert(FALSE);\n\t\t\t}", "\t\t\t/* pending thread (but not yet terminating thread) if waitResult == WAIT_TIMEOUT */\n\t\t}", "\t\tif (serial->IrpThreadToBeTerminatedCount > 0)\n\t\t{\n\t\t\tWLog_Print(serial->log, WLOG_DEBUG, \"%\" PRIu32 \" IRP thread(s) not yet terminated\",\n\t\t\t serial->IrpThreadToBeTerminatedCount);\n\t\t\tSleep(1); /* 1 ms */\n\t\t}", "\t\tfree(ids);\n\t}", "\tLeaveCriticalSection(&serial->TerminatingIrpThreadsLock);\n\t/* NB: At this point and thanks to the synchronization we're\n\t * sure that the incoming IRP uses well a recycled\n\t * CompletionId or the server sent again an IRP already posted\n\t * which didn't get yet a response (this later server behavior\n\t * at least observed with IOCTL_SERIAL_WAIT_ON_MASK and\n\t * mstsc.exe).\n\t *\n\t * FIXME: behavior documented somewhere? behavior not yet\n\t * observed with FreeRDP).\n\t */\n\tkey = irp->CompletionId;\n\tpreviousIrpThread = ListDictionary_GetItemValue(serial->IrpThreads, (void*)key);", "\tif (previousIrpThread)\n\t{\n\t\t/* Thread still alived <=> Request still pending */\n\t\tWLog_Print(serial->log, WLOG_DEBUG,\n\t\t \"IRP recall: IRP with the CompletionId=%\" PRIu32 \" not yet completed!\",\n\t\t irp->CompletionId);\n\t\tassert(FALSE); /* unimplemented */\n\t\t/* TODO: asserts that previousIrpThread handles well\n\t\t * the same request by checking more details. Need an\n\t\t * access to the IRP object used by previousIrpThread\n\t\t */\n\t\t/* TODO: taking over the pending IRP or sending a kind\n\t\t * of wake up signal to accelerate the pending\n\t\t * request\n\t\t *\n\t\t * To be considered:\n\t\t * if (IoControlCode == IOCTL_SERIAL_WAIT_ON_MASK) {\n\t\t * pComm->PendingEvents |= SERIAL_EV_FREERDP_*;\n\t\t * }\n\t\t */\n\t\tirp->Discard(irp);\n\t\treturn;\n\t}", "\tif (ListDictionary_Count(serial->IrpThreads) >= MAX_IRP_THREADS)\n\t{\n\t\tWLog_Print(serial->log, WLOG_WARN,\n\t\t \"Number of IRP threads threshold reached: %d, keep on anyway\",\n\t\t ListDictionary_Count(serial->IrpThreads));\n\t\tassert(FALSE); /* unimplemented */\n\t\t /* TODO: MAX_IRP_THREADS has been thought to avoid a\n\t\t * flooding of pending requests. Use\n\t\t * WaitForMultipleObjects() when available in winpr\n\t\t * for threads.\n\t\t */\n\t}", "\t/* error_handle to be used ... */\n\tdata = (IRP_THREAD_DATA*)calloc(1, sizeof(IRP_THREAD_DATA));", "\tif (data == NULL)\n\t{\n\t\tWLog_Print(serial->log, WLOG_WARN, \"Could not allocate a new IRP_THREAD_DATA.\");\n\t\tgoto error_handle;\n\t}", "\tdata->serial = serial;\n\tdata->irp = irp;\n\t/* data freed by irp_thread_func */\n\tirpThread = CreateThread(NULL, 0, irp_thread_func, (void*)data, 0, NULL);", "\tif (irpThread == INVALID_HANDLE_VALUE)\n\t{\n\t\tWLog_Print(serial->log, WLOG_WARN, \"Could not allocate a new IRP thread.\");\n\t\tgoto error_handle;\n\t}", "\tkey = irp->CompletionId;", "\tif (!ListDictionary_Add(serial->IrpThreads, (void*)key, irpThread))\n\t{\n\t\tWLog_ERR(TAG, \"ListDictionary_Add failed!\");\n\t\tgoto error_handle;\n\t}", "\treturn;\nerror_handle:\n\tirp->IoStatus = STATUS_NO_MEMORY;\n\tirp->Complete(irp);\n\tfree(data);\n}", "static void terminate_pending_irp_threads(SERIAL_DEVICE* serial)\n{\n\tULONG_PTR* ids;\n\tint i, nbIds;\n\tnbIds = ListDictionary_GetKeys(serial->IrpThreads, &ids);\n\tWLog_Print(serial->log, WLOG_DEBUG, \"Terminating %d IRP thread(s)\", nbIds);", "\tfor (i = 0; i < nbIds; i++)\n\t{\n\t\tHANDLE irpThread;\n\t\tULONG_PTR id = ids[i];\n\t\tirpThread = ListDictionary_GetItemValue(serial->IrpThreads, (void*)id);\n\t\tTerminateThread(irpThread, 0);", "\t\tif (WaitForSingleObject(irpThread, INFINITE) == WAIT_FAILED)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"WaitForSingleObject failed!\");\n\t\t\tcontinue;\n\t\t}", "\t\tCloseHandle(irpThread);\n\t\tWLog_Print(serial->log, WLOG_DEBUG, \"IRP thread terminated, CompletionId %p\", (void*)id);\n\t}", "\tListDictionary_Clear(serial->IrpThreads);\n\tfree(ids);\n}", "static DWORD WINAPI serial_thread_func(LPVOID arg)\n{\n\tIRP* irp;\n\twMessage message;\n\tSERIAL_DEVICE* serial = (SERIAL_DEVICE*)arg;\n\tUINT error = CHANNEL_RC_OK;", "\twhile (1)\n\t{\n\t\tif (!MessageQueue_Wait(serial->MainIrpQueue))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"MessageQueue_Wait failed!\");\n\t\t\terror = ERROR_INTERNAL_ERROR;\n\t\t\tbreak;\n\t\t}", "\t\tif (!MessageQueue_Peek(serial->MainIrpQueue, &message, TRUE))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"MessageQueue_Peek failed!\");\n\t\t\terror = ERROR_INTERNAL_ERROR;\n\t\t\tbreak;\n\t\t}", "\t\tif (message.id == WMQ_QUIT)\n\t\t{\n\t\t\tterminate_pending_irp_threads(serial);\n\t\t\tbreak;\n\t\t}", "\t\tirp = (IRP*)message.wParam;", "\t\tif (irp)\n\t\t\tcreate_irp_thread(serial, irp);\n\t}", "\tif (error && serial->rdpcontext)\n\t\tsetChannelError(serial->rdpcontext, error, \"serial_thread_func reported an error\");", "\tExitThread(error);\n\treturn error;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT serial_irp_request(DEVICE* device, IRP* irp)\n{\n\tSERIAL_DEVICE* serial = (SERIAL_DEVICE*)device;\n\tassert(irp != NULL);", "\tif (irp == NULL)\n\t\treturn CHANNEL_RC_OK;", "\t/* NB: ENABLE_ASYNCIO is set, (MS-RDPEFS 2.2.2.7.2) this\n\t * allows the server to send multiple simultaneous read or\n\t * write requests.\n\t */", "\tif (!MessageQueue_Post(serial->MainIrpQueue, NULL, 0, (void*)irp, NULL))\n\t{\n\t\tWLog_ERR(TAG, \"MessageQueue_Post failed!\");\n\t\treturn ERROR_INTERNAL_ERROR;\n\t}", "\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT serial_free(DEVICE* device)\n{\n\tUINT error;\n\tSERIAL_DEVICE* serial = (SERIAL_DEVICE*)device;\n\tWLog_Print(serial->log, WLOG_DEBUG, \"freeing\");\n\tMessageQueue_PostQuit(serial->MainIrpQueue, 0);", "\tif (WaitForSingleObject(serial->MainThread, INFINITE) == WAIT_FAILED)\n\t{\n\t\terror = GetLastError();\n\t\tWLog_ERR(TAG, \"WaitForSingleObject failed with error %\" PRIu32 \"!\", error);\n\t\treturn error;\n\t}", "\tCloseHandle(serial->MainThread);", "\tif (serial->hComm)\n\t\tCloseHandle(serial->hComm);", "\t/* Clean up resources */\n\tStream_Free(serial->device.data, TRUE);\n\tMessageQueue_Free(serial->MainIrpQueue);\n\tListDictionary_Free(serial->IrpThreads);\n\tDeleteCriticalSection(&serial->TerminatingIrpThreadsLock);\n\tfree(serial);\n\treturn CHANNEL_RC_OK;\n}", "#endif /* __linux__ */", "#ifdef BUILTIN_CHANNELS\n#define DeviceServiceEntry serial_DeviceServiceEntry\n#else\n#define DeviceServiceEntry FREERDP_API DeviceServiceEntry\n#endif", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nUINT DeviceServiceEntry(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints)\n{\n\tchar* name;\n\tchar* path;\n\tchar* driver;\n\tRDPDR_SERIAL* device;\n#if defined __linux__ && !defined ANDROID\n\tsize_t i, len;\n\tSERIAL_DEVICE* serial;\n#endif /* __linux__ */\n\tUINT error = CHANNEL_RC_OK;\n\tdevice = (RDPDR_SERIAL*)pEntryPoints->device;\n\tname = device->Name;\n\tpath = device->Path;\n\tdriver = device->Driver;", "\tif (!name || (name[0] == '*'))\n\t{\n\t\t/* TODO: implement auto detection of serial ports */\n\t\treturn CHANNEL_RC_OK;\n\t}", "\tif ((name && name[0]) && (path && path[0]))\n\t{\n\t\twLog* log;\n\t\tlog = WLog_Get(\"com.freerdp.channel.serial.client\");\n\t\tWLog_Print(log, WLOG_DEBUG, \"initializing\");\n#ifndef __linux__ /* to be removed */\n\t\tWLog_Print(log, WLOG_WARN, \"Serial ports redirection not supported on this platform.\");\n\t\treturn CHANNEL_RC_INITIALIZATION_ERROR;\n#else /* __linux __ */\n\t\tWLog_Print(log, WLOG_DEBUG, \"Defining %s as %s\", name, path);", "\t\tif (!DefineCommDevice(name /* eg: COM1 */, path /* eg: /dev/ttyS0 */))\n\t\t{\n\t\t\tDWORD status = GetLastError();\n\t\t\tWLog_ERR(TAG, \"DefineCommDevice failed with %08\" PRIx32, status);\n\t\t\treturn ERROR_INTERNAL_ERROR;\n\t\t}", "\t\tserial = (SERIAL_DEVICE*)calloc(1, sizeof(SERIAL_DEVICE));", "\t\tif (!serial)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}", "\t\tserial->log = log;\n\t\tserial->device.type = RDPDR_DTYP_SERIAL;\n\t\tserial->device.name = name;\n\t\tserial->device.IRPRequest = serial_irp_request;\n\t\tserial->device.Free = serial_free;\n\t\tserial->rdpcontext = pEntryPoints->rdpcontext;\n\t\tlen = strlen(name);\n\t\tserial->device.data = Stream_New(NULL, len + 1);", "\t\tif (!serial->device.data)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\tgoto error_out;\n\t\t}", "\t\tfor (i = 0; i <= len; i++)\n\t\t\tStream_Write_UINT8(serial->device.data, name[i] < 0 ? '_' : name[i]);", "\t\tif (driver != NULL)\n\t\t{\n\t\t\tif (_stricmp(driver, \"Serial\") == 0)\n\t\t\t\tserial->ServerSerialDriverId = SerialDriverSerialSys;\n\t\t\telse if (_stricmp(driver, \"SerCx\") == 0)\n\t\t\t\tserial->ServerSerialDriverId = SerialDriverSerCxSys;\n\t\t\telse if (_stricmp(driver, \"SerCx2\") == 0)\n\t\t\t\tserial->ServerSerialDriverId = SerialDriverSerCx2Sys;\n\t\t\telse\n\t\t\t{\n\t\t\t\tassert(FALSE);\n\t\t\t\tWLog_Print(serial->log, WLOG_DEBUG,\n\t\t\t\t \"Unknown server's serial driver: %s. SerCx2 will be used\", driver);\n\t\t\t\tserial->ServerSerialDriverId = SerialDriverSerialSys;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t/* default driver */\n\t\t\tserial->ServerSerialDriverId = SerialDriverSerialSys;\n\t\t}", "\t\tif (device->Permissive != NULL)\n\t\t{\n\t\t\tif (_stricmp(device->Permissive, \"permissive\") == 0)\n\t\t\t{\n\t\t\t\tserial->permissive = TRUE;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tWLog_Print(serial->log, WLOG_DEBUG, \"Unknown flag: %s\", device->Permissive);\n\t\t\t\tassert(FALSE);\n\t\t\t}\n\t\t}", "\t\tWLog_Print(serial->log, WLOG_DEBUG, \"Server's serial driver: %s (id: %d)\", driver,\n\t\t serial->ServerSerialDriverId);\n\t\t/* TODO: implement auto detection of the server's serial driver */\n\t\tserial->MainIrpQueue = MessageQueue_New(NULL);", "\t\tif (!serial->MainIrpQueue)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"MessageQueue_New failed!\");\n\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\tgoto error_out;\n\t\t}", "\t\t/* IrpThreads content only modified by create_irp_thread() */\n\t\tserial->IrpThreads = ListDictionary_New(FALSE);", "\t\tif (!serial->IrpThreads)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"ListDictionary_New failed!\");\n\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\tgoto error_out;\n\t\t}", "\t\tserial->IrpThreadToBeTerminatedCount = 0;\n\t\tInitializeCriticalSection(&serial->TerminatingIrpThreadsLock);", "\t\tif ((error = pEntryPoints->RegisterDevice(pEntryPoints->devman, (DEVICE*)serial)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"EntryPoints->RegisterDevice failed with error %\" PRIu32 \"!\", error);\n\t\t\tgoto error_out;\n\t\t}", "\t\tif (!(serial->MainThread =\n\t\t CreateThread(NULL, 0, serial_thread_func, (void*)serial, 0, NULL)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"CreateThread failed!\");\n\t\t\terror = ERROR_INTERNAL_ERROR;\n\t\t\tgoto error_out;\n\t\t}", "#endif /* __linux __ */\n\t}", "\treturn error;\nerror_out:\n#ifdef __linux__ /* to be removed */\n\tListDictionary_Free(serial->IrpThreads);\n\tMessageQueue_Free(serial->MainIrpQueue);\n\tStream_Free(serial->device.data, TRUE);\n\tfree(serial);\n#endif /* __linux __ */\n\treturn error;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [357, 496, 447, 322, 308, 1001], "buggy_code_start_loc": [333, 480, 447, 145, 307, 94], "filenames": ["channels/drive/client/drive_main.c", "channels/printer/client/printer_main.c", "channels/rdpei/client/rdpei_main.c", "channels/serial/client/serial_main.c", "libfreerdp/core/gateway/rdg.c", "libfreerdp/core/nego.c"], "fixing_code_end_loc": [361, 502, 451, 327, 309, 1013], "fixing_code_start_loc": [334, 481, 448, 145, 307, 94], "message": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:freerdp:freerdp:*:*:*:*:*:*:*:*", "matchCriteriaId": "5C5F8D57-1D22-42B4-9E08-9131F7BE8FA5", "versionEndExcluding": "2.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "B620311B-34A3-48A6-82DF-6F078D7A4493", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0."}, {"lang": "es", "value": "En FreeRDP versiones anteriores a 2.1.0, se presenta una lectura fuera de l\u00edmite en las funciones de irp (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). Esto ha sido corregido en la versi\u00f3n 2.1.0."}], "evaluatorComment": null, "id": "CVE-2020-11089", "lastModified": "2022-07-19T11:52:15.420", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:L/I:L/A:L", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 2.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-05-29T20:15:11.017", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2020-07/msg00080.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/795842f4096501fcefc1a7f535ccc8132feb31d7"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/security/advisories/GHSA-hfc7-c5gv-8c2h"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-125"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, "type": "CWE-125"}
320
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * FreeRDP: A Remote Desktop Protocol Implementation\n * Serial Port Device Service Virtual Channel\n *\n * Copyright 2011 O.S. Systems Software Ltda.\n * Copyright 2011 Eduardo Fiss Beloni <beloni@ossystems.com.br>\n * Copyright 2014 Hewlett-Packard Development Company, L.P.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */", "#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif", "#include <assert.h>\n#include <errno.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>", "#include <winpr/collections.h>\n#include <winpr/comm.h>\n#include <winpr/crt.h>\n#include <winpr/stream.h>\n#include <winpr/synch.h>\n#include <winpr/thread.h>\n#include <winpr/wlog.h>", "#include <freerdp/freerdp.h>\n#include <freerdp/channels/rdpdr.h>\n#include <freerdp/channels/log.h>", "#define TAG CHANNELS_TAG(\"serial.client\")", "/* TODO: all #ifdef __linux__ could be removed once only some generic\n * functions will be used. Replace CommReadFile by ReadFile,\n * CommWriteFile by WriteFile etc.. */\n#if defined __linux__ && !defined ANDROID", "#define MAX_IRP_THREADS 5", "typedef struct _SERIAL_DEVICE SERIAL_DEVICE;", "struct _SERIAL_DEVICE\n{\n\tDEVICE device;\n\tBOOL permissive;\n\tSERIAL_DRIVER_ID ServerSerialDriverId;\n\tHANDLE* hComm;", "\twLog* log;\n\tHANDLE MainThread;\n\twMessageQueue* MainIrpQueue;", "\t/* one thread per pending IRP and indexed according their CompletionId */\n\twListDictionary* IrpThreads;\n\tUINT32 IrpThreadToBeTerminatedCount;\n\tCRITICAL_SECTION TerminatingIrpThreadsLock;\n\trdpContext* rdpcontext;\n};", "typedef struct _IRP_THREAD_DATA IRP_THREAD_DATA;", "struct _IRP_THREAD_DATA\n{\n\tSERIAL_DEVICE* serial;\n\tIRP* irp;\n};", "static UINT32 _GetLastErrorToIoStatus(SERIAL_DEVICE* serial)\n{\n\t/* http://msdn.microsoft.com/en-us/library/ff547466%28v=vs.85%29.aspx#generic_status_values_for_serial_device_control_requests\n\t */\n\tswitch (GetLastError())\n\t{\n\t\tcase ERROR_BAD_DEVICE:\n\t\t\treturn STATUS_INVALID_DEVICE_REQUEST;", "\t\tcase ERROR_CALL_NOT_IMPLEMENTED:\n\t\t\treturn STATUS_NOT_IMPLEMENTED;", "\t\tcase ERROR_CANCELLED:\n\t\t\treturn STATUS_CANCELLED;", "\t\tcase ERROR_INSUFFICIENT_BUFFER:\n\t\t\treturn STATUS_BUFFER_TOO_SMALL; /* NB: STATUS_BUFFER_SIZE_TOO_SMALL not defined */", "\t\tcase ERROR_INVALID_DEVICE_OBJECT_PARAMETER: /* eg: SerCx2.sys' _purge() */\n\t\t\treturn STATUS_INVALID_DEVICE_STATE;", "\t\tcase ERROR_INVALID_HANDLE:\n\t\t\treturn STATUS_INVALID_DEVICE_REQUEST;", "\t\tcase ERROR_INVALID_PARAMETER:\n\t\t\treturn STATUS_INVALID_PARAMETER;", "\t\tcase ERROR_IO_DEVICE:\n\t\t\treturn STATUS_IO_DEVICE_ERROR;", "\t\tcase ERROR_IO_PENDING:\n\t\t\treturn STATUS_PENDING;", "\t\tcase ERROR_NOT_SUPPORTED:\n\t\t\treturn STATUS_NOT_SUPPORTED;", "\t\tcase ERROR_TIMEOUT:\n\t\t\treturn STATUS_TIMEOUT;\n\t\t\t/* no default */\n\t}", "\tWLog_Print(serial->log, WLOG_DEBUG, \"unexpected last-error: 0x%08\" PRIX32 \"\", GetLastError());\n\treturn STATUS_UNSUCCESSFUL;\n}", "static UINT serial_process_irp_create(SERIAL_DEVICE* serial, IRP* irp)\n{\n\tDWORD DesiredAccess;\n\tDWORD SharedAccess;\n\tDWORD CreateDisposition;\n\tUINT32 PathLength;", "\tif (Stream_GetRemainingLength(irp->input) < 32)\n\t\treturn ERROR_INVALID_DATA;", "\tStream_Read_UINT32(irp->input, DesiredAccess); /* DesiredAccess (4 bytes) */\n\tStream_Seek_UINT64(irp->input); /* AllocationSize (8 bytes) */\n\tStream_Seek_UINT32(irp->input); /* FileAttributes (4 bytes) */\n\tStream_Read_UINT32(irp->input, SharedAccess); /* SharedAccess (4 bytes) */\n\tStream_Read_UINT32(irp->input, CreateDisposition); /* CreateDisposition (4 bytes) */\n\tStream_Seek_UINT32(irp->input); /* CreateOptions (4 bytes) */\n\tStream_Read_UINT32(irp->input, PathLength); /* PathLength (4 bytes) */\n", "\tif (!Stream_SafeSeek(irp->input, PathLength)) /* Path (variable) */", "\t\treturn ERROR_INVALID_DATA;\n", "", "\tassert(PathLength == 0); /* MS-RDPESP 2.2.2.2 */\n#ifndef _WIN32\n\t/* Windows 2012 server sends on a first call :\n\t * DesiredAccess = 0x00100080: SYNCHRONIZE | FILE_READ_ATTRIBUTES\n\t * SharedAccess = 0x00000007: FILE_SHARE_DELETE | FILE_SHARE_WRITE | FILE_SHARE_READ\n\t * CreateDisposition = 0x00000001: CREATE_NEW\n\t *\n\t * then Windows 2012 sends :\n\t * DesiredAccess = 0x00120089: SYNCHRONIZE | READ_CONTROL | FILE_READ_ATTRIBUTES |\n\t * FILE_READ_EA | FILE_READ_DATA SharedAccess = 0x00000007: FILE_SHARE_DELETE |\n\t * FILE_SHARE_WRITE | FILE_SHARE_READ CreateDisposition = 0x00000001: CREATE_NEW\n\t *\n\t * assert(DesiredAccess == (GENERIC_READ | GENERIC_WRITE));\n\t * assert(SharedAccess == 0);\n\t * assert(CreateDisposition == OPEN_EXISTING);\n\t *\n\t */\n\tWLog_Print(serial->log, WLOG_DEBUG,\n\t \"DesiredAccess: 0x%\" PRIX32 \", SharedAccess: 0x%\" PRIX32\n\t \", CreateDisposition: 0x%\" PRIX32 \"\",\n\t DesiredAccess, SharedAccess, CreateDisposition);\n\t/* FIXME: As of today only the flags below are supported by CommCreateFileA: */\n\tDesiredAccess = GENERIC_READ | GENERIC_WRITE;\n\tSharedAccess = 0;\n\tCreateDisposition = OPEN_EXISTING;\n#endif\n\tserial->hComm =\n\t CreateFile(serial->device.name, DesiredAccess, SharedAccess, NULL, /* SecurityAttributes */\n\t CreateDisposition, 0, /* FlagsAndAttributes */\n\t NULL); /* TemplateFile */", "\tif (!serial->hComm || (serial->hComm == INVALID_HANDLE_VALUE))\n\t{\n\t\tWLog_Print(serial->log, WLOG_WARN, \"CreateFile failure: %s last-error: 0x%08\" PRIX32 \"\",\n\t\t serial->device.name, GetLastError());\n\t\tirp->IoStatus = STATUS_UNSUCCESSFUL;\n\t\tgoto error_handle;\n\t}", "\t_comm_setServerSerialDriver(serial->hComm, serial->ServerSerialDriverId);\n\t_comm_set_permissive(serial->hComm, serial->permissive);\n\t/* NOTE: binary mode/raw mode required for the redirection. On\n\t * Linux, CommCreateFileA forces this setting.\n\t */\n\t/* ZeroMemory(&dcb, sizeof(DCB)); */\n\t/* dcb.DCBlength = sizeof(DCB); */\n\t/* GetCommState(serial->hComm, &dcb); */\n\t/* dcb.fBinary = TRUE; */\n\t/* SetCommState(serial->hComm, &dcb); */\n\tassert(irp->FileId == 0);\n\tirp->FileId = irp->devman->id_sequence++; /* FIXME: why not ((WINPR_COMM*)hComm)->fd? */\n\tirp->IoStatus = STATUS_SUCCESS;\n\tWLog_Print(serial->log, WLOG_DEBUG, \"%s (DeviceId: %\" PRIu32 \", FileId: %\" PRIu32 \") created.\",\n\t serial->device.name, irp->device->id, irp->FileId);\nerror_handle:\n\tStream_Write_UINT32(irp->output, irp->FileId); /* FileId (4 bytes) */\n\tStream_Write_UINT8(irp->output, 0); /* Information (1 byte) */\n\treturn CHANNEL_RC_OK;\n}", "static UINT serial_process_irp_close(SERIAL_DEVICE* serial, IRP* irp)\n{\n\tif (Stream_GetRemainingLength(irp->input) < 32)\n\t\treturn ERROR_INVALID_DATA;", "\tStream_Seek(irp->input, 32); /* Padding (32 bytes) */", "\tif (!CloseHandle(serial->hComm))\n\t{\n\t\tWLog_Print(serial->log, WLOG_WARN, \"CloseHandle failure: %s (%\" PRIu32 \") closed.\",\n\t\t serial->device.name, irp->device->id);\n\t\tirp->IoStatus = STATUS_UNSUCCESSFUL;\n\t\tgoto error_handle;\n\t}", "\tWLog_Print(serial->log, WLOG_DEBUG, \"%s (DeviceId: %\" PRIu32 \", FileId: %\" PRIu32 \") closed.\",\n\t serial->device.name, irp->device->id, irp->FileId);\n\tserial->hComm = NULL;\n\tirp->IoStatus = STATUS_SUCCESS;\nerror_handle:\n\tStream_Zero(irp->output, 5); /* Padding (5 bytes) */\n\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT serial_process_irp_read(SERIAL_DEVICE* serial, IRP* irp)\n{\n\tUINT32 Length;\n\tUINT64 Offset;\n\tBYTE* buffer = NULL;\n\tDWORD nbRead = 0;", "\tif (Stream_GetRemainingLength(irp->input) < 32)\n\t\treturn ERROR_INVALID_DATA;", "\tStream_Read_UINT32(irp->input, Length); /* Length (4 bytes) */\n\tStream_Read_UINT64(irp->input, Offset); /* Offset (8 bytes) */\n\tStream_Seek(irp->input, 20); /* Padding (20 bytes) */\n\tbuffer = (BYTE*)calloc(Length, sizeof(BYTE));", "\tif (buffer == NULL)\n\t{\n\t\tirp->IoStatus = STATUS_NO_MEMORY;\n\t\tgoto error_handle;\n\t}", "\t/* MS-RDPESP 3.2.5.1.4: If the Offset field is not set to 0, the value MUST be ignored\n\t * assert(Offset == 0);\n\t */\n\tWLog_Print(serial->log, WLOG_DEBUG, \"reading %\" PRIu32 \" bytes from %s\", Length,\n\t serial->device.name);", "\t/* FIXME: CommReadFile to be replaced by ReadFile */\n\tif (CommReadFile(serial->hComm, buffer, Length, &nbRead, NULL))\n\t{\n\t\tirp->IoStatus = STATUS_SUCCESS;\n\t}\n\telse\n\t{\n\t\tWLog_Print(serial->log, WLOG_DEBUG,\n\t\t \"read failure to %s, nbRead=%\" PRIu32 \", last-error: 0x%08\" PRIX32 \"\",\n\t\t serial->device.name, nbRead, GetLastError());\n\t\tirp->IoStatus = _GetLastErrorToIoStatus(serial);\n\t}", "\tWLog_Print(serial->log, WLOG_DEBUG, \"%\" PRIu32 \" bytes read from %s\", nbRead,\n\t serial->device.name);\nerror_handle:\n\tStream_Write_UINT32(irp->output, nbRead); /* Length (4 bytes) */", "\tif (nbRead > 0)\n\t{\n\t\tif (!Stream_EnsureRemainingCapacity(irp->output, nbRead))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"Stream_EnsureRemainingCapacity failed!\");\n\t\t\tfree(buffer);\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}", "\t\tStream_Write(irp->output, buffer, nbRead); /* ReadData */\n\t}", "\tfree(buffer);\n\treturn CHANNEL_RC_OK;\n}", "static UINT serial_process_irp_write(SERIAL_DEVICE* serial, IRP* irp)\n{\n\tUINT32 Length;\n\tUINT64 Offset;", "\tvoid* ptr;", "\tDWORD nbWritten = 0;", "\tif (Stream_GetRemainingLength(irp->input) < 32)\n\t\treturn ERROR_INVALID_DATA;", "\tStream_Read_UINT32(irp->input, Length); /* Length (4 bytes) */\n\tStream_Read_UINT64(irp->input, Offset); /* Offset (8 bytes) */", "\tif (!Stream_SafeSeek(irp->input, 20)) /* Padding (20 bytes) */\n\t\treturn ERROR_INVALID_DATA;\n", "\t/* MS-RDPESP 3.2.5.1.5: The Offset field is ignored\n\t * assert(Offset == 0);\n\t *\n\t * Using a serial printer, noticed though this field could be\n\t * set.\n\t */\n\tWLog_Print(serial->log, WLOG_DEBUG, \"writing %\" PRIu32 \" bytes to %s\", Length,\n\t serial->device.name);\n", "\tptr = Stream_Pointer(irp->input);\n\tif (!Stream_SafeSeek(irp->input, Length))\n\t\treturn ERROR_INVALID_DATA;", "\t/* FIXME: CommWriteFile to be replaced by WriteFile */", "\tif (CommWriteFile(serial->hComm, ptr, Length, &nbWritten, NULL))", "\t{\n\t\tirp->IoStatus = STATUS_SUCCESS;\n\t}\n\telse\n\t{\n\t\tWLog_Print(serial->log, WLOG_DEBUG,\n\t\t \"write failure to %s, nbWritten=%\" PRIu32 \", last-error: 0x%08\" PRIX32 \"\",\n\t\t serial->device.name, nbWritten, GetLastError());\n\t\tirp->IoStatus = _GetLastErrorToIoStatus(serial);\n\t}", "\tWLog_Print(serial->log, WLOG_DEBUG, \"%\" PRIu32 \" bytes written to %s\", nbWritten,\n\t serial->device.name);\n\tStream_Write_UINT32(irp->output, nbWritten); /* Length (4 bytes) */\n\tStream_Write_UINT8(irp->output, 0); /* Padding (1 byte) */\n\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT serial_process_irp_device_control(SERIAL_DEVICE* serial, IRP* irp)\n{\n\tUINT32 IoControlCode;\n\tUINT32 InputBufferLength;\n\tBYTE* InputBuffer = NULL;\n\tUINT32 OutputBufferLength;\n\tBYTE* OutputBuffer = NULL;\n\tDWORD BytesReturned = 0;", "\tif (Stream_GetRemainingLength(irp->input) < 32)\n\t\treturn ERROR_INVALID_DATA;", "\tStream_Read_UINT32(irp->input, OutputBufferLength); /* OutputBufferLength (4 bytes) */\n\tStream_Read_UINT32(irp->input, InputBufferLength); /* InputBufferLength (4 bytes) */\n\tStream_Read_UINT32(irp->input, IoControlCode); /* IoControlCode (4 bytes) */\n\tStream_Seek(irp->input, 20); /* Padding (20 bytes) */", "\tif (Stream_GetRemainingLength(irp->input) < InputBufferLength)\n\t\treturn ERROR_INVALID_DATA;", "\tOutputBuffer = (BYTE*)calloc(OutputBufferLength, sizeof(BYTE));", "\tif (OutputBuffer == NULL)\n\t{\n\t\tirp->IoStatus = STATUS_NO_MEMORY;\n\t\tgoto error_handle;\n\t}", "\tInputBuffer = (BYTE*)calloc(InputBufferLength, sizeof(BYTE));", "\tif (InputBuffer == NULL)\n\t{\n\t\tirp->IoStatus = STATUS_NO_MEMORY;\n\t\tgoto error_handle;\n\t}", "\tStream_Read(irp->input, InputBuffer, InputBufferLength);\n\tWLog_Print(serial->log, WLOG_DEBUG,\n\t \"CommDeviceIoControl: CompletionId=%\" PRIu32 \", IoControlCode=[0x%\" PRIX32 \"] %s\",\n\t irp->CompletionId, IoControlCode, _comm_serial_ioctl_name(IoControlCode));", "\t/* FIXME: CommDeviceIoControl to be replaced by DeviceIoControl() */\n\tif (CommDeviceIoControl(serial->hComm, IoControlCode, InputBuffer, InputBufferLength,\n\t OutputBuffer, OutputBufferLength, &BytesReturned, NULL))\n\t{\n\t\t/* WLog_Print(serial->log, WLOG_DEBUG, \"CommDeviceIoControl: CompletionId=%\"PRIu32\",\n\t\t * IoControlCode=[0x%\"PRIX32\"] %s done\", irp->CompletionId, IoControlCode,\n\t\t * _comm_serial_ioctl_name(IoControlCode)); */\n\t\tirp->IoStatus = STATUS_SUCCESS;\n\t}\n\telse\n\t{\n\t\tWLog_Print(serial->log, WLOG_DEBUG,\n\t\t \"CommDeviceIoControl failure: IoControlCode=[0x%\" PRIX32\n\t\t \"] %s, last-error: 0x%08\" PRIX32 \"\",\n\t\t IoControlCode, _comm_serial_ioctl_name(IoControlCode), GetLastError());\n\t\tirp->IoStatus = _GetLastErrorToIoStatus(serial);\n\t}", "error_handle:\n\t/* FIXME: find out whether it's required or not to get\n\t * BytesReturned == OutputBufferLength when\n\t * CommDeviceIoControl returns FALSE */\n\tassert(OutputBufferLength == BytesReturned);\n\tStream_Write_UINT32(irp->output, BytesReturned); /* OutputBufferLength (4 bytes) */", "\tif (BytesReturned > 0)\n\t{\n\t\tif (!Stream_EnsureRemainingCapacity(irp->output, BytesReturned))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"Stream_EnsureRemainingCapacity failed!\");\n\t\t\tfree(InputBuffer);\n\t\t\tfree(OutputBuffer);\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}", "\t\tStream_Write(irp->output, OutputBuffer, BytesReturned); /* OutputBuffer */\n\t}", "\t/* FIXME: Why at least Windows 2008R2 gets lost with this\n\t * extra byte and likely on a IOCTL_SERIAL_SET_BAUD_RATE? The\n\t * extra byte is well required according MS-RDPEFS\n\t * 2.2.1.5.5 */\n\t/* else */\n\t/* { */\n\t/* \tStream_Write_UINT8(irp->output, 0); /\\* Padding (1 byte) *\\/ */\n\t/* } */\n\tfree(InputBuffer);\n\tfree(OutputBuffer);\n\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT serial_process_irp(SERIAL_DEVICE* serial, IRP* irp)\n{\n\tUINT error = CHANNEL_RC_OK;\n\tWLog_Print(serial->log, WLOG_DEBUG,\n\t \"IRP MajorFunction: 0x%08\" PRIX32 \" MinorFunction: 0x%08\" PRIX32 \"\\n\",\n\t irp->MajorFunction, irp->MinorFunction);", "\tswitch (irp->MajorFunction)\n\t{\n\t\tcase IRP_MJ_CREATE:\n\t\t\terror = serial_process_irp_create(serial, irp);\n\t\t\tbreak;", "\t\tcase IRP_MJ_CLOSE:\n\t\t\terror = serial_process_irp_close(serial, irp);\n\t\t\tbreak;", "\t\tcase IRP_MJ_READ:\n\t\t\tif ((error = serial_process_irp_read(serial, irp)))\n\t\t\t\tWLog_ERR(TAG, \"serial_process_irp_read failed with error %\" PRIu32 \"!\", error);", "\t\t\tbreak;", "\t\tcase IRP_MJ_WRITE:\n\t\t\terror = serial_process_irp_write(serial, irp);\n\t\t\tbreak;", "\t\tcase IRP_MJ_DEVICE_CONTROL:\n\t\t\tif ((error = serial_process_irp_device_control(serial, irp)))\n\t\t\t\tWLog_ERR(TAG, \"serial_process_irp_device_control failed with error %\" PRIu32 \"!\",\n\t\t\t\t error);", "\t\t\tbreak;", "\t\tdefault:\n\t\t\tirp->IoStatus = STATUS_NOT_SUPPORTED;\n\t\t\tbreak;\n\t}", "\treturn error;\n}", "static DWORD WINAPI irp_thread_func(LPVOID arg)\n{\n\tIRP_THREAD_DATA* data = (IRP_THREAD_DATA*)arg;\n\tUINT error;", "\t/* blocks until the end of the request */\n\tif ((error = serial_process_irp(data->serial, data->irp)))\n\t{\n\t\tWLog_ERR(TAG, \"serial_process_irp failed with error %\" PRIu32 \"\", error);\n\t\tgoto error_out;\n\t}", "\tEnterCriticalSection(&data->serial->TerminatingIrpThreadsLock);\n\tdata->serial->IrpThreadToBeTerminatedCount++;\n\terror = data->irp->Complete(data->irp);\n\tLeaveCriticalSection(&data->serial->TerminatingIrpThreadsLock);\nerror_out:", "\tif (error && data->serial->rdpcontext)\n\t\tsetChannelError(data->serial->rdpcontext, error, \"irp_thread_func reported an error\");", "\t/* NB: At this point, the server might already being reusing\n\t * the CompletionId whereas the thread is not yet\n\t * terminated */\n\tfree(data);\n\tExitThread(error);\n\treturn error;\n}", "static void create_irp_thread(SERIAL_DEVICE* serial, IRP* irp)\n{\n\tIRP_THREAD_DATA* data = NULL;\n\tHANDLE irpThread;\n\tHANDLE previousIrpThread;\n\tuintptr_t key;\n\t/* for a test/debug purpose, uncomment the code below to get a\n\t * single thread for all IRPs. NB: two IRPs could not be\n\t * processed at the same time, typically two concurent\n\t * Read/Write operations could block each other. */\n\t/* serial_process_irp(serial, irp); */\n\t/* irp->Complete(irp); */\n\t/* return; */\n\t/* NOTE: for good or bad, this implementation relies on the\n\t * server to avoid a flooding of requests. see also _purge().\n\t */\n\tEnterCriticalSection(&serial->TerminatingIrpThreadsLock);", "\twhile (serial->IrpThreadToBeTerminatedCount > 0)\n\t{\n\t\t/* Cleaning up termitating and pending irp\n\t\t * threads. See also: irp_thread_func() */\n\t\tHANDLE irpThread;\n\t\tULONG_PTR* ids;\n\t\tint i, nbIds;\n\t\tnbIds = ListDictionary_GetKeys(serial->IrpThreads, &ids);", "\t\tfor (i = 0; i < nbIds; i++)\n\t\t{\n\t\t\t/* Checking if ids[i] is terminating or pending */\n\t\t\tDWORD waitResult;\n\t\t\tULONG_PTR id = ids[i];\n\t\t\tirpThread = ListDictionary_GetItemValue(serial->IrpThreads, (void*)id);\n\t\t\t/* FIXME: not quite sure a zero timeout is a good thing to check whether a thread is\n\t\t\t * stil alived or not */\n\t\t\twaitResult = WaitForSingleObject(irpThread, 0);", "\t\t\tif (waitResult == WAIT_OBJECT_0)\n\t\t\t{\n\t\t\t\t/* terminating thread */\n\t\t\t\t/* WLog_Print(serial->log, WLOG_DEBUG, \"IRP thread with CompletionId=%\"PRIuz\"\n\t\t\t\t * naturally died\", id); */\n\t\t\t\tCloseHandle(irpThread);\n\t\t\t\tListDictionary_Remove(serial->IrpThreads, (void*)id);\n\t\t\t\tserial->IrpThreadToBeTerminatedCount--;\n\t\t\t}\n\t\t\telse if (waitResult != WAIT_TIMEOUT)\n\t\t\t{\n\t\t\t\t/* unexpected thread state */\n\t\t\t\tWLog_Print(serial->log, WLOG_WARN,\n\t\t\t\t \"WaitForSingleObject, got an unexpected result=0x%\" PRIX32 \"\\n\",\n\t\t\t\t waitResult);\n\t\t\t\tassert(FALSE);\n\t\t\t}", "\t\t\t/* pending thread (but not yet terminating thread) if waitResult == WAIT_TIMEOUT */\n\t\t}", "\t\tif (serial->IrpThreadToBeTerminatedCount > 0)\n\t\t{\n\t\t\tWLog_Print(serial->log, WLOG_DEBUG, \"%\" PRIu32 \" IRP thread(s) not yet terminated\",\n\t\t\t serial->IrpThreadToBeTerminatedCount);\n\t\t\tSleep(1); /* 1 ms */\n\t\t}", "\t\tfree(ids);\n\t}", "\tLeaveCriticalSection(&serial->TerminatingIrpThreadsLock);\n\t/* NB: At this point and thanks to the synchronization we're\n\t * sure that the incoming IRP uses well a recycled\n\t * CompletionId or the server sent again an IRP already posted\n\t * which didn't get yet a response (this later server behavior\n\t * at least observed with IOCTL_SERIAL_WAIT_ON_MASK and\n\t * mstsc.exe).\n\t *\n\t * FIXME: behavior documented somewhere? behavior not yet\n\t * observed with FreeRDP).\n\t */\n\tkey = irp->CompletionId;\n\tpreviousIrpThread = ListDictionary_GetItemValue(serial->IrpThreads, (void*)key);", "\tif (previousIrpThread)\n\t{\n\t\t/* Thread still alived <=> Request still pending */\n\t\tWLog_Print(serial->log, WLOG_DEBUG,\n\t\t \"IRP recall: IRP with the CompletionId=%\" PRIu32 \" not yet completed!\",\n\t\t irp->CompletionId);\n\t\tassert(FALSE); /* unimplemented */\n\t\t/* TODO: asserts that previousIrpThread handles well\n\t\t * the same request by checking more details. Need an\n\t\t * access to the IRP object used by previousIrpThread\n\t\t */\n\t\t/* TODO: taking over the pending IRP or sending a kind\n\t\t * of wake up signal to accelerate the pending\n\t\t * request\n\t\t *\n\t\t * To be considered:\n\t\t * if (IoControlCode == IOCTL_SERIAL_WAIT_ON_MASK) {\n\t\t * pComm->PendingEvents |= SERIAL_EV_FREERDP_*;\n\t\t * }\n\t\t */\n\t\tirp->Discard(irp);\n\t\treturn;\n\t}", "\tif (ListDictionary_Count(serial->IrpThreads) >= MAX_IRP_THREADS)\n\t{\n\t\tWLog_Print(serial->log, WLOG_WARN,\n\t\t \"Number of IRP threads threshold reached: %d, keep on anyway\",\n\t\t ListDictionary_Count(serial->IrpThreads));\n\t\tassert(FALSE); /* unimplemented */\n\t\t /* TODO: MAX_IRP_THREADS has been thought to avoid a\n\t\t * flooding of pending requests. Use\n\t\t * WaitForMultipleObjects() when available in winpr\n\t\t * for threads.\n\t\t */\n\t}", "\t/* error_handle to be used ... */\n\tdata = (IRP_THREAD_DATA*)calloc(1, sizeof(IRP_THREAD_DATA));", "\tif (data == NULL)\n\t{\n\t\tWLog_Print(serial->log, WLOG_WARN, \"Could not allocate a new IRP_THREAD_DATA.\");\n\t\tgoto error_handle;\n\t}", "\tdata->serial = serial;\n\tdata->irp = irp;\n\t/* data freed by irp_thread_func */\n\tirpThread = CreateThread(NULL, 0, irp_thread_func, (void*)data, 0, NULL);", "\tif (irpThread == INVALID_HANDLE_VALUE)\n\t{\n\t\tWLog_Print(serial->log, WLOG_WARN, \"Could not allocate a new IRP thread.\");\n\t\tgoto error_handle;\n\t}", "\tkey = irp->CompletionId;", "\tif (!ListDictionary_Add(serial->IrpThreads, (void*)key, irpThread))\n\t{\n\t\tWLog_ERR(TAG, \"ListDictionary_Add failed!\");\n\t\tgoto error_handle;\n\t}", "\treturn;\nerror_handle:\n\tirp->IoStatus = STATUS_NO_MEMORY;\n\tirp->Complete(irp);\n\tfree(data);\n}", "static void terminate_pending_irp_threads(SERIAL_DEVICE* serial)\n{\n\tULONG_PTR* ids;\n\tint i, nbIds;\n\tnbIds = ListDictionary_GetKeys(serial->IrpThreads, &ids);\n\tWLog_Print(serial->log, WLOG_DEBUG, \"Terminating %d IRP thread(s)\", nbIds);", "\tfor (i = 0; i < nbIds; i++)\n\t{\n\t\tHANDLE irpThread;\n\t\tULONG_PTR id = ids[i];\n\t\tirpThread = ListDictionary_GetItemValue(serial->IrpThreads, (void*)id);\n\t\tTerminateThread(irpThread, 0);", "\t\tif (WaitForSingleObject(irpThread, INFINITE) == WAIT_FAILED)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"WaitForSingleObject failed!\");\n\t\t\tcontinue;\n\t\t}", "\t\tCloseHandle(irpThread);\n\t\tWLog_Print(serial->log, WLOG_DEBUG, \"IRP thread terminated, CompletionId %p\", (void*)id);\n\t}", "\tListDictionary_Clear(serial->IrpThreads);\n\tfree(ids);\n}", "static DWORD WINAPI serial_thread_func(LPVOID arg)\n{\n\tIRP* irp;\n\twMessage message;\n\tSERIAL_DEVICE* serial = (SERIAL_DEVICE*)arg;\n\tUINT error = CHANNEL_RC_OK;", "\twhile (1)\n\t{\n\t\tif (!MessageQueue_Wait(serial->MainIrpQueue))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"MessageQueue_Wait failed!\");\n\t\t\terror = ERROR_INTERNAL_ERROR;\n\t\t\tbreak;\n\t\t}", "\t\tif (!MessageQueue_Peek(serial->MainIrpQueue, &message, TRUE))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"MessageQueue_Peek failed!\");\n\t\t\terror = ERROR_INTERNAL_ERROR;\n\t\t\tbreak;\n\t\t}", "\t\tif (message.id == WMQ_QUIT)\n\t\t{\n\t\t\tterminate_pending_irp_threads(serial);\n\t\t\tbreak;\n\t\t}", "\t\tirp = (IRP*)message.wParam;", "\t\tif (irp)\n\t\t\tcreate_irp_thread(serial, irp);\n\t}", "\tif (error && serial->rdpcontext)\n\t\tsetChannelError(serial->rdpcontext, error, \"serial_thread_func reported an error\");", "\tExitThread(error);\n\treturn error;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT serial_irp_request(DEVICE* device, IRP* irp)\n{\n\tSERIAL_DEVICE* serial = (SERIAL_DEVICE*)device;\n\tassert(irp != NULL);", "\tif (irp == NULL)\n\t\treturn CHANNEL_RC_OK;", "\t/* NB: ENABLE_ASYNCIO is set, (MS-RDPEFS 2.2.2.7.2) this\n\t * allows the server to send multiple simultaneous read or\n\t * write requests.\n\t */", "\tif (!MessageQueue_Post(serial->MainIrpQueue, NULL, 0, (void*)irp, NULL))\n\t{\n\t\tWLog_ERR(TAG, \"MessageQueue_Post failed!\");\n\t\treturn ERROR_INTERNAL_ERROR;\n\t}", "\treturn CHANNEL_RC_OK;\n}", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nstatic UINT serial_free(DEVICE* device)\n{\n\tUINT error;\n\tSERIAL_DEVICE* serial = (SERIAL_DEVICE*)device;\n\tWLog_Print(serial->log, WLOG_DEBUG, \"freeing\");\n\tMessageQueue_PostQuit(serial->MainIrpQueue, 0);", "\tif (WaitForSingleObject(serial->MainThread, INFINITE) == WAIT_FAILED)\n\t{\n\t\terror = GetLastError();\n\t\tWLog_ERR(TAG, \"WaitForSingleObject failed with error %\" PRIu32 \"!\", error);\n\t\treturn error;\n\t}", "\tCloseHandle(serial->MainThread);", "\tif (serial->hComm)\n\t\tCloseHandle(serial->hComm);", "\t/* Clean up resources */\n\tStream_Free(serial->device.data, TRUE);\n\tMessageQueue_Free(serial->MainIrpQueue);\n\tListDictionary_Free(serial->IrpThreads);\n\tDeleteCriticalSection(&serial->TerminatingIrpThreadsLock);\n\tfree(serial);\n\treturn CHANNEL_RC_OK;\n}", "#endif /* __linux__ */", "#ifdef BUILTIN_CHANNELS\n#define DeviceServiceEntry serial_DeviceServiceEntry\n#else\n#define DeviceServiceEntry FREERDP_API DeviceServiceEntry\n#endif", "/**\n * Function description\n *\n * @return 0 on success, otherwise a Win32 error code\n */\nUINT DeviceServiceEntry(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints)\n{\n\tchar* name;\n\tchar* path;\n\tchar* driver;\n\tRDPDR_SERIAL* device;\n#if defined __linux__ && !defined ANDROID\n\tsize_t i, len;\n\tSERIAL_DEVICE* serial;\n#endif /* __linux__ */\n\tUINT error = CHANNEL_RC_OK;\n\tdevice = (RDPDR_SERIAL*)pEntryPoints->device;\n\tname = device->Name;\n\tpath = device->Path;\n\tdriver = device->Driver;", "\tif (!name || (name[0] == '*'))\n\t{\n\t\t/* TODO: implement auto detection of serial ports */\n\t\treturn CHANNEL_RC_OK;\n\t}", "\tif ((name && name[0]) && (path && path[0]))\n\t{\n\t\twLog* log;\n\t\tlog = WLog_Get(\"com.freerdp.channel.serial.client\");\n\t\tWLog_Print(log, WLOG_DEBUG, \"initializing\");\n#ifndef __linux__ /* to be removed */\n\t\tWLog_Print(log, WLOG_WARN, \"Serial ports redirection not supported on this platform.\");\n\t\treturn CHANNEL_RC_INITIALIZATION_ERROR;\n#else /* __linux __ */\n\t\tWLog_Print(log, WLOG_DEBUG, \"Defining %s as %s\", name, path);", "\t\tif (!DefineCommDevice(name /* eg: COM1 */, path /* eg: /dev/ttyS0 */))\n\t\t{\n\t\t\tDWORD status = GetLastError();\n\t\t\tWLog_ERR(TAG, \"DefineCommDevice failed with %08\" PRIx32, status);\n\t\t\treturn ERROR_INTERNAL_ERROR;\n\t\t}", "\t\tserial = (SERIAL_DEVICE*)calloc(1, sizeof(SERIAL_DEVICE));", "\t\tif (!serial)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\treturn CHANNEL_RC_NO_MEMORY;\n\t\t}", "\t\tserial->log = log;\n\t\tserial->device.type = RDPDR_DTYP_SERIAL;\n\t\tserial->device.name = name;\n\t\tserial->device.IRPRequest = serial_irp_request;\n\t\tserial->device.Free = serial_free;\n\t\tserial->rdpcontext = pEntryPoints->rdpcontext;\n\t\tlen = strlen(name);\n\t\tserial->device.data = Stream_New(NULL, len + 1);", "\t\tif (!serial->device.data)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"calloc failed!\");\n\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\tgoto error_out;\n\t\t}", "\t\tfor (i = 0; i <= len; i++)\n\t\t\tStream_Write_UINT8(serial->device.data, name[i] < 0 ? '_' : name[i]);", "\t\tif (driver != NULL)\n\t\t{\n\t\t\tif (_stricmp(driver, \"Serial\") == 0)\n\t\t\t\tserial->ServerSerialDriverId = SerialDriverSerialSys;\n\t\t\telse if (_stricmp(driver, \"SerCx\") == 0)\n\t\t\t\tserial->ServerSerialDriverId = SerialDriverSerCxSys;\n\t\t\telse if (_stricmp(driver, \"SerCx2\") == 0)\n\t\t\t\tserial->ServerSerialDriverId = SerialDriverSerCx2Sys;\n\t\t\telse\n\t\t\t{\n\t\t\t\tassert(FALSE);\n\t\t\t\tWLog_Print(serial->log, WLOG_DEBUG,\n\t\t\t\t \"Unknown server's serial driver: %s. SerCx2 will be used\", driver);\n\t\t\t\tserial->ServerSerialDriverId = SerialDriverSerialSys;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t/* default driver */\n\t\t\tserial->ServerSerialDriverId = SerialDriverSerialSys;\n\t\t}", "\t\tif (device->Permissive != NULL)\n\t\t{\n\t\t\tif (_stricmp(device->Permissive, \"permissive\") == 0)\n\t\t\t{\n\t\t\t\tserial->permissive = TRUE;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tWLog_Print(serial->log, WLOG_DEBUG, \"Unknown flag: %s\", device->Permissive);\n\t\t\t\tassert(FALSE);\n\t\t\t}\n\t\t}", "\t\tWLog_Print(serial->log, WLOG_DEBUG, \"Server's serial driver: %s (id: %d)\", driver,\n\t\t serial->ServerSerialDriverId);\n\t\t/* TODO: implement auto detection of the server's serial driver */\n\t\tserial->MainIrpQueue = MessageQueue_New(NULL);", "\t\tif (!serial->MainIrpQueue)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"MessageQueue_New failed!\");\n\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\tgoto error_out;\n\t\t}", "\t\t/* IrpThreads content only modified by create_irp_thread() */\n\t\tserial->IrpThreads = ListDictionary_New(FALSE);", "\t\tif (!serial->IrpThreads)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"ListDictionary_New failed!\");\n\t\t\terror = CHANNEL_RC_NO_MEMORY;\n\t\t\tgoto error_out;\n\t\t}", "\t\tserial->IrpThreadToBeTerminatedCount = 0;\n\t\tInitializeCriticalSection(&serial->TerminatingIrpThreadsLock);", "\t\tif ((error = pEntryPoints->RegisterDevice(pEntryPoints->devman, (DEVICE*)serial)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"EntryPoints->RegisterDevice failed with error %\" PRIu32 \"!\", error);\n\t\t\tgoto error_out;\n\t\t}", "\t\tif (!(serial->MainThread =\n\t\t CreateThread(NULL, 0, serial_thread_func, (void*)serial, 0, NULL)))\n\t\t{\n\t\t\tWLog_ERR(TAG, \"CreateThread failed!\");\n\t\t\terror = ERROR_INTERNAL_ERROR;\n\t\t\tgoto error_out;\n\t\t}", "#endif /* __linux __ */\n\t}", "\treturn error;\nerror_out:\n#ifdef __linux__ /* to be removed */\n\tListDictionary_Free(serial->IrpThreads);\n\tMessageQueue_Free(serial->MainIrpQueue);\n\tStream_Free(serial->device.data, TRUE);\n\tfree(serial);\n#endif /* __linux __ */\n\treturn error;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [357, 496, 447, 322, 308, 1001], "buggy_code_start_loc": [333, 480, 447, 145, 307, 94], "filenames": ["channels/drive/client/drive_main.c", "channels/printer/client/printer_main.c", "channels/rdpei/client/rdpei_main.c", "channels/serial/client/serial_main.c", "libfreerdp/core/gateway/rdg.c", "libfreerdp/core/nego.c"], "fixing_code_end_loc": [361, 502, 451, 327, 309, 1013], "fixing_code_start_loc": [334, 481, 448, 145, 307, 94], "message": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:freerdp:freerdp:*:*:*:*:*:*:*:*", "matchCriteriaId": "5C5F8D57-1D22-42B4-9E08-9131F7BE8FA5", "versionEndExcluding": "2.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "B620311B-34A3-48A6-82DF-6F078D7A4493", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0."}, {"lang": "es", "value": "En FreeRDP versiones anteriores a 2.1.0, se presenta una lectura fuera de l\u00edmite en las funciones de irp (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). Esto ha sido corregido en la versi\u00f3n 2.1.0."}], "evaluatorComment": null, "id": "CVE-2020-11089", "lastModified": "2022-07-19T11:52:15.420", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:L/I:L/A:L", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 2.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-05-29T20:15:11.017", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2020-07/msg00080.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/795842f4096501fcefc1a7f535ccc8132feb31d7"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/security/advisories/GHSA-hfc7-c5gv-8c2h"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-125"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, "type": "CWE-125"}
320
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * FreeRDP: A Remote Desktop Protocol Implementation\n * Remote Desktop Gateway (RDG)\n *\n * Copyright 2015 Denis Vincent <dvincent@devolutions.net>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */", "#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif", "#include <assert.h>", "#include <winpr/crt.h>\n#include <winpr/synch.h>\n#include <winpr/print.h>\n#include <winpr/stream.h>\n#include <winpr/winsock.h>", "#include <freerdp/log.h>\n#include <freerdp/error.h>\n#include <freerdp/utils/ringbuffer.h>", "#include \"rdg.h\"\n#include \"../proxy.h\"\n#include \"../rdp.h\"\n#include \"../../crypto/opensslcompat.h\"\n#include \"rpc_fault.h\"", "#define TAG FREERDP_TAG(\"core.gateway.rdg\")", "/* HTTP channel response fields present flags. */\n#define HTTP_CHANNEL_RESPONSE_FIELD_CHANNELID 0x1\n#define HTTP_CHANNEL_RESPONSE_OPTIONAL 0x2\n#define HTTP_CHANNEL_RESPONSE_FIELD_UDPPORT 0x4", "/* HTTP extended auth. */\n#define HTTP_EXTENDED_AUTH_NONE 0x0\n#define HTTP_EXTENDED_AUTH_SC 0x1 /* Smart card authentication. */\n#define HTTP_EXTENDED_AUTH_PAA 0x02 /* Pluggable authentication. */\n#define HTTP_EXTENDED_AUTH_SSPI_NTLM 0x04 /* NTLM extended authentication. */", "/* HTTP packet types. */\n#define PKT_TYPE_HANDSHAKE_REQUEST 0x1\n#define PKT_TYPE_HANDSHAKE_RESPONSE 0x2\n#define PKT_TYPE_EXTENDED_AUTH_MSG 0x3\n#define PKT_TYPE_TUNNEL_CREATE 0x4\n#define PKT_TYPE_TUNNEL_RESPONSE 0x5\n#define PKT_TYPE_TUNNEL_AUTH 0x6\n#define PKT_TYPE_TUNNEL_AUTH_RESPONSE 0x7\n#define PKT_TYPE_CHANNEL_CREATE 0x8\n#define PKT_TYPE_CHANNEL_RESPONSE 0x9\n#define PKT_TYPE_DATA 0xA\n#define PKT_TYPE_SERVICE_MESSAGE 0xB\n#define PKT_TYPE_REAUTH_MESSAGE 0xC\n#define PKT_TYPE_KEEPALIVE 0xD\n#define PKT_TYPE_CLOSE_CHANNEL 0x10\n#define PKT_TYPE_CLOSE_CHANNEL_RESPONSE 0x11", "/* HTTP tunnel auth fields present flags. */\n#define HTTP_TUNNEL_AUTH_FIELD_SOH 0x1", "/* HTTP tunnel auth response fields present flags. */\n#define HTTP_TUNNEL_AUTH_RESPONSE_FIELD_REDIR_FLAGS 0x1\n#define HTTP_TUNNEL_AUTH_RESPONSE_FIELD_IDLE_TIMEOUT 0x2\n#define HTTP_TUNNEL_AUTH_RESPONSE_FIELD_SOH_RESPONSE 0x4", "/* HTTP tunnel packet fields present flags. */\n#define HTTP_TUNNEL_PACKET_FIELD_PAA_COOKIE 0x1\n#define HTTP_TUNNEL_PACKET_FIELD_REAUTH 0x2", "/* HTTP tunnel redir flags. */\n#define HTTP_TUNNEL_REDIR_ENABLE_ALL 0x80000000\n#define HTTP_TUNNEL_REDIR_DISABLE_ALL 0x40000000\n#define HTTP_TUNNEL_REDIR_DISABLE_DRIVE 0x1\n#define HTTP_TUNNEL_REDIR_DISABLE_PRINTER 0x2\n#define HTTP_TUNNEL_REDIR_DISABLE_PORT 0x4\n#define HTTP_TUNNEL_REDIR_DISABLE_CLIPBOARD 0x8\n#define HTTP_TUNNEL_REDIR_DISABLE_PNP 0x10", "/* HTTP tunnel response fields present flags. */\n#define HTTP_TUNNEL_RESPONSE_FIELD_TUNNEL_ID 0x1\n#define HTTP_TUNNEL_RESPONSE_FIELD_CAPS 0x2\n#define HTTP_TUNNEL_RESPONSE_FIELD_SOH_REQ 0x4\n#define HTTP_TUNNEL_RESPONSE_FIELD_CONSENT_MSG 0x10", "/* HTTP capability type enumeration. */\n#define HTTP_CAPABILITY_TYPE_QUAR_SOH 0x1\n#define HTTP_CAPABILITY_IDLE_TIMEOUT 0x2\n#define HTTP_CAPABILITY_MESSAGING_CONSENT_SIGN 0x4\n#define HTTP_CAPABILITY_MESSAGING_SERVICE_MSG 0x8\n#define HTTP_CAPABILITY_REAUTH 0x10\n#define HTTP_CAPABILITY_UDP_TRANSPORT 0x20", "struct rdp_rdg\n{\n\trdpContext* context;\n\trdpSettings* settings;\n\tBOOL attached;\n\tBIO* frontBio;\n\trdpTls* tlsIn;\n\trdpTls* tlsOut;\n\trdpNtlm* ntlm;\n\tHttpContext* http;\n\tCRITICAL_SECTION writeSection;", "\tUUID guid;", "\tint state;\n\tUINT16 packetRemainingCount;\n\tUINT16 reserved1;\n\tint timeout;\n\tUINT16 extAuth;\n\tUINT16 reserved2;\n};", "enum\n{\n\tRDG_CLIENT_STATE_INITIAL,\n\tRDG_CLIENT_STATE_HANDSHAKE,\n\tRDG_CLIENT_STATE_TUNNEL_CREATE,\n\tRDG_CLIENT_STATE_TUNNEL_AUTHORIZE,\n\tRDG_CLIENT_STATE_CHANNEL_CREATE,\n\tRDG_CLIENT_STATE_OPENED,\n};", "#pragma pack(push, 1)", "typedef struct rdg_packet_header\n{\n\tUINT16 type;\n\tUINT16 reserved;\n\tUINT32 packetLength;\n} RdgPacketHeader;", "#pragma pack(pop)", "typedef struct\n{\n\tUINT32 code;\n\tconst char* name;\n} t_err_mapping;", "static const t_err_mapping tunnel_response_fields_present[] = {\n\t{ HTTP_TUNNEL_RESPONSE_FIELD_TUNNEL_ID, \"HTTP_TUNNEL_RESPONSE_FIELD_TUNNEL_ID\" },\n\t{ HTTP_TUNNEL_RESPONSE_FIELD_CAPS, \"HTTP_TUNNEL_RESPONSE_FIELD_CAPS\" },\n\t{ HTTP_TUNNEL_RESPONSE_FIELD_SOH_REQ, \"HTTP_TUNNEL_RESPONSE_FIELD_SOH_REQ\" },\n\t{ HTTP_TUNNEL_RESPONSE_FIELD_CONSENT_MSG, \"HTTP_TUNNEL_RESPONSE_FIELD_CONSENT_MSG\" }\n};", "static const t_err_mapping channel_response_fields_present[] = {\n\t{ HTTP_CHANNEL_RESPONSE_FIELD_CHANNELID, \"HTTP_CHANNEL_RESPONSE_FIELD_CHANNELID\" },\n\t{ HTTP_CHANNEL_RESPONSE_OPTIONAL, \"HTTP_CHANNEL_RESPONSE_OPTIONAL\" },\n\t{ HTTP_CHANNEL_RESPONSE_FIELD_UDPPORT, \"HTTP_CHANNEL_RESPONSE_FIELD_UDPPORT\" }\n};", "static const t_err_mapping tunnel_authorization_response_fields_present[] = {\n\t{ HTTP_TUNNEL_AUTH_RESPONSE_FIELD_REDIR_FLAGS, \"HTTP_TUNNEL_AUTH_RESPONSE_FIELD_REDIR_FLAGS\" },\n\t{ HTTP_TUNNEL_AUTH_RESPONSE_FIELD_IDLE_TIMEOUT,\n\t \"HTTP_TUNNEL_AUTH_RESPONSE_FIELD_IDLE_TIMEOUT\" },\n\t{ HTTP_TUNNEL_AUTH_RESPONSE_FIELD_SOH_RESPONSE,\n\t \"HTTP_TUNNEL_AUTH_RESPONSE_FIELD_SOH_RESPONSE\" }\n};", "static const t_err_mapping extended_auth[] = {\n\t{ HTTP_EXTENDED_AUTH_NONE, \"HTTP_EXTENDED_AUTH_NONE\" },\n\t{ HTTP_EXTENDED_AUTH_SC, \"HTTP_EXTENDED_AUTH_SC\" },\n\t{ HTTP_EXTENDED_AUTH_PAA, \"HTTP_EXTENDED_AUTH_PAA\" },\n\t{ HTTP_EXTENDED_AUTH_SSPI_NTLM, \"HTTP_EXTENDED_AUTH_SSPI_NTLM\" }\n};", "static const char* fields_present_to_string(UINT16 fieldsPresent, const t_err_mapping* map,\n size_t elements)\n{\n\tsize_t x = 0;\n\tstatic char buffer[1024] = { 0 };\n\tchar fields[12];\n\tmemset(buffer, 0, sizeof(buffer));", "\tfor (x = 0; x < elements; x++)\n\t{\n\t\tif (buffer[0] != '\\0')\n\t\t\tstrcat(buffer, \"|\");", "\t\tif ((map[x].code & fieldsPresent) != 0)\n\t\t\tstrcat(buffer, map[x].name);\n\t}", "\tsprintf_s(fields, ARRAYSIZE(fields), \" [%04\" PRIx16 \"]\", fieldsPresent);\n\tstrcat(buffer, fields);\n\treturn buffer;\n}", "static const char* channel_response_fields_present_to_string(UINT16 fieldsPresent)\n{\n\treturn fields_present_to_string(fieldsPresent, channel_response_fields_present,\n\t ARRAYSIZE(channel_response_fields_present));\n}", "static const char* tunnel_response_fields_present_to_string(UINT16 fieldsPresent)\n{\n\treturn fields_present_to_string(fieldsPresent, tunnel_response_fields_present,\n\t ARRAYSIZE(tunnel_response_fields_present));\n}", "static const char* tunnel_authorization_response_fields_present_to_string(UINT16 fieldsPresent)\n{\n\treturn fields_present_to_string(fieldsPresent, tunnel_authorization_response_fields_present,\n\t ARRAYSIZE(tunnel_authorization_response_fields_present));\n}", "static const char* extended_auth_to_string(UINT16 auth)\n{\n\tif (auth == HTTP_EXTENDED_AUTH_NONE)\n\t\treturn \"HTTP_EXTENDED_AUTH_NONE [0x0000]\";", "\treturn fields_present_to_string(auth, extended_auth, ARRAYSIZE(extended_auth));\n}", "static BOOL rdg_write_packet(rdpRdg* rdg, wStream* sPacket)\n{\n\tsize_t s;\n\tint status;\n\twStream* sChunk;\n\tchar chunkSize[11];\n\tsprintf_s(chunkSize, sizeof(chunkSize), \"%\" PRIXz \"\\r\\n\", Stream_Length(sPacket));\n\tsChunk = Stream_New(NULL, strnlen(chunkSize, sizeof(chunkSize)) + Stream_Length(sPacket) + 2);", "\tif (!sChunk)\n\t\treturn FALSE;", "\tStream_Write(sChunk, chunkSize, strnlen(chunkSize, sizeof(chunkSize)));\n\tStream_Write(sChunk, Stream_Buffer(sPacket), Stream_Length(sPacket));\n\tStream_Write(sChunk, \"\\r\\n\", 2);\n\tStream_SealLength(sChunk);\n\ts = Stream_Length(sChunk);", "\tif (s > INT_MAX)\n\t\treturn FALSE;", "\tstatus = tls_write_all(rdg->tlsIn, Stream_Buffer(sChunk), (int)s);\n\tStream_Free(sChunk, TRUE);", "\tif (status < 0)\n\t\treturn FALSE;", "\treturn TRUE;\n}", "static BOOL rdg_read_all(rdpTls* tls, BYTE* buffer, int size)\n{\n\tint status;\n\tint readCount = 0;\n\tBYTE* pBuffer = buffer;", "\twhile (readCount < size)\n\t{\n\t\tstatus = BIO_read(tls->bio, pBuffer, size - readCount);", "\t\tif (status <= 0)\n\t\t{\n\t\t\tif (!BIO_should_retry(tls->bio))\n\t\t\t\treturn FALSE;", "\t\t\tcontinue;\n\t\t}", "\t\treadCount += status;\n\t\tpBuffer += status;\n\t}", "\treturn TRUE;\n}", "static wStream* rdg_receive_packet(rdpRdg* rdg)\n{\n\twStream* s;\n\tconst size_t header = sizeof(RdgPacketHeader);\n\tsize_t packetLength;\n\tassert(header <= INT_MAX);\n\ts = Stream_New(NULL, 1024);", "\tif (!s)\n\t\treturn NULL;", "\tif (!rdg_read_all(rdg->tlsOut, Stream_Buffer(s), header))\n\t{\n\t\tStream_Free(s, TRUE);\n\t\treturn NULL;\n\t}", "\tStream_Seek(s, 4);\n\tStream_Read_UINT32(s, packetLength);\n", "\tif ((packetLength > INT_MAX) || !Stream_EnsureCapacity(s, packetLength))", "\t{\n\t\tStream_Free(s, TRUE);\n\t\treturn NULL;\n\t}", "\tif (!rdg_read_all(rdg->tlsOut, Stream_Buffer(s) + header, (int)packetLength - (int)header))\n\t{\n\t\tStream_Free(s, TRUE);\n\t\treturn NULL;\n\t}", "\tStream_SetLength(s, packetLength);\n\treturn s;\n}", "static BOOL rdg_send_handshake(rdpRdg* rdg)\n{\n\twStream* s;\n\tBOOL status;\n\ts = Stream_New(NULL, 14);", "\tif (!s)\n\t\treturn FALSE;", "\tStream_Write_UINT16(s, PKT_TYPE_HANDSHAKE_REQUEST); /* Type (2 bytes) */\n\tStream_Write_UINT16(s, 0); /* Reserved (2 bytes) */\n\tStream_Write_UINT32(s, 14); /* PacketLength (4 bytes) */\n\tStream_Write_UINT8(s, 1); /* VersionMajor (1 byte) */\n\tStream_Write_UINT8(s, 0); /* VersionMinor (1 byte) */\n\tStream_Write_UINT16(s, 0); /* ClientVersion (2 bytes), must be 0 */\n\tStream_Write_UINT16(s, rdg->extAuth); /* ExtendedAuthentication (2 bytes) */\n\tStream_SealLength(s);\n\tstatus = rdg_write_packet(rdg, s);\n\tStream_Free(s, TRUE);", "\tif (status)\n\t{\n\t\trdg->state = RDG_CLIENT_STATE_HANDSHAKE;\n\t}", "\treturn status;\n}", "static BOOL rdg_send_tunnel_request(rdpRdg* rdg)\n{\n\twStream* s;\n\tBOOL status;\n\tUINT32 packetSize = 16;\n\tUINT16 fieldsPresent = 0;\n\tWCHAR* PAACookie = NULL;\n\tint PAACookieLen = 0;", "\tif (rdg->extAuth == HTTP_EXTENDED_AUTH_PAA)\n\t{\n\t\tPAACookieLen =\n\t\t ConvertToUnicode(CP_UTF8, 0, rdg->settings->GatewayAccessToken, -1, &PAACookie, 0);", "\t\tif (!PAACookie || (PAACookieLen < 0) || (PAACookieLen > UINT16_MAX / 2))\n\t\t{\n\t\t\tfree(PAACookie);\n\t\t\treturn FALSE;\n\t\t}", "\t\tpacketSize += 2 + (UINT32)PAACookieLen * sizeof(WCHAR);\n\t\tfieldsPresent = HTTP_TUNNEL_PACKET_FIELD_PAA_COOKIE;\n\t}", "\ts = Stream_New(NULL, packetSize);", "\tif (!s)\n\t{\n\t\tfree(PAACookie);\n\t\treturn FALSE;\n\t}", "\tStream_Write_UINT16(s, PKT_TYPE_TUNNEL_CREATE); /* Type (2 bytes) */\n\tStream_Write_UINT16(s, 0); /* Reserved (2 bytes) */\n\tStream_Write_UINT32(s, packetSize); /* PacketLength (4 bytes) */\n\tStream_Write_UINT32(s, HTTP_CAPABILITY_TYPE_QUAR_SOH); /* CapabilityFlags (4 bytes) */\n\tStream_Write_UINT16(s, fieldsPresent); /* FieldsPresent (2 bytes) */\n\tStream_Write_UINT16(s, 0); /* Reserved (2 bytes), must be 0 */", "\tif (PAACookie)\n\t{\n\t\tStream_Write_UINT16(s, (UINT16)PAACookieLen * 2); /* PAA cookie string length */\n\t\tStream_Write_UTF16_String(s, PAACookie, (size_t)PAACookieLen);\n\t}", "\tStream_SealLength(s);\n\tstatus = rdg_write_packet(rdg, s);\n\tStream_Free(s, TRUE);\n\tfree(PAACookie);", "\tif (status)\n\t{\n\t\trdg->state = RDG_CLIENT_STATE_TUNNEL_CREATE;\n\t}", "\treturn status;\n}", "static BOOL rdg_send_tunnel_authorization(rdpRdg* rdg)\n{\n\twStream* s;\n\tBOOL status;\n\tWCHAR* clientName = NULL;\n\tUINT32 packetSize;\n\tint clientNameLen =\n\t ConvertToUnicode(CP_UTF8, 0, rdg->settings->ClientHostname, -1, &clientName, 0);", "\tif (!clientName || (clientNameLen < 0) || (clientNameLen > UINT16_MAX / 2))\n\t{\n\t\tfree(clientName);\n\t\treturn FALSE;\n\t}", "\tpacketSize = 12 + (UINT32)clientNameLen * sizeof(WCHAR);\n\ts = Stream_New(NULL, packetSize);", "\tif (!s)\n\t{\n\t\tfree(clientName);\n\t\treturn FALSE;\n\t}", "\tStream_Write_UINT16(s, PKT_TYPE_TUNNEL_AUTH); /* Type (2 bytes) */\n\tStream_Write_UINT16(s, 0); /* Reserved (2 bytes) */\n\tStream_Write_UINT32(s, packetSize); /* PacketLength (4 bytes) */\n\tStream_Write_UINT16(s, 0); /* FieldsPresent (2 bytes) */\n\tStream_Write_UINT16(s, (UINT16)clientNameLen * 2); /* Client name string length */\n\tStream_Write_UTF16_String(s, clientName, (size_t)clientNameLen);\n\tStream_SealLength(s);\n\tstatus = rdg_write_packet(rdg, s);\n\tStream_Free(s, TRUE);\n\tfree(clientName);", "\tif (status)\n\t{\n\t\trdg->state = RDG_CLIENT_STATE_TUNNEL_AUTHORIZE;\n\t}", "\treturn status;\n}", "static BOOL rdg_send_channel_create(rdpRdg* rdg)\n{\n\twStream* s = NULL;\n\tBOOL status = FALSE;\n\tWCHAR* serverName = NULL;\n\tint serverNameLen =\n\t ConvertToUnicode(CP_UTF8, 0, rdg->settings->ServerHostname, -1, &serverName, 0);\n\tUINT32 packetSize = 16 + ((UINT32)serverNameLen) * 2;", "\tif ((serverNameLen < 0) || (serverNameLen > UINT16_MAX / 2))\n\t\tgoto fail;", "\ts = Stream_New(NULL, packetSize);", "\tif (!s)\n\t\tgoto fail;", "\tStream_Write_UINT16(s, PKT_TYPE_CHANNEL_CREATE); /* Type (2 bytes) */\n\tStream_Write_UINT16(s, 0); /* Reserved (2 bytes) */\n\tStream_Write_UINT32(s, packetSize); /* PacketLength (4 bytes) */\n\tStream_Write_UINT8(s, 1); /* Number of resources. (1 byte) */\n\tStream_Write_UINT8(s, 0); /* Number of alternative resources (1 byte) */\n\tStream_Write_UINT16(s, (UINT16)rdg->settings->ServerPort); /* Resource port (2 bytes) */\n\tStream_Write_UINT16(s, 3); /* Protocol number (2 bytes) */\n\tStream_Write_UINT16(s, (UINT16)serverNameLen * 2);\n\tStream_Write_UTF16_String(s, serverName, (size_t)serverNameLen);\n\tStream_SealLength(s);\n\tstatus = rdg_write_packet(rdg, s);\nfail:\n\tfree(serverName);\n\tStream_Free(s, TRUE);", "\tif (status)\n\t\trdg->state = RDG_CLIENT_STATE_CHANNEL_CREATE;", "\treturn status;\n}", "static BOOL rdg_set_ntlm_auth_header(rdpNtlm* ntlm, HttpRequest* request)\n{\n\tconst SecBuffer* ntlmToken = ntlm_client_get_output_buffer(ntlm);\n\tchar* base64NtlmToken = NULL;", "\tif (ntlmToken)\n\t{\n\t\tif (ntlmToken->cbBuffer > INT_MAX)\n\t\t\treturn FALSE;", "\t\tbase64NtlmToken = crypto_base64_encode(ntlmToken->pvBuffer, (int)ntlmToken->cbBuffer);\n\t}", "\tif (base64NtlmToken)\n\t{\n\t\tBOOL rc = http_request_set_auth_scheme(request, \"NTLM\") &&\n\t\t http_request_set_auth_param(request, base64NtlmToken);\n\t\tfree(base64NtlmToken);", "\t\tif (!rc)\n\t\t\treturn FALSE;\n\t}", "\treturn TRUE;\n}", "static wStream* rdg_build_http_request(rdpRdg* rdg, const char* method,\n const char* transferEncoding)\n{\n\twStream* s = NULL;\n\tHttpRequest* request = NULL;\n\tconst char* uri;", "\tif (!rdg || !method)\n\t\treturn NULL;", "\turi = http_context_get_uri(rdg->http);\n\trequest = http_request_new();", "\tif (!request)\n\t\treturn NULL;", "\tif (!http_request_set_method(request, method) || !http_request_set_uri(request, uri))\n\t\tgoto out;", "\tif (rdg->ntlm)\n\t{\n\t\tif (!rdg_set_ntlm_auth_header(rdg->ntlm, request))\n\t\t\tgoto out;\n\t}", "\tif (transferEncoding)\n\t{\n\t\thttp_request_set_transfer_encoding(request, transferEncoding);\n\t}", "\ts = http_request_write(rdg->http, request);\nout:\n\thttp_request_free(request);", "\tif (s)\n\t\tStream_SealLength(s);", "\treturn s;\n}", "static BOOL rdg_handle_ntlm_challenge(rdpNtlm* ntlm, HttpResponse* response)\n{\n\tBOOL continueNeeded = FALSE;\n\tsize_t len;\n\tconst char* token64 = NULL;\n\tint ntlmTokenLength = 0;\n\tBYTE* ntlmTokenData = NULL;\n\tlong StatusCode;", "\tif (!ntlm || !response)\n\t\treturn FALSE;", "\tStatusCode = http_response_get_status_code(response);", "\tif (StatusCode != HTTP_STATUS_DENIED)\n\t{\n\t\tWLog_DBG(TAG, \"Unexpected NTLM challenge HTTP status: %ld\", StatusCode);\n\t\treturn FALSE;\n\t}", "\ttoken64 = http_response_get_auth_token(response, \"NTLM\");", "\tif (!token64)\n\t\treturn FALSE;", "\tlen = strlen(token64);", "\tif (len > INT_MAX)\n\t\treturn FALSE;", "\tcrypto_base64_decode(token64, (int)len, &ntlmTokenData, &ntlmTokenLength);", "\tif (ntlmTokenLength < 0)\n\t{\n\t\tfree(ntlmTokenData);\n\t\treturn FALSE;\n\t}", "\tif (ntlmTokenData && ntlmTokenLength)\n\t{\n\t\tif (!ntlm_client_set_input_buffer(ntlm, FALSE, ntlmTokenData, (size_t)ntlmTokenLength))\n\t\t\treturn FALSE;\n\t}", "\tif (!ntlm_authenticate(ntlm, &continueNeeded))\n\t\treturn FALSE;", "\tif (continueNeeded)\n\t\treturn FALSE;", "\treturn TRUE;\n}", "static BOOL rdg_skip_seed_payload(rdpTls* tls, SSIZE_T lastResponseLength)\n{\n\tBYTE seed_payload[10];\n\tconst size_t size = sizeof(seed_payload);", "\tassert(size < SSIZE_MAX);", "\t/* Per [MS-TSGU] 3.3.5.1 step 4, after final OK response RDG server sends\n\t * random \"seed\" payload of limited size. In practice it's 10 bytes.\n\t */\n\tif (lastResponseLength < (SSIZE_T)size)\n\t{\n\t\tif (!rdg_read_all(tls, seed_payload, size - lastResponseLength))\n\t\t{\n\t\t\treturn FALSE;\n\t\t}\n\t}", "\treturn TRUE;\n}", "static BOOL rdg_process_handshake_response(rdpRdg* rdg, wStream* s)\n{\n\tUINT32 errorCode;\n\tUINT16 serverVersion, extendedAuth;\n\tBYTE verMajor, verMinor;\n\tconst char* error;\n\tWLog_DBG(TAG, \"Handshake response received\");", "\tif (rdg->state != RDG_CLIENT_STATE_HANDSHAKE)\n\t{\n\t\treturn FALSE;\n\t}", "\tif (Stream_GetRemainingLength(s) < 10)\n\t{\n\t\tWLog_ERR(TAG, \"[%s] Short packet %\" PRIuz \", expected 10\", __FUNCTION__,\n\t\t Stream_GetRemainingLength(s));\n\t\treturn FALSE;\n\t}", "\tStream_Read_UINT32(s, errorCode);\n\tStream_Read_UINT8(s, verMajor);\n\tStream_Read_UINT8(s, verMinor);\n\tStream_Read_UINT16(s, serverVersion);\n\tStream_Read_UINT16(s, extendedAuth);\n\terror = rpc_error_to_string(errorCode);\n\tWLog_DBG(TAG,\n\t \"errorCode=%s, verMajor=%\" PRId8 \", verMinor=%\" PRId8 \", serverVersion=%\" PRId16\n\t \", extendedAuth=%s\",\n\t error, verMajor, verMinor, serverVersion, extended_auth_to_string(extendedAuth));", "\tif (FAILED(errorCode))\n\t{\n\t\tWLog_ERR(TAG, \"Handshake error %s\", error);\n\t\tfreerdp_set_last_error_log(rdg->context, errorCode);\n\t\treturn FALSE;\n\t}", "\treturn rdg_send_tunnel_request(rdg);\n}", "static BOOL rdg_process_tunnel_response(rdpRdg* rdg, wStream* s)\n{\n\tUINT16 serverVersion, fieldsPresent;\n\tUINT32 errorCode;\n\tconst char* error;\n\tWLog_DBG(TAG, \"Tunnel response received\");", "\tif (rdg->state != RDG_CLIENT_STATE_TUNNEL_CREATE)\n\t{\n\t\treturn FALSE;\n\t}", "\tif (Stream_GetRemainingLength(s) < 10)\n\t{\n\t\tWLog_ERR(TAG, \"[%s] Short packet %\" PRIuz \", expected 10\", __FUNCTION__,\n\t\t Stream_GetRemainingLength(s));\n\t\treturn FALSE;\n\t}", "\tStream_Read_UINT16(s, serverVersion);\n\tStream_Read_UINT32(s, errorCode);\n\tStream_Read_UINT16(s, fieldsPresent);\n\tStream_Seek_UINT16(s); /* reserved */\n\terror = rpc_error_to_string(errorCode);\n\tWLog_DBG(TAG, \"serverVersion=%\" PRId16 \", errorCode=%s, fieldsPresent=%s\", serverVersion, error,\n\t tunnel_response_fields_present_to_string(fieldsPresent));", "\tif (FAILED(errorCode))\n\t{\n\t\tWLog_ERR(TAG, \"Tunnel creation error %s\", error);\n\t\tfreerdp_set_last_error_log(rdg->context, errorCode);\n\t\treturn FALSE;\n\t}", "\treturn rdg_send_tunnel_authorization(rdg);\n}", "static BOOL rdg_process_tunnel_authorization_response(rdpRdg* rdg, wStream* s)\n{\n\tUINT32 errorCode;\n\tUINT16 fieldsPresent;\n\tconst char* error;\n\tWLog_DBG(TAG, \"Tunnel authorization received\");", "\tif (rdg->state != RDG_CLIENT_STATE_TUNNEL_AUTHORIZE)\n\t{\n\t\treturn FALSE;\n\t}", "\tif (Stream_GetRemainingLength(s) < 8)\n\t{\n\t\tWLog_ERR(TAG, \"[%s] Short packet %\" PRIuz \", expected 8\", __FUNCTION__,\n\t\t Stream_GetRemainingLength(s));\n\t\treturn FALSE;\n\t}", "\tStream_Read_UINT32(s, errorCode);\n\tStream_Read_UINT16(s, fieldsPresent);\n\tStream_Seek_UINT16(s); /* reserved */\n\terror = rpc_error_to_string(errorCode);\n\tWLog_DBG(TAG, \"errorCode=%s, fieldsPresent=%s\", error,\n\t tunnel_authorization_response_fields_present_to_string(fieldsPresent));", "\tif (FAILED(errorCode))\n\t{\n\t\tWLog_ERR(TAG, \"Tunnel authorization error %s\", error);\n\t\tfreerdp_set_last_error_log(rdg->context, errorCode);\n\t\treturn FALSE;\n\t}", "\treturn rdg_send_channel_create(rdg);\n}", "static BOOL rdg_process_channel_response(rdpRdg* rdg, wStream* s)\n{\n\tUINT16 fieldsPresent;\n\tUINT32 errorCode;\n\tconst char* error;\n\tWLog_DBG(TAG, \"Channel response received\");", "\tif (rdg->state != RDG_CLIENT_STATE_CHANNEL_CREATE)\n\t{\n\t\treturn FALSE;\n\t}", "\tif (Stream_GetRemainingLength(s) < 8)\n\t{\n\t\tWLog_ERR(TAG, \"[%s] Short packet %\" PRIuz \", expected 8\", __FUNCTION__,\n\t\t Stream_GetRemainingLength(s));\n\t\treturn FALSE;\n\t}", "\tStream_Read_UINT32(s, errorCode);\n\tStream_Read_UINT16(s, fieldsPresent);\n\tStream_Seek_UINT16(s); /* reserved */\n\terror = rpc_error_to_string(errorCode);\n\tWLog_DBG(TAG, \"channel response errorCode=%s, fieldsPresent=%s\", error,\n\t channel_response_fields_present_to_string(fieldsPresent));", "\tif (FAILED(errorCode))\n\t{\n\t\tWLog_ERR(TAG, \"channel response errorCode=%s, fieldsPresent=%s\", error,\n\t\t channel_response_fields_present_to_string(fieldsPresent));\n\t\tfreerdp_set_last_error_log(rdg->context, errorCode);\n\t\treturn FALSE;\n\t}", "\trdg->state = RDG_CLIENT_STATE_OPENED;\n\treturn TRUE;\n}", "static BOOL rdg_process_packet(rdpRdg* rdg, wStream* s)\n{\n\tBOOL status = TRUE;\n\tUINT16 type;\n\tUINT32 packetLength;\n\tStream_SetPosition(s, 0);", "\tif (Stream_GetRemainingLength(s) < 8)\n\t{\n\t\tWLog_ERR(TAG, \"[%s] Short packet %\" PRIuz \", expected 8\", __FUNCTION__,\n\t\t Stream_GetRemainingLength(s));\n\t\treturn FALSE;\n\t}", "\tStream_Read_UINT16(s, type);\n\tStream_Seek_UINT16(s); /* reserved */\n\tStream_Read_UINT32(s, packetLength);", "\tif (Stream_Length(s) < packetLength)\n\t{\n\t\tWLog_ERR(TAG, \"[%s] Short packet %\" PRIuz \", expected %\" PRIuz, __FUNCTION__,\n\t\t Stream_Length(s), packetLength);\n\t\treturn FALSE;\n\t}", "\tswitch (type)\n\t{\n\t\tcase PKT_TYPE_HANDSHAKE_RESPONSE:\n\t\t\tstatus = rdg_process_handshake_response(rdg, s);\n\t\t\tbreak;", "\t\tcase PKT_TYPE_TUNNEL_RESPONSE:\n\t\t\tstatus = rdg_process_tunnel_response(rdg, s);\n\t\t\tbreak;", "\t\tcase PKT_TYPE_TUNNEL_AUTH_RESPONSE:\n\t\t\tstatus = rdg_process_tunnel_authorization_response(rdg, s);\n\t\t\tbreak;", "\t\tcase PKT_TYPE_CHANNEL_RESPONSE:\n\t\t\tstatus = rdg_process_channel_response(rdg, s);\n\t\t\tbreak;", "\t\tcase PKT_TYPE_DATA:\n\t\t\tWLog_ERR(TAG, \"[%s] Unexpected packet type DATA\", __FUNCTION__);\n\t\t\treturn FALSE;\n\t}", "\treturn status;\n}", "DWORD rdg_get_event_handles(rdpRdg* rdg, HANDLE* events, DWORD count)\n{\n\tDWORD nCount = 0;\n\tassert(rdg != NULL);", "\tif (rdg->tlsOut && rdg->tlsOut->bio)\n\t{\n\t\tif (events && (nCount < count))\n\t\t{\n\t\t\tBIO_get_event(rdg->tlsOut->bio, &events[nCount]);\n\t\t\tnCount++;\n\t\t}\n\t\telse\n\t\t\treturn 0;\n\t}", "\tif (rdg->tlsIn && rdg->tlsIn->bio)\n\t{\n\t\tif (events && (nCount < count))\n\t\t{\n\t\t\tBIO_get_event(rdg->tlsIn->bio, &events[nCount]);\n\t\t\tnCount++;\n\t\t}\n\t\telse\n\t\t\treturn 0;\n\t}", "\treturn nCount;\n}", "static BOOL rdg_get_gateway_credentials(rdpContext* context)\n{\n\trdpSettings* settings = context->settings;\n\tfreerdp* instance = context->instance;", "\tif (!settings->GatewayPassword || !settings->GatewayUsername ||\n\t !strlen(settings->GatewayPassword) || !strlen(settings->GatewayUsername))\n\t{\n\t\tif (freerdp_shall_disconnect(instance))\n\t\t\treturn FALSE;", "\t\tif (!instance->GatewayAuthenticate)\n\t\t{\n\t\t\tfreerdp_set_last_error_log(context, FREERDP_ERROR_CONNECT_NO_OR_MISSING_CREDENTIALS);\n\t\t\treturn FALSE;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tBOOL proceed =\n\t\t\t instance->GatewayAuthenticate(instance, &settings->GatewayUsername,\n\t\t\t &settings->GatewayPassword, &settings->GatewayDomain);", "\t\t\tif (!proceed)\n\t\t\t{\n\t\t\t\tfreerdp_set_last_error_log(context,\n\t\t\t\t FREERDP_ERROR_CONNECT_NO_OR_MISSING_CREDENTIALS);\n\t\t\t\treturn FALSE;\n\t\t\t}", "\t\t\tif (settings->GatewayUseSameCredentials)\n\t\t\t{\n\t\t\t\tif (settings->GatewayUsername)\n\t\t\t\t{\n\t\t\t\t\tfree(settings->Username);", "\t\t\t\t\tif (!(settings->Username = _strdup(settings->GatewayUsername)))\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t}", "\t\t\t\tif (settings->GatewayDomain)\n\t\t\t\t{\n\t\t\t\t\tfree(settings->Domain);", "\t\t\t\t\tif (!(settings->Domain = _strdup(settings->GatewayDomain)))\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t}", "\t\t\t\tif (settings->GatewayPassword)\n\t\t\t\t{\n\t\t\t\t\tfree(settings->Password);", "\t\t\t\t\tif (!(settings->Password = _strdup(settings->GatewayPassword)))\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "\treturn TRUE;\n}", "static BOOL rdg_ntlm_init(rdpRdg* rdg, rdpTls* tls)\n{\n\tBOOL continueNeeded = FALSE;\n\trdpContext* context = rdg->context;\n\trdpSettings* settings = context->settings;\n\trdg->ntlm = ntlm_new();", "\tif (!rdg->ntlm)\n\t\treturn FALSE;", "\tif (!rdg_get_gateway_credentials(context))\n\t\treturn FALSE;", "\tif (!ntlm_client_init(rdg->ntlm, TRUE, settings->GatewayUsername, settings->GatewayDomain,\n\t settings->GatewayPassword, tls->Bindings))\n\t\treturn FALSE;", "\tif (!ntlm_client_make_spn(rdg->ntlm, _T(\"HTTP\"), settings->GatewayHostname))\n\t\treturn FALSE;", "\tif (!ntlm_authenticate(rdg->ntlm, &continueNeeded))\n\t\treturn FALSE;", "\treturn continueNeeded;\n}", "static BOOL rdg_send_http_request(rdpRdg* rdg, rdpTls* tls, const char* method,\n const char* transferEncoding)\n{\n\tsize_t sz;\n\twStream* s = NULL;\n\tint status = -1;\n\ts = rdg_build_http_request(rdg, method, transferEncoding);", "\tif (!s)\n\t\treturn FALSE;", "\tsz = Stream_Length(s);", "\tif (sz <= INT_MAX)\n\t\tstatus = tls_write_all(tls, Stream_Buffer(s), (int)sz);", "\tStream_Free(s, TRUE);\n\treturn (status >= 0);\n}", "static BOOL rdg_tls_connect(rdpRdg* rdg, rdpTls* tls, const char* peerAddress, int timeout)\n{\n\tint sockfd = 0;\n\tlong status = 0;\n\tBIO* socketBio = NULL;\n\tBIO* bufferedBio = NULL;\n\trdpSettings* settings = rdg->settings;\n\tconst char* peerHostname = settings->GatewayHostname;\n\tUINT16 peerPort = (UINT16)settings->GatewayPort;\n\tconst char *proxyUsername, *proxyPassword;\n\tBOOL isProxyConnection =\n\t proxy_prepare(settings, &peerHostname, &peerPort, &proxyUsername, &proxyPassword);", "\tif (settings->GatewayPort > UINT16_MAX)\n\t\treturn FALSE;", "\tsockfd = freerdp_tcp_connect(rdg->context, settings, peerAddress ? peerAddress : peerHostname,\n\t peerPort, timeout);", "\tif (sockfd < 0)\n\t{\n\t\treturn FALSE;\n\t}", "\tsocketBio = BIO_new(BIO_s_simple_socket());", "\tif (!socketBio)\n\t{\n\t\tclosesocket((SOCKET)sockfd);\n\t\treturn FALSE;\n\t}", "\tBIO_set_fd(socketBio, sockfd, BIO_CLOSE);\n\tbufferedBio = BIO_new(BIO_s_buffered_socket());", "\tif (!bufferedBio)\n\t{\n\t\tBIO_free_all(socketBio);\n\t\treturn FALSE;\n\t}", "\tbufferedBio = BIO_push(bufferedBio, socketBio);\n\tstatus = BIO_set_nonblock(bufferedBio, TRUE);", "\tif (isProxyConnection)\n\t{\n\t\tif (!proxy_connect(settings, bufferedBio, proxyUsername, proxyPassword,\n\t\t settings->GatewayHostname, (UINT16)settings->GatewayPort))\n\t\t{\n\t\t\tBIO_free_all(bufferedBio);\n\t\t\treturn FALSE;\n\t\t}\n\t}", "\tif (!status)\n\t{\n\t\tBIO_free_all(bufferedBio);\n\t\treturn FALSE;\n\t}", "\ttls->hostname = settings->GatewayHostname;\n\ttls->port = (int)settings->GatewayPort;\n\ttls->isGatewayTransport = TRUE;\n\tstatus = tls_connect(tls, bufferedBio);\n\tif (status < 1)\n\t{\n\t\trdpContext* context = rdg->context;\n\t\tif (status < 0)\n\t\t{\n\t\t\tfreerdp_set_last_error_if_not(context, FREERDP_ERROR_TLS_CONNECT_FAILED);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfreerdp_set_last_error_if_not(context, FREERDP_ERROR_CONNECT_CANCELLED);\n\t\t}", "\t\treturn FALSE;\n\t}\n\treturn (status >= 1);\n}", "static BOOL rdg_establish_data_connection(rdpRdg* rdg, rdpTls* tls, const char* method,\n const char* peerAddress, int timeout, BOOL* rpcFallback)\n{\n\tHttpResponse* response = NULL;\n\tlong statusCode;\n\tSSIZE_T bodyLength;\n\tlong StatusCode;", "\tif (!rdg_tls_connect(rdg, tls, peerAddress, timeout))\n\t\treturn FALSE;", "\tif (rdg->extAuth == HTTP_EXTENDED_AUTH_NONE)\n\t{\n\t\tif (!rdg_ntlm_init(rdg, tls))\n\t\t\treturn FALSE;", "\t\tif (!rdg_send_http_request(rdg, tls, method, NULL))\n\t\t\treturn FALSE;", "\t\tresponse = http_response_recv(tls, TRUE);", "\t\tif (!response)\n\t\t\treturn FALSE;", "\t\tStatusCode = http_response_get_status_code(response);", "\t\tswitch (StatusCode)\n\t\t{\n\t\t\tcase HTTP_STATUS_NOT_FOUND:\n\t\t\t{\n\t\t\t\tWLog_INFO(TAG, \"RD Gateway does not support HTTP transport.\");", "\t\t\t\tif (rpcFallback)\n\t\t\t\t\t*rpcFallback = TRUE;", "\t\t\t\thttp_response_free(response);\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}", "\t\tif (!rdg_handle_ntlm_challenge(rdg->ntlm, response))\n\t\t{\n\t\t\thttp_response_free(response);\n\t\t\treturn FALSE;\n\t\t}", "\t\thttp_response_free(response);\n\t}", "\tif (!rdg_send_http_request(rdg, tls, method, NULL))\n\t\treturn FALSE;", "\tntlm_free(rdg->ntlm);\n\trdg->ntlm = NULL;\n\tresponse = http_response_recv(tls, TRUE);", "\tif (!response)\n\t\treturn FALSE;", "\tstatusCode = http_response_get_status_code(response);\n\tbodyLength = http_response_get_body_length(response);\n\thttp_response_free(response);\n\tWLog_DBG(TAG, \"%s authorization result: %d\", method, statusCode);", "\tswitch (statusCode)\n\t{\n\t\tcase HTTP_STATUS_OK:\n\t\t\tbreak;\n\t\tcase HTTP_STATUS_DENIED:\n\t\t\tfreerdp_set_last_error_log(rdg->context, FREERDP_ERROR_CONNECT_ACCESS_DENIED);\n\t\t\treturn FALSE;\n\t\tdefault:\n\t\t\treturn FALSE;\n\t}", "\tif (strcmp(method, \"RDG_OUT_DATA\") == 0)\n\t{\n\t\tif (!rdg_skip_seed_payload(tls, bodyLength))\n\t\t\treturn FALSE;\n\t}\n\telse\n\t{\n\t\tif (!rdg_send_http_request(rdg, tls, method, \"chunked\"))\n\t\t\treturn FALSE;\n\t}", "\treturn TRUE;\n}", "static BOOL rdg_tunnel_connect(rdpRdg* rdg)\n{\n\tBOOL status;\n\twStream* s;\n\trdg_send_handshake(rdg);", "\twhile (rdg->state < RDG_CLIENT_STATE_OPENED)\n\t{\n\t\tstatus = FALSE;\n\t\ts = rdg_receive_packet(rdg);", "\t\tif (s)\n\t\t{\n\t\t\tstatus = rdg_process_packet(rdg, s);\n\t\t\tStream_Free(s, TRUE);\n\t\t}", "\t\tif (!status)\n\t\t{\n\t\t\trdg->context->rdp->transport->layer = TRANSPORT_LAYER_CLOSED;\n\t\t\treturn FALSE;\n\t\t}\n\t}", "\treturn TRUE;\n}", "BOOL rdg_connect(rdpRdg* rdg, int timeout, BOOL* rpcFallback)\n{\n\tBOOL status;\n\tSOCKET outConnSocket = 0;\n\tchar* peerAddress = NULL;\n\tassert(rdg != NULL);\n\tstatus =\n\t rdg_establish_data_connection(rdg, rdg->tlsOut, \"RDG_OUT_DATA\", NULL, timeout, rpcFallback);", "\tif (status)\n\t{\n\t\t/* Establish IN connection with the same peer/server as OUT connection,\n\t\t * even when server hostname resolves to different IP addresses.\n\t\t */\n\t\tBIO_get_socket(rdg->tlsOut->underlying, &outConnSocket);\n\t\tpeerAddress = freerdp_tcp_get_peer_address(outConnSocket);\n\t\tstatus = rdg_establish_data_connection(rdg, rdg->tlsIn, \"RDG_IN_DATA\", peerAddress, timeout,\n\t\t NULL);\n\t\tfree(peerAddress);\n\t}", "\tif (!status)\n\t{\n\t\trdg->context->rdp->transport->layer = TRANSPORT_LAYER_CLOSED;\n\t\treturn FALSE;\n\t}", "\tstatus = rdg_tunnel_connect(rdg);", "\tif (!status)\n\t\treturn FALSE;", "\treturn TRUE;\n}", "static int rdg_write_data_packet(rdpRdg* rdg, const BYTE* buf, int isize)\n{\n\tint status;\n\tsize_t s;\n\twStream* sChunk;\n\tsize_t size = (size_t)isize;\n\tsize_t packetSize = size + 10;\n\tchar chunkSize[11];", "\tif ((isize < 0) || (isize > UINT16_MAX))\n\t\treturn -1;", "\tif (size < 1)\n\t\treturn 0;", "\tsprintf_s(chunkSize, sizeof(chunkSize), \"%\" PRIxz \"\\r\\n\", packetSize);\n\tsChunk = Stream_New(NULL, strnlen(chunkSize, sizeof(chunkSize)) + packetSize + 2);", "\tif (!sChunk)\n\t\treturn -1;", "\tStream_Write(sChunk, chunkSize, strnlen(chunkSize, sizeof(chunkSize)));\n\tStream_Write_UINT16(sChunk, PKT_TYPE_DATA); /* Type */\n\tStream_Write_UINT16(sChunk, 0); /* Reserved */\n\tStream_Write_UINT32(sChunk, (UINT32)packetSize); /* Packet length */\n\tStream_Write_UINT16(sChunk, (UINT16)size); /* Data size */\n\tStream_Write(sChunk, buf, size); /* Data */\n\tStream_Write(sChunk, \"\\r\\n\", 2);\n\tStream_SealLength(sChunk);\n\ts = Stream_Length(sChunk);", "\tif (s > INT_MAX)\n\t\treturn -1;", "\tstatus = tls_write_all(rdg->tlsIn, Stream_Buffer(sChunk), (int)s);\n\tStream_Free(sChunk, TRUE);", "\tif (status < 0)\n\t\treturn -1;", "\treturn (int)size;\n}", "static BOOL rdg_process_close_packet(rdpRdg* rdg)\n{\n\tint status = -1;\n\tsize_t s;\n\twStream* sChunk;\n\tUINT32 packetSize = 12;\n\tchar chunkSize[11];\n\tint chunkLen = sprintf_s(chunkSize, sizeof(chunkSize), \"%\" PRIx32 \"\\r\\n\", packetSize);", "\tif (chunkLen < 0)\n\t\treturn FALSE;", "\tsChunk = Stream_New(NULL, (size_t)chunkLen + packetSize + 2);", "\tif (!sChunk)\n\t\treturn FALSE;", "\tStream_Write(sChunk, chunkSize, (size_t)chunkLen);\n\tStream_Write_UINT16(sChunk, PKT_TYPE_CLOSE_CHANNEL_RESPONSE); /* Type */\n\tStream_Write_UINT16(sChunk, 0); /* Reserved */\n\tStream_Write_UINT32(sChunk, packetSize); /* Packet length */\n\tStream_Write_UINT32(sChunk, 0); /* Status code */\n\tStream_Write(sChunk, \"\\r\\n\", 2);\n\tStream_SealLength(sChunk);\n\ts = Stream_Length(sChunk);", "\tif (s <= INT_MAX)\n\t\tstatus = tls_write_all(rdg->tlsIn, Stream_Buffer(sChunk), (int)s);", "\tStream_Free(sChunk, TRUE);\n\treturn (status < 0 ? FALSE : TRUE);\n}", "static BOOL rdg_process_keep_alive_packet(rdpRdg* rdg)\n{\n\tint status = -1;\n\tsize_t s;\n\twStream* sChunk;\n\tsize_t packetSize = 8;\n\tchar chunkSize[11];\n\tint chunkLen = sprintf_s(chunkSize, sizeof(chunkSize), \"%\" PRIxz \"\\r\\n\", packetSize);", "\tif ((chunkLen < 0) || (packetSize > UINT32_MAX))\n\t\treturn FALSE;", "\tsChunk = Stream_New(NULL, (size_t)chunkLen + packetSize + 2);", "\tif (!sChunk)\n\t\treturn FALSE;", "\tStream_Write(sChunk, chunkSize, (size_t)chunkLen);\n\tStream_Write_UINT16(sChunk, PKT_TYPE_KEEPALIVE); /* Type */\n\tStream_Write_UINT16(sChunk, 0); /* Reserved */\n\tStream_Write_UINT32(sChunk, (UINT32)packetSize); /* Packet length */\n\tStream_Write(sChunk, \"\\r\\n\", 2);\n\tStream_SealLength(sChunk);\n\ts = Stream_Length(sChunk);", "\tif (s <= INT_MAX)\n\t\tstatus = tls_write_all(rdg->tlsIn, Stream_Buffer(sChunk), (int)s);", "\tStream_Free(sChunk, TRUE);\n\treturn (status < 0 ? FALSE : TRUE);\n}", "static BOOL rdg_process_unknown_packet(rdpRdg* rdg, int type)\n{\n\tWINPR_UNUSED(rdg);\n\tWINPR_UNUSED(type);\n\tWLog_WARN(TAG, \"Unknown Control Packet received: %X\", type);\n\treturn TRUE;\n}", "static BOOL rdg_process_control_packet(rdpRdg* rdg, int type, size_t packetLength)\n{\n\twStream* s = NULL;\n\tsize_t readCount = 0;\n\tint status;\n\tsize_t payloadSize = packetLength - sizeof(RdgPacketHeader);", "\tif (packetLength < sizeof(RdgPacketHeader))\n\t\treturn FALSE;", "\tassert(sizeof(RdgPacketHeader) < INT_MAX);", "\tif (payloadSize)\n\t{\n\t\ts = Stream_New(NULL, payloadSize);", "\t\tif (!s)\n\t\t\treturn FALSE;", "\t\twhile (readCount < payloadSize)\n\t\t{\n\t\t\tstatus =\n\t\t\t BIO_read(rdg->tlsOut->bio, Stream_Pointer(s), (int)payloadSize - (int)readCount);", "\t\t\tif (status <= 0)\n\t\t\t{\n\t\t\t\tif (!BIO_should_retry(rdg->tlsOut->bio))\n\t\t\t\t{\n\t\t\t\t\tStream_Free(s, TRUE);\n\t\t\t\t\treturn FALSE;\n\t\t\t\t}", "\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tStream_Seek(s, (size_t)status);\n\t\t\treadCount += (size_t)status;", "\t\t\tif (readCount > INT_MAX)\n\t\t\t{\n\t\t\t\tStream_Free(s, TRUE);\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t}\n\t}", "\tswitch (type)\n\t{\n\t\tcase PKT_TYPE_CLOSE_CHANNEL:\n\t\t\tEnterCriticalSection(&rdg->writeSection);\n\t\t\tstatus = rdg_process_close_packet(rdg);\n\t\t\tLeaveCriticalSection(&rdg->writeSection);\n\t\t\tbreak;", "\t\tcase PKT_TYPE_KEEPALIVE:\n\t\t\tEnterCriticalSection(&rdg->writeSection);\n\t\t\tstatus = rdg_process_keep_alive_packet(rdg);\n\t\t\tLeaveCriticalSection(&rdg->writeSection);\n\t\t\tbreak;", "\t\tdefault:\n\t\t\tstatus = rdg_process_unknown_packet(rdg, type);\n\t\t\tbreak;\n\t}", "\tStream_Free(s, TRUE);\n\treturn status;\n}", "static int rdg_read_data_packet(rdpRdg* rdg, BYTE* buffer, int size)\n{\n\tRdgPacketHeader header;\n\tsize_t readCount = 0;\n\tint readSize;\n\tint status;", "\tif (!rdg->packetRemainingCount)\n\t{\n\t\tassert(sizeof(RdgPacketHeader) < INT_MAX);", "\t\twhile (readCount < sizeof(RdgPacketHeader))\n\t\t{\n\t\t\tstatus = BIO_read(rdg->tlsOut->bio, (BYTE*)(&header) + readCount,\n\t\t\t (int)sizeof(RdgPacketHeader) - (int)readCount);", "\t\t\tif (status <= 0)\n\t\t\t{\n\t\t\t\tif (!BIO_should_retry(rdg->tlsOut->bio))\n\t\t\t\t\treturn -1;", "\t\t\t\tif (!readCount)\n\t\t\t\t\treturn 0;", "\t\t\t\tBIO_wait_read(rdg->tlsOut->bio, 50);\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\treadCount += (size_t)status;", "\t\t\tif (readCount > INT_MAX)\n\t\t\t\treturn -1;\n\t\t}", "\t\tif (header.type != PKT_TYPE_DATA)\n\t\t{\n\t\t\tstatus = rdg_process_control_packet(rdg, header.type, header.packetLength);", "\t\t\tif (!status)\n\t\t\t\treturn -1;", "\t\t\treturn 0;\n\t\t}", "\t\treadCount = 0;", "\t\twhile (readCount < 2)\n\t\t{\n\t\t\tstatus = BIO_read(rdg->tlsOut->bio, (BYTE*)(&rdg->packetRemainingCount) + readCount,\n\t\t\t 2 - (int)readCount);", "\t\t\tif (status < 0)\n\t\t\t{\n\t\t\t\tif (!BIO_should_retry(rdg->tlsOut->bio))\n\t\t\t\t\treturn -1;", "\t\t\t\tBIO_wait_read(rdg->tlsOut->bio, 50);\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\treadCount += (size_t)status;\n\t\t}\n\t}", "\treadSize = (rdg->packetRemainingCount < size ? rdg->packetRemainingCount : size);\n\tstatus = BIO_read(rdg->tlsOut->bio, buffer, readSize);", "\tif (status <= 0)\n\t{\n\t\tif (!BIO_should_retry(rdg->tlsOut->bio))\n\t\t{\n\t\t\treturn -1;\n\t\t}", "\t\treturn 0;\n\t}", "\trdg->packetRemainingCount -= status;\n\treturn status;\n}", "static int rdg_bio_write(BIO* bio, const char* buf, int num)\n{\n\tint status;\n\trdpRdg* rdg = (rdpRdg*)BIO_get_data(bio);\n\tBIO_clear_flags(bio, BIO_FLAGS_WRITE);\n\tEnterCriticalSection(&rdg->writeSection);\n\tstatus = rdg_write_data_packet(rdg, (const BYTE*)buf, num);\n\tLeaveCriticalSection(&rdg->writeSection);", "\tif (status < 0)\n\t{\n\t\tBIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);\n\t\treturn -1;\n\t}\n\telse if (status < num)\n\t{\n\t\tBIO_set_flags(bio, BIO_FLAGS_WRITE);\n\t\tWSASetLastError(WSAEWOULDBLOCK);\n\t}\n\telse\n\t{\n\t\tBIO_set_flags(bio, BIO_FLAGS_WRITE);\n\t}", "\treturn status;\n}", "static int rdg_bio_read(BIO* bio, char* buf, int size)\n{\n\tint status;\n\trdpRdg* rdg = (rdpRdg*)BIO_get_data(bio);\n\tstatus = rdg_read_data_packet(rdg, (BYTE*)buf, size);", "\tif (status < 0)\n\t{\n\t\tBIO_clear_retry_flags(bio);\n\t\treturn -1;\n\t}\n\telse if (status == 0)\n\t{\n\t\tBIO_set_retry_read(bio);\n\t\tWSASetLastError(WSAEWOULDBLOCK);\n\t\treturn -1;\n\t}\n\telse\n\t{\n\t\tBIO_set_flags(bio, BIO_FLAGS_READ);\n\t}", "\treturn status;\n}", "static int rdg_bio_puts(BIO* bio, const char* str)\n{\n\tWINPR_UNUSED(bio);\n\tWINPR_UNUSED(str);\n\treturn -2;\n}", "static int rdg_bio_gets(BIO* bio, char* str, int size)\n{\n\tWINPR_UNUSED(bio);\n\tWINPR_UNUSED(str);\n\tWINPR_UNUSED(size);\n\treturn -2;\n}", "static long rdg_bio_ctrl(BIO* bio, int cmd, long arg1, void* arg2)\n{\n\tlong status = -1;\n\trdpRdg* rdg = (rdpRdg*)BIO_get_data(bio);\n\trdpTls* tlsOut = rdg->tlsOut;\n\trdpTls* tlsIn = rdg->tlsIn;", "\tif (cmd == BIO_CTRL_FLUSH)\n\t{\n\t\t(void)BIO_flush(tlsOut->bio);\n\t\t(void)BIO_flush(tlsIn->bio);\n\t\tstatus = 1;\n\t}\n\telse if (cmd == BIO_C_SET_NONBLOCK)\n\t{\n\t\tstatus = 1;\n\t}\n\telse if (cmd == BIO_C_READ_BLOCKED)\n\t{\n\t\tBIO* bio = tlsOut->bio;\n\t\tstatus = BIO_read_blocked(bio);\n\t}\n\telse if (cmd == BIO_C_WRITE_BLOCKED)\n\t{\n\t\tBIO* bio = tlsIn->bio;\n\t\tstatus = BIO_write_blocked(bio);\n\t}\n\telse if (cmd == BIO_C_WAIT_READ)\n\t{\n\t\tint timeout = (int)arg1;\n\t\tBIO* bio = tlsOut->bio;", "\t\tif (BIO_read_blocked(bio))\n\t\t\treturn BIO_wait_read(bio, timeout);\n\t\telse if (BIO_write_blocked(bio))\n\t\t\treturn BIO_wait_write(bio, timeout);\n\t\telse\n\t\t\tstatus = 1;\n\t}\n\telse if (cmd == BIO_C_WAIT_WRITE)\n\t{\n\t\tint timeout = (int)arg1;\n\t\tBIO* bio = tlsIn->bio;", "\t\tif (BIO_write_blocked(bio))\n\t\t\tstatus = BIO_wait_write(bio, timeout);\n\t\telse if (BIO_read_blocked(bio))\n\t\t\tstatus = BIO_wait_read(bio, timeout);\n\t\telse\n\t\t\tstatus = 1;\n\t}\n\telse if (cmd == BIO_C_GET_EVENT || cmd == BIO_C_GET_FD)\n\t{\n\t\t/*\n\t\t * A note about BIO_C_GET_FD:\n\t\t * Even if two FDs are part of RDG, only one FD can be returned here.\n\t\t *\n\t\t * In FreeRDP, BIO FDs are only used for polling, so it is safe to use the outgoing FD only\n\t\t *\n\t\t * See issue #3602\n\t\t */\n\t\tstatus = BIO_ctrl(tlsOut->bio, cmd, arg1, arg2);\n\t}", "\treturn status;\n}", "static int rdg_bio_new(BIO* bio)\n{\n\tBIO_set_init(bio, 1);\n\tBIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY);\n\treturn 1;\n}", "static int rdg_bio_free(BIO* bio)\n{\n\tWINPR_UNUSED(bio);\n\treturn 1;\n}", "static BIO_METHOD* BIO_s_rdg(void)\n{\n\tstatic BIO_METHOD* bio_methods = NULL;", "\tif (bio_methods == NULL)\n\t{\n\t\tif (!(bio_methods = BIO_meth_new(BIO_TYPE_TSG, \"RDGateway\")))\n\t\t\treturn NULL;", "\t\tBIO_meth_set_write(bio_methods, rdg_bio_write);\n\t\tBIO_meth_set_read(bio_methods, rdg_bio_read);\n\t\tBIO_meth_set_puts(bio_methods, rdg_bio_puts);\n\t\tBIO_meth_set_gets(bio_methods, rdg_bio_gets);\n\t\tBIO_meth_set_ctrl(bio_methods, rdg_bio_ctrl);\n\t\tBIO_meth_set_create(bio_methods, rdg_bio_new);\n\t\tBIO_meth_set_destroy(bio_methods, rdg_bio_free);\n\t}", "\treturn bio_methods;\n}", "rdpRdg* rdg_new(rdpContext* context)\n{\n\trdpRdg* rdg;\n\tRPC_CSTR stringUuid;\n\tchar bracedUuid[40];\n\tRPC_STATUS rpcStatus;", "\tif (!context)\n\t\treturn NULL;", "\trdg = (rdpRdg*)calloc(1, sizeof(rdpRdg));", "\tif (rdg)\n\t{\n\t\trdg->state = RDG_CLIENT_STATE_INITIAL;\n\t\trdg->context = context;\n\t\trdg->settings = rdg->context->settings;\n\t\trdg->extAuth = HTTP_EXTENDED_AUTH_NONE;", "\t\tif (rdg->settings->GatewayAccessToken)\n\t\t\trdg->extAuth = HTTP_EXTENDED_AUTH_PAA;", "\t\tUuidCreate(&rdg->guid);\n\t\trpcStatus = UuidToStringA(&rdg->guid, &stringUuid);", "\t\tif (rpcStatus == RPC_S_OUT_OF_MEMORY)\n\t\t\tgoto rdg_alloc_error;", "\t\tsprintf_s(bracedUuid, sizeof(bracedUuid), \"{%s}\", stringUuid);\n\t\tRpcStringFreeA(&stringUuid);\n\t\trdg->tlsOut = tls_new(rdg->settings);", "\t\tif (!rdg->tlsOut)\n\t\t\tgoto rdg_alloc_error;", "\t\trdg->tlsIn = tls_new(rdg->settings);", "\t\tif (!rdg->tlsIn)\n\t\t\tgoto rdg_alloc_error;", "\t\trdg->http = http_context_new();", "\t\tif (!rdg->http)\n\t\t\tgoto rdg_alloc_error;", "\t\tif (!http_context_set_uri(rdg->http, \"/remoteDesktopGateway/\") ||\n\t\t !http_context_set_accept(rdg->http, \"*/*\") ||\n\t\t !http_context_set_cache_control(rdg->http, \"no-cache\") ||\n\t\t !http_context_set_pragma(rdg->http, \"no-cache\") ||\n\t\t !http_context_set_connection(rdg->http, \"Keep-Alive\") ||\n\t\t !http_context_set_user_agent(rdg->http, \"MS-RDGateway/1.0\") ||\n\t\t !http_context_set_host(rdg->http, rdg->settings->GatewayHostname) ||\n\t\t !http_context_set_rdg_connection_id(rdg->http, bracedUuid))\n\t\t{\n\t\t\tgoto rdg_alloc_error;\n\t\t}", "\t\tif (rdg->extAuth != HTTP_EXTENDED_AUTH_NONE)\n\t\t{\n\t\t\tswitch (rdg->extAuth)\n\t\t\t{\n\t\t\t\tcase HTTP_EXTENDED_AUTH_PAA:\n\t\t\t\t\tif (!http_context_set_rdg_auth_scheme(rdg->http, \"PAA\"))\n\t\t\t\t\t\tgoto rdg_alloc_error;", "\t\t\t\t\tbreak;", "\t\t\t\tdefault:\n\t\t\t\t\tWLog_DBG(TAG, \"RDG extended authentication method %d not supported\",\n\t\t\t\t\t rdg->extAuth);\n\t\t\t}\n\t\t}", "\t\trdg->frontBio = BIO_new(BIO_s_rdg());", "\t\tif (!rdg->frontBio)\n\t\t\tgoto rdg_alloc_error;", "\t\tBIO_set_data(rdg->frontBio, rdg);\n\t\tInitializeCriticalSection(&rdg->writeSection);\n\t}", "\treturn rdg;\nrdg_alloc_error:\n\trdg_free(rdg);\n\treturn NULL;\n}", "void rdg_free(rdpRdg* rdg)\n{\n\tif (!rdg)\n\t\treturn;", "\ttls_free(rdg->tlsOut);\n\ttls_free(rdg->tlsIn);\n\thttp_context_free(rdg->http);\n\tntlm_free(rdg->ntlm);", "\tif (!rdg->attached)\n\t\tBIO_free_all(rdg->frontBio);", "\tDeleteCriticalSection(&rdg->writeSection);\n\tfree(rdg);\n}", "BIO* rdg_get_front_bio_and_take_ownership(rdpRdg* rdg)\n{\n\tif (!rdg)\n\t\treturn NULL;", "\trdg->attached = TRUE;\n\treturn rdg->frontBio;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [357, 496, 447, 322, 308, 1001], "buggy_code_start_loc": [333, 480, 447, 145, 307, 94], "filenames": ["channels/drive/client/drive_main.c", "channels/printer/client/printer_main.c", "channels/rdpei/client/rdpei_main.c", "channels/serial/client/serial_main.c", "libfreerdp/core/gateway/rdg.c", "libfreerdp/core/nego.c"], "fixing_code_end_loc": [361, 502, 451, 327, 309, 1013], "fixing_code_start_loc": [334, 481, 448, 145, 307, 94], "message": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:freerdp:freerdp:*:*:*:*:*:*:*:*", "matchCriteriaId": "5C5F8D57-1D22-42B4-9E08-9131F7BE8FA5", "versionEndExcluding": "2.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "B620311B-34A3-48A6-82DF-6F078D7A4493", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0."}, {"lang": "es", "value": "En FreeRDP versiones anteriores a 2.1.0, se presenta una lectura fuera de l\u00edmite en las funciones de irp (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). Esto ha sido corregido en la versi\u00f3n 2.1.0."}], "evaluatorComment": null, "id": "CVE-2020-11089", "lastModified": "2022-07-19T11:52:15.420", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:L/I:L/A:L", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 2.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-05-29T20:15:11.017", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2020-07/msg00080.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/795842f4096501fcefc1a7f535ccc8132feb31d7"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/security/advisories/GHSA-hfc7-c5gv-8c2h"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-125"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, "type": "CWE-125"}
320
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * FreeRDP: A Remote Desktop Protocol Implementation\n * Remote Desktop Gateway (RDG)\n *\n * Copyright 2015 Denis Vincent <dvincent@devolutions.net>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */", "#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif", "#include <assert.h>", "#include <winpr/crt.h>\n#include <winpr/synch.h>\n#include <winpr/print.h>\n#include <winpr/stream.h>\n#include <winpr/winsock.h>", "#include <freerdp/log.h>\n#include <freerdp/error.h>\n#include <freerdp/utils/ringbuffer.h>", "#include \"rdg.h\"\n#include \"../proxy.h\"\n#include \"../rdp.h\"\n#include \"../../crypto/opensslcompat.h\"\n#include \"rpc_fault.h\"", "#define TAG FREERDP_TAG(\"core.gateway.rdg\")", "/* HTTP channel response fields present flags. */\n#define HTTP_CHANNEL_RESPONSE_FIELD_CHANNELID 0x1\n#define HTTP_CHANNEL_RESPONSE_OPTIONAL 0x2\n#define HTTP_CHANNEL_RESPONSE_FIELD_UDPPORT 0x4", "/* HTTP extended auth. */\n#define HTTP_EXTENDED_AUTH_NONE 0x0\n#define HTTP_EXTENDED_AUTH_SC 0x1 /* Smart card authentication. */\n#define HTTP_EXTENDED_AUTH_PAA 0x02 /* Pluggable authentication. */\n#define HTTP_EXTENDED_AUTH_SSPI_NTLM 0x04 /* NTLM extended authentication. */", "/* HTTP packet types. */\n#define PKT_TYPE_HANDSHAKE_REQUEST 0x1\n#define PKT_TYPE_HANDSHAKE_RESPONSE 0x2\n#define PKT_TYPE_EXTENDED_AUTH_MSG 0x3\n#define PKT_TYPE_TUNNEL_CREATE 0x4\n#define PKT_TYPE_TUNNEL_RESPONSE 0x5\n#define PKT_TYPE_TUNNEL_AUTH 0x6\n#define PKT_TYPE_TUNNEL_AUTH_RESPONSE 0x7\n#define PKT_TYPE_CHANNEL_CREATE 0x8\n#define PKT_TYPE_CHANNEL_RESPONSE 0x9\n#define PKT_TYPE_DATA 0xA\n#define PKT_TYPE_SERVICE_MESSAGE 0xB\n#define PKT_TYPE_REAUTH_MESSAGE 0xC\n#define PKT_TYPE_KEEPALIVE 0xD\n#define PKT_TYPE_CLOSE_CHANNEL 0x10\n#define PKT_TYPE_CLOSE_CHANNEL_RESPONSE 0x11", "/* HTTP tunnel auth fields present flags. */\n#define HTTP_TUNNEL_AUTH_FIELD_SOH 0x1", "/* HTTP tunnel auth response fields present flags. */\n#define HTTP_TUNNEL_AUTH_RESPONSE_FIELD_REDIR_FLAGS 0x1\n#define HTTP_TUNNEL_AUTH_RESPONSE_FIELD_IDLE_TIMEOUT 0x2\n#define HTTP_TUNNEL_AUTH_RESPONSE_FIELD_SOH_RESPONSE 0x4", "/* HTTP tunnel packet fields present flags. */\n#define HTTP_TUNNEL_PACKET_FIELD_PAA_COOKIE 0x1\n#define HTTP_TUNNEL_PACKET_FIELD_REAUTH 0x2", "/* HTTP tunnel redir flags. */\n#define HTTP_TUNNEL_REDIR_ENABLE_ALL 0x80000000\n#define HTTP_TUNNEL_REDIR_DISABLE_ALL 0x40000000\n#define HTTP_TUNNEL_REDIR_DISABLE_DRIVE 0x1\n#define HTTP_TUNNEL_REDIR_DISABLE_PRINTER 0x2\n#define HTTP_TUNNEL_REDIR_DISABLE_PORT 0x4\n#define HTTP_TUNNEL_REDIR_DISABLE_CLIPBOARD 0x8\n#define HTTP_TUNNEL_REDIR_DISABLE_PNP 0x10", "/* HTTP tunnel response fields present flags. */\n#define HTTP_TUNNEL_RESPONSE_FIELD_TUNNEL_ID 0x1\n#define HTTP_TUNNEL_RESPONSE_FIELD_CAPS 0x2\n#define HTTP_TUNNEL_RESPONSE_FIELD_SOH_REQ 0x4\n#define HTTP_TUNNEL_RESPONSE_FIELD_CONSENT_MSG 0x10", "/* HTTP capability type enumeration. */\n#define HTTP_CAPABILITY_TYPE_QUAR_SOH 0x1\n#define HTTP_CAPABILITY_IDLE_TIMEOUT 0x2\n#define HTTP_CAPABILITY_MESSAGING_CONSENT_SIGN 0x4\n#define HTTP_CAPABILITY_MESSAGING_SERVICE_MSG 0x8\n#define HTTP_CAPABILITY_REAUTH 0x10\n#define HTTP_CAPABILITY_UDP_TRANSPORT 0x20", "struct rdp_rdg\n{\n\trdpContext* context;\n\trdpSettings* settings;\n\tBOOL attached;\n\tBIO* frontBio;\n\trdpTls* tlsIn;\n\trdpTls* tlsOut;\n\trdpNtlm* ntlm;\n\tHttpContext* http;\n\tCRITICAL_SECTION writeSection;", "\tUUID guid;", "\tint state;\n\tUINT16 packetRemainingCount;\n\tUINT16 reserved1;\n\tint timeout;\n\tUINT16 extAuth;\n\tUINT16 reserved2;\n};", "enum\n{\n\tRDG_CLIENT_STATE_INITIAL,\n\tRDG_CLIENT_STATE_HANDSHAKE,\n\tRDG_CLIENT_STATE_TUNNEL_CREATE,\n\tRDG_CLIENT_STATE_TUNNEL_AUTHORIZE,\n\tRDG_CLIENT_STATE_CHANNEL_CREATE,\n\tRDG_CLIENT_STATE_OPENED,\n};", "#pragma pack(push, 1)", "typedef struct rdg_packet_header\n{\n\tUINT16 type;\n\tUINT16 reserved;\n\tUINT32 packetLength;\n} RdgPacketHeader;", "#pragma pack(pop)", "typedef struct\n{\n\tUINT32 code;\n\tconst char* name;\n} t_err_mapping;", "static const t_err_mapping tunnel_response_fields_present[] = {\n\t{ HTTP_TUNNEL_RESPONSE_FIELD_TUNNEL_ID, \"HTTP_TUNNEL_RESPONSE_FIELD_TUNNEL_ID\" },\n\t{ HTTP_TUNNEL_RESPONSE_FIELD_CAPS, \"HTTP_TUNNEL_RESPONSE_FIELD_CAPS\" },\n\t{ HTTP_TUNNEL_RESPONSE_FIELD_SOH_REQ, \"HTTP_TUNNEL_RESPONSE_FIELD_SOH_REQ\" },\n\t{ HTTP_TUNNEL_RESPONSE_FIELD_CONSENT_MSG, \"HTTP_TUNNEL_RESPONSE_FIELD_CONSENT_MSG\" }\n};", "static const t_err_mapping channel_response_fields_present[] = {\n\t{ HTTP_CHANNEL_RESPONSE_FIELD_CHANNELID, \"HTTP_CHANNEL_RESPONSE_FIELD_CHANNELID\" },\n\t{ HTTP_CHANNEL_RESPONSE_OPTIONAL, \"HTTP_CHANNEL_RESPONSE_OPTIONAL\" },\n\t{ HTTP_CHANNEL_RESPONSE_FIELD_UDPPORT, \"HTTP_CHANNEL_RESPONSE_FIELD_UDPPORT\" }\n};", "static const t_err_mapping tunnel_authorization_response_fields_present[] = {\n\t{ HTTP_TUNNEL_AUTH_RESPONSE_FIELD_REDIR_FLAGS, \"HTTP_TUNNEL_AUTH_RESPONSE_FIELD_REDIR_FLAGS\" },\n\t{ HTTP_TUNNEL_AUTH_RESPONSE_FIELD_IDLE_TIMEOUT,\n\t \"HTTP_TUNNEL_AUTH_RESPONSE_FIELD_IDLE_TIMEOUT\" },\n\t{ HTTP_TUNNEL_AUTH_RESPONSE_FIELD_SOH_RESPONSE,\n\t \"HTTP_TUNNEL_AUTH_RESPONSE_FIELD_SOH_RESPONSE\" }\n};", "static const t_err_mapping extended_auth[] = {\n\t{ HTTP_EXTENDED_AUTH_NONE, \"HTTP_EXTENDED_AUTH_NONE\" },\n\t{ HTTP_EXTENDED_AUTH_SC, \"HTTP_EXTENDED_AUTH_SC\" },\n\t{ HTTP_EXTENDED_AUTH_PAA, \"HTTP_EXTENDED_AUTH_PAA\" },\n\t{ HTTP_EXTENDED_AUTH_SSPI_NTLM, \"HTTP_EXTENDED_AUTH_SSPI_NTLM\" }\n};", "static const char* fields_present_to_string(UINT16 fieldsPresent, const t_err_mapping* map,\n size_t elements)\n{\n\tsize_t x = 0;\n\tstatic char buffer[1024] = { 0 };\n\tchar fields[12];\n\tmemset(buffer, 0, sizeof(buffer));", "\tfor (x = 0; x < elements; x++)\n\t{\n\t\tif (buffer[0] != '\\0')\n\t\t\tstrcat(buffer, \"|\");", "\t\tif ((map[x].code & fieldsPresent) != 0)\n\t\t\tstrcat(buffer, map[x].name);\n\t}", "\tsprintf_s(fields, ARRAYSIZE(fields), \" [%04\" PRIx16 \"]\", fieldsPresent);\n\tstrcat(buffer, fields);\n\treturn buffer;\n}", "static const char* channel_response_fields_present_to_string(UINT16 fieldsPresent)\n{\n\treturn fields_present_to_string(fieldsPresent, channel_response_fields_present,\n\t ARRAYSIZE(channel_response_fields_present));\n}", "static const char* tunnel_response_fields_present_to_string(UINT16 fieldsPresent)\n{\n\treturn fields_present_to_string(fieldsPresent, tunnel_response_fields_present,\n\t ARRAYSIZE(tunnel_response_fields_present));\n}", "static const char* tunnel_authorization_response_fields_present_to_string(UINT16 fieldsPresent)\n{\n\treturn fields_present_to_string(fieldsPresent, tunnel_authorization_response_fields_present,\n\t ARRAYSIZE(tunnel_authorization_response_fields_present));\n}", "static const char* extended_auth_to_string(UINT16 auth)\n{\n\tif (auth == HTTP_EXTENDED_AUTH_NONE)\n\t\treturn \"HTTP_EXTENDED_AUTH_NONE [0x0000]\";", "\treturn fields_present_to_string(auth, extended_auth, ARRAYSIZE(extended_auth));\n}", "static BOOL rdg_write_packet(rdpRdg* rdg, wStream* sPacket)\n{\n\tsize_t s;\n\tint status;\n\twStream* sChunk;\n\tchar chunkSize[11];\n\tsprintf_s(chunkSize, sizeof(chunkSize), \"%\" PRIXz \"\\r\\n\", Stream_Length(sPacket));\n\tsChunk = Stream_New(NULL, strnlen(chunkSize, sizeof(chunkSize)) + Stream_Length(sPacket) + 2);", "\tif (!sChunk)\n\t\treturn FALSE;", "\tStream_Write(sChunk, chunkSize, strnlen(chunkSize, sizeof(chunkSize)));\n\tStream_Write(sChunk, Stream_Buffer(sPacket), Stream_Length(sPacket));\n\tStream_Write(sChunk, \"\\r\\n\", 2);\n\tStream_SealLength(sChunk);\n\ts = Stream_Length(sChunk);", "\tif (s > INT_MAX)\n\t\treturn FALSE;", "\tstatus = tls_write_all(rdg->tlsIn, Stream_Buffer(sChunk), (int)s);\n\tStream_Free(sChunk, TRUE);", "\tif (status < 0)\n\t\treturn FALSE;", "\treturn TRUE;\n}", "static BOOL rdg_read_all(rdpTls* tls, BYTE* buffer, int size)\n{\n\tint status;\n\tint readCount = 0;\n\tBYTE* pBuffer = buffer;", "\twhile (readCount < size)\n\t{\n\t\tstatus = BIO_read(tls->bio, pBuffer, size - readCount);", "\t\tif (status <= 0)\n\t\t{\n\t\t\tif (!BIO_should_retry(tls->bio))\n\t\t\t\treturn FALSE;", "\t\t\tcontinue;\n\t\t}", "\t\treadCount += status;\n\t\tpBuffer += status;\n\t}", "\treturn TRUE;\n}", "static wStream* rdg_receive_packet(rdpRdg* rdg)\n{\n\twStream* s;\n\tconst size_t header = sizeof(RdgPacketHeader);\n\tsize_t packetLength;\n\tassert(header <= INT_MAX);\n\ts = Stream_New(NULL, 1024);", "\tif (!s)\n\t\treturn NULL;", "\tif (!rdg_read_all(rdg->tlsOut, Stream_Buffer(s), header))\n\t{\n\t\tStream_Free(s, TRUE);\n\t\treturn NULL;\n\t}", "\tStream_Seek(s, 4);\n\tStream_Read_UINT32(s, packetLength);\n", "\tif ((packetLength > INT_MAX) || !Stream_EnsureCapacity(s, packetLength) ||\n\t (packetLength < header))", "\t{\n\t\tStream_Free(s, TRUE);\n\t\treturn NULL;\n\t}", "\tif (!rdg_read_all(rdg->tlsOut, Stream_Buffer(s) + header, (int)packetLength - (int)header))\n\t{\n\t\tStream_Free(s, TRUE);\n\t\treturn NULL;\n\t}", "\tStream_SetLength(s, packetLength);\n\treturn s;\n}", "static BOOL rdg_send_handshake(rdpRdg* rdg)\n{\n\twStream* s;\n\tBOOL status;\n\ts = Stream_New(NULL, 14);", "\tif (!s)\n\t\treturn FALSE;", "\tStream_Write_UINT16(s, PKT_TYPE_HANDSHAKE_REQUEST); /* Type (2 bytes) */\n\tStream_Write_UINT16(s, 0); /* Reserved (2 bytes) */\n\tStream_Write_UINT32(s, 14); /* PacketLength (4 bytes) */\n\tStream_Write_UINT8(s, 1); /* VersionMajor (1 byte) */\n\tStream_Write_UINT8(s, 0); /* VersionMinor (1 byte) */\n\tStream_Write_UINT16(s, 0); /* ClientVersion (2 bytes), must be 0 */\n\tStream_Write_UINT16(s, rdg->extAuth); /* ExtendedAuthentication (2 bytes) */\n\tStream_SealLength(s);\n\tstatus = rdg_write_packet(rdg, s);\n\tStream_Free(s, TRUE);", "\tif (status)\n\t{\n\t\trdg->state = RDG_CLIENT_STATE_HANDSHAKE;\n\t}", "\treturn status;\n}", "static BOOL rdg_send_tunnel_request(rdpRdg* rdg)\n{\n\twStream* s;\n\tBOOL status;\n\tUINT32 packetSize = 16;\n\tUINT16 fieldsPresent = 0;\n\tWCHAR* PAACookie = NULL;\n\tint PAACookieLen = 0;", "\tif (rdg->extAuth == HTTP_EXTENDED_AUTH_PAA)\n\t{\n\t\tPAACookieLen =\n\t\t ConvertToUnicode(CP_UTF8, 0, rdg->settings->GatewayAccessToken, -1, &PAACookie, 0);", "\t\tif (!PAACookie || (PAACookieLen < 0) || (PAACookieLen > UINT16_MAX / 2))\n\t\t{\n\t\t\tfree(PAACookie);\n\t\t\treturn FALSE;\n\t\t}", "\t\tpacketSize += 2 + (UINT32)PAACookieLen * sizeof(WCHAR);\n\t\tfieldsPresent = HTTP_TUNNEL_PACKET_FIELD_PAA_COOKIE;\n\t}", "\ts = Stream_New(NULL, packetSize);", "\tif (!s)\n\t{\n\t\tfree(PAACookie);\n\t\treturn FALSE;\n\t}", "\tStream_Write_UINT16(s, PKT_TYPE_TUNNEL_CREATE); /* Type (2 bytes) */\n\tStream_Write_UINT16(s, 0); /* Reserved (2 bytes) */\n\tStream_Write_UINT32(s, packetSize); /* PacketLength (4 bytes) */\n\tStream_Write_UINT32(s, HTTP_CAPABILITY_TYPE_QUAR_SOH); /* CapabilityFlags (4 bytes) */\n\tStream_Write_UINT16(s, fieldsPresent); /* FieldsPresent (2 bytes) */\n\tStream_Write_UINT16(s, 0); /* Reserved (2 bytes), must be 0 */", "\tif (PAACookie)\n\t{\n\t\tStream_Write_UINT16(s, (UINT16)PAACookieLen * 2); /* PAA cookie string length */\n\t\tStream_Write_UTF16_String(s, PAACookie, (size_t)PAACookieLen);\n\t}", "\tStream_SealLength(s);\n\tstatus = rdg_write_packet(rdg, s);\n\tStream_Free(s, TRUE);\n\tfree(PAACookie);", "\tif (status)\n\t{\n\t\trdg->state = RDG_CLIENT_STATE_TUNNEL_CREATE;\n\t}", "\treturn status;\n}", "static BOOL rdg_send_tunnel_authorization(rdpRdg* rdg)\n{\n\twStream* s;\n\tBOOL status;\n\tWCHAR* clientName = NULL;\n\tUINT32 packetSize;\n\tint clientNameLen =\n\t ConvertToUnicode(CP_UTF8, 0, rdg->settings->ClientHostname, -1, &clientName, 0);", "\tif (!clientName || (clientNameLen < 0) || (clientNameLen > UINT16_MAX / 2))\n\t{\n\t\tfree(clientName);\n\t\treturn FALSE;\n\t}", "\tpacketSize = 12 + (UINT32)clientNameLen * sizeof(WCHAR);\n\ts = Stream_New(NULL, packetSize);", "\tif (!s)\n\t{\n\t\tfree(clientName);\n\t\treturn FALSE;\n\t}", "\tStream_Write_UINT16(s, PKT_TYPE_TUNNEL_AUTH); /* Type (2 bytes) */\n\tStream_Write_UINT16(s, 0); /* Reserved (2 bytes) */\n\tStream_Write_UINT32(s, packetSize); /* PacketLength (4 bytes) */\n\tStream_Write_UINT16(s, 0); /* FieldsPresent (2 bytes) */\n\tStream_Write_UINT16(s, (UINT16)clientNameLen * 2); /* Client name string length */\n\tStream_Write_UTF16_String(s, clientName, (size_t)clientNameLen);\n\tStream_SealLength(s);\n\tstatus = rdg_write_packet(rdg, s);\n\tStream_Free(s, TRUE);\n\tfree(clientName);", "\tif (status)\n\t{\n\t\trdg->state = RDG_CLIENT_STATE_TUNNEL_AUTHORIZE;\n\t}", "\treturn status;\n}", "static BOOL rdg_send_channel_create(rdpRdg* rdg)\n{\n\twStream* s = NULL;\n\tBOOL status = FALSE;\n\tWCHAR* serverName = NULL;\n\tint serverNameLen =\n\t ConvertToUnicode(CP_UTF8, 0, rdg->settings->ServerHostname, -1, &serverName, 0);\n\tUINT32 packetSize = 16 + ((UINT32)serverNameLen) * 2;", "\tif ((serverNameLen < 0) || (serverNameLen > UINT16_MAX / 2))\n\t\tgoto fail;", "\ts = Stream_New(NULL, packetSize);", "\tif (!s)\n\t\tgoto fail;", "\tStream_Write_UINT16(s, PKT_TYPE_CHANNEL_CREATE); /* Type (2 bytes) */\n\tStream_Write_UINT16(s, 0); /* Reserved (2 bytes) */\n\tStream_Write_UINT32(s, packetSize); /* PacketLength (4 bytes) */\n\tStream_Write_UINT8(s, 1); /* Number of resources. (1 byte) */\n\tStream_Write_UINT8(s, 0); /* Number of alternative resources (1 byte) */\n\tStream_Write_UINT16(s, (UINT16)rdg->settings->ServerPort); /* Resource port (2 bytes) */\n\tStream_Write_UINT16(s, 3); /* Protocol number (2 bytes) */\n\tStream_Write_UINT16(s, (UINT16)serverNameLen * 2);\n\tStream_Write_UTF16_String(s, serverName, (size_t)serverNameLen);\n\tStream_SealLength(s);\n\tstatus = rdg_write_packet(rdg, s);\nfail:\n\tfree(serverName);\n\tStream_Free(s, TRUE);", "\tif (status)\n\t\trdg->state = RDG_CLIENT_STATE_CHANNEL_CREATE;", "\treturn status;\n}", "static BOOL rdg_set_ntlm_auth_header(rdpNtlm* ntlm, HttpRequest* request)\n{\n\tconst SecBuffer* ntlmToken = ntlm_client_get_output_buffer(ntlm);\n\tchar* base64NtlmToken = NULL;", "\tif (ntlmToken)\n\t{\n\t\tif (ntlmToken->cbBuffer > INT_MAX)\n\t\t\treturn FALSE;", "\t\tbase64NtlmToken = crypto_base64_encode(ntlmToken->pvBuffer, (int)ntlmToken->cbBuffer);\n\t}", "\tif (base64NtlmToken)\n\t{\n\t\tBOOL rc = http_request_set_auth_scheme(request, \"NTLM\") &&\n\t\t http_request_set_auth_param(request, base64NtlmToken);\n\t\tfree(base64NtlmToken);", "\t\tif (!rc)\n\t\t\treturn FALSE;\n\t}", "\treturn TRUE;\n}", "static wStream* rdg_build_http_request(rdpRdg* rdg, const char* method,\n const char* transferEncoding)\n{\n\twStream* s = NULL;\n\tHttpRequest* request = NULL;\n\tconst char* uri;", "\tif (!rdg || !method)\n\t\treturn NULL;", "\turi = http_context_get_uri(rdg->http);\n\trequest = http_request_new();", "\tif (!request)\n\t\treturn NULL;", "\tif (!http_request_set_method(request, method) || !http_request_set_uri(request, uri))\n\t\tgoto out;", "\tif (rdg->ntlm)\n\t{\n\t\tif (!rdg_set_ntlm_auth_header(rdg->ntlm, request))\n\t\t\tgoto out;\n\t}", "\tif (transferEncoding)\n\t{\n\t\thttp_request_set_transfer_encoding(request, transferEncoding);\n\t}", "\ts = http_request_write(rdg->http, request);\nout:\n\thttp_request_free(request);", "\tif (s)\n\t\tStream_SealLength(s);", "\treturn s;\n}", "static BOOL rdg_handle_ntlm_challenge(rdpNtlm* ntlm, HttpResponse* response)\n{\n\tBOOL continueNeeded = FALSE;\n\tsize_t len;\n\tconst char* token64 = NULL;\n\tint ntlmTokenLength = 0;\n\tBYTE* ntlmTokenData = NULL;\n\tlong StatusCode;", "\tif (!ntlm || !response)\n\t\treturn FALSE;", "\tStatusCode = http_response_get_status_code(response);", "\tif (StatusCode != HTTP_STATUS_DENIED)\n\t{\n\t\tWLog_DBG(TAG, \"Unexpected NTLM challenge HTTP status: %ld\", StatusCode);\n\t\treturn FALSE;\n\t}", "\ttoken64 = http_response_get_auth_token(response, \"NTLM\");", "\tif (!token64)\n\t\treturn FALSE;", "\tlen = strlen(token64);", "\tif (len > INT_MAX)\n\t\treturn FALSE;", "\tcrypto_base64_decode(token64, (int)len, &ntlmTokenData, &ntlmTokenLength);", "\tif (ntlmTokenLength < 0)\n\t{\n\t\tfree(ntlmTokenData);\n\t\treturn FALSE;\n\t}", "\tif (ntlmTokenData && ntlmTokenLength)\n\t{\n\t\tif (!ntlm_client_set_input_buffer(ntlm, FALSE, ntlmTokenData, (size_t)ntlmTokenLength))\n\t\t\treturn FALSE;\n\t}", "\tif (!ntlm_authenticate(ntlm, &continueNeeded))\n\t\treturn FALSE;", "\tif (continueNeeded)\n\t\treturn FALSE;", "\treturn TRUE;\n}", "static BOOL rdg_skip_seed_payload(rdpTls* tls, SSIZE_T lastResponseLength)\n{\n\tBYTE seed_payload[10];\n\tconst size_t size = sizeof(seed_payload);", "\tassert(size < SSIZE_MAX);", "\t/* Per [MS-TSGU] 3.3.5.1 step 4, after final OK response RDG server sends\n\t * random \"seed\" payload of limited size. In practice it's 10 bytes.\n\t */\n\tif (lastResponseLength < (SSIZE_T)size)\n\t{\n\t\tif (!rdg_read_all(tls, seed_payload, size - lastResponseLength))\n\t\t{\n\t\t\treturn FALSE;\n\t\t}\n\t}", "\treturn TRUE;\n}", "static BOOL rdg_process_handshake_response(rdpRdg* rdg, wStream* s)\n{\n\tUINT32 errorCode;\n\tUINT16 serverVersion, extendedAuth;\n\tBYTE verMajor, verMinor;\n\tconst char* error;\n\tWLog_DBG(TAG, \"Handshake response received\");", "\tif (rdg->state != RDG_CLIENT_STATE_HANDSHAKE)\n\t{\n\t\treturn FALSE;\n\t}", "\tif (Stream_GetRemainingLength(s) < 10)\n\t{\n\t\tWLog_ERR(TAG, \"[%s] Short packet %\" PRIuz \", expected 10\", __FUNCTION__,\n\t\t Stream_GetRemainingLength(s));\n\t\treturn FALSE;\n\t}", "\tStream_Read_UINT32(s, errorCode);\n\tStream_Read_UINT8(s, verMajor);\n\tStream_Read_UINT8(s, verMinor);\n\tStream_Read_UINT16(s, serverVersion);\n\tStream_Read_UINT16(s, extendedAuth);\n\terror = rpc_error_to_string(errorCode);\n\tWLog_DBG(TAG,\n\t \"errorCode=%s, verMajor=%\" PRId8 \", verMinor=%\" PRId8 \", serverVersion=%\" PRId16\n\t \", extendedAuth=%s\",\n\t error, verMajor, verMinor, serverVersion, extended_auth_to_string(extendedAuth));", "\tif (FAILED(errorCode))\n\t{\n\t\tWLog_ERR(TAG, \"Handshake error %s\", error);\n\t\tfreerdp_set_last_error_log(rdg->context, errorCode);\n\t\treturn FALSE;\n\t}", "\treturn rdg_send_tunnel_request(rdg);\n}", "static BOOL rdg_process_tunnel_response(rdpRdg* rdg, wStream* s)\n{\n\tUINT16 serverVersion, fieldsPresent;\n\tUINT32 errorCode;\n\tconst char* error;\n\tWLog_DBG(TAG, \"Tunnel response received\");", "\tif (rdg->state != RDG_CLIENT_STATE_TUNNEL_CREATE)\n\t{\n\t\treturn FALSE;\n\t}", "\tif (Stream_GetRemainingLength(s) < 10)\n\t{\n\t\tWLog_ERR(TAG, \"[%s] Short packet %\" PRIuz \", expected 10\", __FUNCTION__,\n\t\t Stream_GetRemainingLength(s));\n\t\treturn FALSE;\n\t}", "\tStream_Read_UINT16(s, serverVersion);\n\tStream_Read_UINT32(s, errorCode);\n\tStream_Read_UINT16(s, fieldsPresent);\n\tStream_Seek_UINT16(s); /* reserved */\n\terror = rpc_error_to_string(errorCode);\n\tWLog_DBG(TAG, \"serverVersion=%\" PRId16 \", errorCode=%s, fieldsPresent=%s\", serverVersion, error,\n\t tunnel_response_fields_present_to_string(fieldsPresent));", "\tif (FAILED(errorCode))\n\t{\n\t\tWLog_ERR(TAG, \"Tunnel creation error %s\", error);\n\t\tfreerdp_set_last_error_log(rdg->context, errorCode);\n\t\treturn FALSE;\n\t}", "\treturn rdg_send_tunnel_authorization(rdg);\n}", "static BOOL rdg_process_tunnel_authorization_response(rdpRdg* rdg, wStream* s)\n{\n\tUINT32 errorCode;\n\tUINT16 fieldsPresent;\n\tconst char* error;\n\tWLog_DBG(TAG, \"Tunnel authorization received\");", "\tif (rdg->state != RDG_CLIENT_STATE_TUNNEL_AUTHORIZE)\n\t{\n\t\treturn FALSE;\n\t}", "\tif (Stream_GetRemainingLength(s) < 8)\n\t{\n\t\tWLog_ERR(TAG, \"[%s] Short packet %\" PRIuz \", expected 8\", __FUNCTION__,\n\t\t Stream_GetRemainingLength(s));\n\t\treturn FALSE;\n\t}", "\tStream_Read_UINT32(s, errorCode);\n\tStream_Read_UINT16(s, fieldsPresent);\n\tStream_Seek_UINT16(s); /* reserved */\n\terror = rpc_error_to_string(errorCode);\n\tWLog_DBG(TAG, \"errorCode=%s, fieldsPresent=%s\", error,\n\t tunnel_authorization_response_fields_present_to_string(fieldsPresent));", "\tif (FAILED(errorCode))\n\t{\n\t\tWLog_ERR(TAG, \"Tunnel authorization error %s\", error);\n\t\tfreerdp_set_last_error_log(rdg->context, errorCode);\n\t\treturn FALSE;\n\t}", "\treturn rdg_send_channel_create(rdg);\n}", "static BOOL rdg_process_channel_response(rdpRdg* rdg, wStream* s)\n{\n\tUINT16 fieldsPresent;\n\tUINT32 errorCode;\n\tconst char* error;\n\tWLog_DBG(TAG, \"Channel response received\");", "\tif (rdg->state != RDG_CLIENT_STATE_CHANNEL_CREATE)\n\t{\n\t\treturn FALSE;\n\t}", "\tif (Stream_GetRemainingLength(s) < 8)\n\t{\n\t\tWLog_ERR(TAG, \"[%s] Short packet %\" PRIuz \", expected 8\", __FUNCTION__,\n\t\t Stream_GetRemainingLength(s));\n\t\treturn FALSE;\n\t}", "\tStream_Read_UINT32(s, errorCode);\n\tStream_Read_UINT16(s, fieldsPresent);\n\tStream_Seek_UINT16(s); /* reserved */\n\terror = rpc_error_to_string(errorCode);\n\tWLog_DBG(TAG, \"channel response errorCode=%s, fieldsPresent=%s\", error,\n\t channel_response_fields_present_to_string(fieldsPresent));", "\tif (FAILED(errorCode))\n\t{\n\t\tWLog_ERR(TAG, \"channel response errorCode=%s, fieldsPresent=%s\", error,\n\t\t channel_response_fields_present_to_string(fieldsPresent));\n\t\tfreerdp_set_last_error_log(rdg->context, errorCode);\n\t\treturn FALSE;\n\t}", "\trdg->state = RDG_CLIENT_STATE_OPENED;\n\treturn TRUE;\n}", "static BOOL rdg_process_packet(rdpRdg* rdg, wStream* s)\n{\n\tBOOL status = TRUE;\n\tUINT16 type;\n\tUINT32 packetLength;\n\tStream_SetPosition(s, 0);", "\tif (Stream_GetRemainingLength(s) < 8)\n\t{\n\t\tWLog_ERR(TAG, \"[%s] Short packet %\" PRIuz \", expected 8\", __FUNCTION__,\n\t\t Stream_GetRemainingLength(s));\n\t\treturn FALSE;\n\t}", "\tStream_Read_UINT16(s, type);\n\tStream_Seek_UINT16(s); /* reserved */\n\tStream_Read_UINT32(s, packetLength);", "\tif (Stream_Length(s) < packetLength)\n\t{\n\t\tWLog_ERR(TAG, \"[%s] Short packet %\" PRIuz \", expected %\" PRIuz, __FUNCTION__,\n\t\t Stream_Length(s), packetLength);\n\t\treturn FALSE;\n\t}", "\tswitch (type)\n\t{\n\t\tcase PKT_TYPE_HANDSHAKE_RESPONSE:\n\t\t\tstatus = rdg_process_handshake_response(rdg, s);\n\t\t\tbreak;", "\t\tcase PKT_TYPE_TUNNEL_RESPONSE:\n\t\t\tstatus = rdg_process_tunnel_response(rdg, s);\n\t\t\tbreak;", "\t\tcase PKT_TYPE_TUNNEL_AUTH_RESPONSE:\n\t\t\tstatus = rdg_process_tunnel_authorization_response(rdg, s);\n\t\t\tbreak;", "\t\tcase PKT_TYPE_CHANNEL_RESPONSE:\n\t\t\tstatus = rdg_process_channel_response(rdg, s);\n\t\t\tbreak;", "\t\tcase PKT_TYPE_DATA:\n\t\t\tWLog_ERR(TAG, \"[%s] Unexpected packet type DATA\", __FUNCTION__);\n\t\t\treturn FALSE;\n\t}", "\treturn status;\n}", "DWORD rdg_get_event_handles(rdpRdg* rdg, HANDLE* events, DWORD count)\n{\n\tDWORD nCount = 0;\n\tassert(rdg != NULL);", "\tif (rdg->tlsOut && rdg->tlsOut->bio)\n\t{\n\t\tif (events && (nCount < count))\n\t\t{\n\t\t\tBIO_get_event(rdg->tlsOut->bio, &events[nCount]);\n\t\t\tnCount++;\n\t\t}\n\t\telse\n\t\t\treturn 0;\n\t}", "\tif (rdg->tlsIn && rdg->tlsIn->bio)\n\t{\n\t\tif (events && (nCount < count))\n\t\t{\n\t\t\tBIO_get_event(rdg->tlsIn->bio, &events[nCount]);\n\t\t\tnCount++;\n\t\t}\n\t\telse\n\t\t\treturn 0;\n\t}", "\treturn nCount;\n}", "static BOOL rdg_get_gateway_credentials(rdpContext* context)\n{\n\trdpSettings* settings = context->settings;\n\tfreerdp* instance = context->instance;", "\tif (!settings->GatewayPassword || !settings->GatewayUsername ||\n\t !strlen(settings->GatewayPassword) || !strlen(settings->GatewayUsername))\n\t{\n\t\tif (freerdp_shall_disconnect(instance))\n\t\t\treturn FALSE;", "\t\tif (!instance->GatewayAuthenticate)\n\t\t{\n\t\t\tfreerdp_set_last_error_log(context, FREERDP_ERROR_CONNECT_NO_OR_MISSING_CREDENTIALS);\n\t\t\treturn FALSE;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tBOOL proceed =\n\t\t\t instance->GatewayAuthenticate(instance, &settings->GatewayUsername,\n\t\t\t &settings->GatewayPassword, &settings->GatewayDomain);", "\t\t\tif (!proceed)\n\t\t\t{\n\t\t\t\tfreerdp_set_last_error_log(context,\n\t\t\t\t FREERDP_ERROR_CONNECT_NO_OR_MISSING_CREDENTIALS);\n\t\t\t\treturn FALSE;\n\t\t\t}", "\t\t\tif (settings->GatewayUseSameCredentials)\n\t\t\t{\n\t\t\t\tif (settings->GatewayUsername)\n\t\t\t\t{\n\t\t\t\t\tfree(settings->Username);", "\t\t\t\t\tif (!(settings->Username = _strdup(settings->GatewayUsername)))\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t}", "\t\t\t\tif (settings->GatewayDomain)\n\t\t\t\t{\n\t\t\t\t\tfree(settings->Domain);", "\t\t\t\t\tif (!(settings->Domain = _strdup(settings->GatewayDomain)))\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t}", "\t\t\t\tif (settings->GatewayPassword)\n\t\t\t\t{\n\t\t\t\t\tfree(settings->Password);", "\t\t\t\t\tif (!(settings->Password = _strdup(settings->GatewayPassword)))\n\t\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "\treturn TRUE;\n}", "static BOOL rdg_ntlm_init(rdpRdg* rdg, rdpTls* tls)\n{\n\tBOOL continueNeeded = FALSE;\n\trdpContext* context = rdg->context;\n\trdpSettings* settings = context->settings;\n\trdg->ntlm = ntlm_new();", "\tif (!rdg->ntlm)\n\t\treturn FALSE;", "\tif (!rdg_get_gateway_credentials(context))\n\t\treturn FALSE;", "\tif (!ntlm_client_init(rdg->ntlm, TRUE, settings->GatewayUsername, settings->GatewayDomain,\n\t settings->GatewayPassword, tls->Bindings))\n\t\treturn FALSE;", "\tif (!ntlm_client_make_spn(rdg->ntlm, _T(\"HTTP\"), settings->GatewayHostname))\n\t\treturn FALSE;", "\tif (!ntlm_authenticate(rdg->ntlm, &continueNeeded))\n\t\treturn FALSE;", "\treturn continueNeeded;\n}", "static BOOL rdg_send_http_request(rdpRdg* rdg, rdpTls* tls, const char* method,\n const char* transferEncoding)\n{\n\tsize_t sz;\n\twStream* s = NULL;\n\tint status = -1;\n\ts = rdg_build_http_request(rdg, method, transferEncoding);", "\tif (!s)\n\t\treturn FALSE;", "\tsz = Stream_Length(s);", "\tif (sz <= INT_MAX)\n\t\tstatus = tls_write_all(tls, Stream_Buffer(s), (int)sz);", "\tStream_Free(s, TRUE);\n\treturn (status >= 0);\n}", "static BOOL rdg_tls_connect(rdpRdg* rdg, rdpTls* tls, const char* peerAddress, int timeout)\n{\n\tint sockfd = 0;\n\tlong status = 0;\n\tBIO* socketBio = NULL;\n\tBIO* bufferedBio = NULL;\n\trdpSettings* settings = rdg->settings;\n\tconst char* peerHostname = settings->GatewayHostname;\n\tUINT16 peerPort = (UINT16)settings->GatewayPort;\n\tconst char *proxyUsername, *proxyPassword;\n\tBOOL isProxyConnection =\n\t proxy_prepare(settings, &peerHostname, &peerPort, &proxyUsername, &proxyPassword);", "\tif (settings->GatewayPort > UINT16_MAX)\n\t\treturn FALSE;", "\tsockfd = freerdp_tcp_connect(rdg->context, settings, peerAddress ? peerAddress : peerHostname,\n\t peerPort, timeout);", "\tif (sockfd < 0)\n\t{\n\t\treturn FALSE;\n\t}", "\tsocketBio = BIO_new(BIO_s_simple_socket());", "\tif (!socketBio)\n\t{\n\t\tclosesocket((SOCKET)sockfd);\n\t\treturn FALSE;\n\t}", "\tBIO_set_fd(socketBio, sockfd, BIO_CLOSE);\n\tbufferedBio = BIO_new(BIO_s_buffered_socket());", "\tif (!bufferedBio)\n\t{\n\t\tBIO_free_all(socketBio);\n\t\treturn FALSE;\n\t}", "\tbufferedBio = BIO_push(bufferedBio, socketBio);\n\tstatus = BIO_set_nonblock(bufferedBio, TRUE);", "\tif (isProxyConnection)\n\t{\n\t\tif (!proxy_connect(settings, bufferedBio, proxyUsername, proxyPassword,\n\t\t settings->GatewayHostname, (UINT16)settings->GatewayPort))\n\t\t{\n\t\t\tBIO_free_all(bufferedBio);\n\t\t\treturn FALSE;\n\t\t}\n\t}", "\tif (!status)\n\t{\n\t\tBIO_free_all(bufferedBio);\n\t\treturn FALSE;\n\t}", "\ttls->hostname = settings->GatewayHostname;\n\ttls->port = (int)settings->GatewayPort;\n\ttls->isGatewayTransport = TRUE;\n\tstatus = tls_connect(tls, bufferedBio);\n\tif (status < 1)\n\t{\n\t\trdpContext* context = rdg->context;\n\t\tif (status < 0)\n\t\t{\n\t\t\tfreerdp_set_last_error_if_not(context, FREERDP_ERROR_TLS_CONNECT_FAILED);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfreerdp_set_last_error_if_not(context, FREERDP_ERROR_CONNECT_CANCELLED);\n\t\t}", "\t\treturn FALSE;\n\t}\n\treturn (status >= 1);\n}", "static BOOL rdg_establish_data_connection(rdpRdg* rdg, rdpTls* tls, const char* method,\n const char* peerAddress, int timeout, BOOL* rpcFallback)\n{\n\tHttpResponse* response = NULL;\n\tlong statusCode;\n\tSSIZE_T bodyLength;\n\tlong StatusCode;", "\tif (!rdg_tls_connect(rdg, tls, peerAddress, timeout))\n\t\treturn FALSE;", "\tif (rdg->extAuth == HTTP_EXTENDED_AUTH_NONE)\n\t{\n\t\tif (!rdg_ntlm_init(rdg, tls))\n\t\t\treturn FALSE;", "\t\tif (!rdg_send_http_request(rdg, tls, method, NULL))\n\t\t\treturn FALSE;", "\t\tresponse = http_response_recv(tls, TRUE);", "\t\tif (!response)\n\t\t\treturn FALSE;", "\t\tStatusCode = http_response_get_status_code(response);", "\t\tswitch (StatusCode)\n\t\t{\n\t\t\tcase HTTP_STATUS_NOT_FOUND:\n\t\t\t{\n\t\t\t\tWLog_INFO(TAG, \"RD Gateway does not support HTTP transport.\");", "\t\t\t\tif (rpcFallback)\n\t\t\t\t\t*rpcFallback = TRUE;", "\t\t\t\thttp_response_free(response);\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}", "\t\tif (!rdg_handle_ntlm_challenge(rdg->ntlm, response))\n\t\t{\n\t\t\thttp_response_free(response);\n\t\t\treturn FALSE;\n\t\t}", "\t\thttp_response_free(response);\n\t}", "\tif (!rdg_send_http_request(rdg, tls, method, NULL))\n\t\treturn FALSE;", "\tntlm_free(rdg->ntlm);\n\trdg->ntlm = NULL;\n\tresponse = http_response_recv(tls, TRUE);", "\tif (!response)\n\t\treturn FALSE;", "\tstatusCode = http_response_get_status_code(response);\n\tbodyLength = http_response_get_body_length(response);\n\thttp_response_free(response);\n\tWLog_DBG(TAG, \"%s authorization result: %d\", method, statusCode);", "\tswitch (statusCode)\n\t{\n\t\tcase HTTP_STATUS_OK:\n\t\t\tbreak;\n\t\tcase HTTP_STATUS_DENIED:\n\t\t\tfreerdp_set_last_error_log(rdg->context, FREERDP_ERROR_CONNECT_ACCESS_DENIED);\n\t\t\treturn FALSE;\n\t\tdefault:\n\t\t\treturn FALSE;\n\t}", "\tif (strcmp(method, \"RDG_OUT_DATA\") == 0)\n\t{\n\t\tif (!rdg_skip_seed_payload(tls, bodyLength))\n\t\t\treturn FALSE;\n\t}\n\telse\n\t{\n\t\tif (!rdg_send_http_request(rdg, tls, method, \"chunked\"))\n\t\t\treturn FALSE;\n\t}", "\treturn TRUE;\n}", "static BOOL rdg_tunnel_connect(rdpRdg* rdg)\n{\n\tBOOL status;\n\twStream* s;\n\trdg_send_handshake(rdg);", "\twhile (rdg->state < RDG_CLIENT_STATE_OPENED)\n\t{\n\t\tstatus = FALSE;\n\t\ts = rdg_receive_packet(rdg);", "\t\tif (s)\n\t\t{\n\t\t\tstatus = rdg_process_packet(rdg, s);\n\t\t\tStream_Free(s, TRUE);\n\t\t}", "\t\tif (!status)\n\t\t{\n\t\t\trdg->context->rdp->transport->layer = TRANSPORT_LAYER_CLOSED;\n\t\t\treturn FALSE;\n\t\t}\n\t}", "\treturn TRUE;\n}", "BOOL rdg_connect(rdpRdg* rdg, int timeout, BOOL* rpcFallback)\n{\n\tBOOL status;\n\tSOCKET outConnSocket = 0;\n\tchar* peerAddress = NULL;\n\tassert(rdg != NULL);\n\tstatus =\n\t rdg_establish_data_connection(rdg, rdg->tlsOut, \"RDG_OUT_DATA\", NULL, timeout, rpcFallback);", "\tif (status)\n\t{\n\t\t/* Establish IN connection with the same peer/server as OUT connection,\n\t\t * even when server hostname resolves to different IP addresses.\n\t\t */\n\t\tBIO_get_socket(rdg->tlsOut->underlying, &outConnSocket);\n\t\tpeerAddress = freerdp_tcp_get_peer_address(outConnSocket);\n\t\tstatus = rdg_establish_data_connection(rdg, rdg->tlsIn, \"RDG_IN_DATA\", peerAddress, timeout,\n\t\t NULL);\n\t\tfree(peerAddress);\n\t}", "\tif (!status)\n\t{\n\t\trdg->context->rdp->transport->layer = TRANSPORT_LAYER_CLOSED;\n\t\treturn FALSE;\n\t}", "\tstatus = rdg_tunnel_connect(rdg);", "\tif (!status)\n\t\treturn FALSE;", "\treturn TRUE;\n}", "static int rdg_write_data_packet(rdpRdg* rdg, const BYTE* buf, int isize)\n{\n\tint status;\n\tsize_t s;\n\twStream* sChunk;\n\tsize_t size = (size_t)isize;\n\tsize_t packetSize = size + 10;\n\tchar chunkSize[11];", "\tif ((isize < 0) || (isize > UINT16_MAX))\n\t\treturn -1;", "\tif (size < 1)\n\t\treturn 0;", "\tsprintf_s(chunkSize, sizeof(chunkSize), \"%\" PRIxz \"\\r\\n\", packetSize);\n\tsChunk = Stream_New(NULL, strnlen(chunkSize, sizeof(chunkSize)) + packetSize + 2);", "\tif (!sChunk)\n\t\treturn -1;", "\tStream_Write(sChunk, chunkSize, strnlen(chunkSize, sizeof(chunkSize)));\n\tStream_Write_UINT16(sChunk, PKT_TYPE_DATA); /* Type */\n\tStream_Write_UINT16(sChunk, 0); /* Reserved */\n\tStream_Write_UINT32(sChunk, (UINT32)packetSize); /* Packet length */\n\tStream_Write_UINT16(sChunk, (UINT16)size); /* Data size */\n\tStream_Write(sChunk, buf, size); /* Data */\n\tStream_Write(sChunk, \"\\r\\n\", 2);\n\tStream_SealLength(sChunk);\n\ts = Stream_Length(sChunk);", "\tif (s > INT_MAX)\n\t\treturn -1;", "\tstatus = tls_write_all(rdg->tlsIn, Stream_Buffer(sChunk), (int)s);\n\tStream_Free(sChunk, TRUE);", "\tif (status < 0)\n\t\treturn -1;", "\treturn (int)size;\n}", "static BOOL rdg_process_close_packet(rdpRdg* rdg)\n{\n\tint status = -1;\n\tsize_t s;\n\twStream* sChunk;\n\tUINT32 packetSize = 12;\n\tchar chunkSize[11];\n\tint chunkLen = sprintf_s(chunkSize, sizeof(chunkSize), \"%\" PRIx32 \"\\r\\n\", packetSize);", "\tif (chunkLen < 0)\n\t\treturn FALSE;", "\tsChunk = Stream_New(NULL, (size_t)chunkLen + packetSize + 2);", "\tif (!sChunk)\n\t\treturn FALSE;", "\tStream_Write(sChunk, chunkSize, (size_t)chunkLen);\n\tStream_Write_UINT16(sChunk, PKT_TYPE_CLOSE_CHANNEL_RESPONSE); /* Type */\n\tStream_Write_UINT16(sChunk, 0); /* Reserved */\n\tStream_Write_UINT32(sChunk, packetSize); /* Packet length */\n\tStream_Write_UINT32(sChunk, 0); /* Status code */\n\tStream_Write(sChunk, \"\\r\\n\", 2);\n\tStream_SealLength(sChunk);\n\ts = Stream_Length(sChunk);", "\tif (s <= INT_MAX)\n\t\tstatus = tls_write_all(rdg->tlsIn, Stream_Buffer(sChunk), (int)s);", "\tStream_Free(sChunk, TRUE);\n\treturn (status < 0 ? FALSE : TRUE);\n}", "static BOOL rdg_process_keep_alive_packet(rdpRdg* rdg)\n{\n\tint status = -1;\n\tsize_t s;\n\twStream* sChunk;\n\tsize_t packetSize = 8;\n\tchar chunkSize[11];\n\tint chunkLen = sprintf_s(chunkSize, sizeof(chunkSize), \"%\" PRIxz \"\\r\\n\", packetSize);", "\tif ((chunkLen < 0) || (packetSize > UINT32_MAX))\n\t\treturn FALSE;", "\tsChunk = Stream_New(NULL, (size_t)chunkLen + packetSize + 2);", "\tif (!sChunk)\n\t\treturn FALSE;", "\tStream_Write(sChunk, chunkSize, (size_t)chunkLen);\n\tStream_Write_UINT16(sChunk, PKT_TYPE_KEEPALIVE); /* Type */\n\tStream_Write_UINT16(sChunk, 0); /* Reserved */\n\tStream_Write_UINT32(sChunk, (UINT32)packetSize); /* Packet length */\n\tStream_Write(sChunk, \"\\r\\n\", 2);\n\tStream_SealLength(sChunk);\n\ts = Stream_Length(sChunk);", "\tif (s <= INT_MAX)\n\t\tstatus = tls_write_all(rdg->tlsIn, Stream_Buffer(sChunk), (int)s);", "\tStream_Free(sChunk, TRUE);\n\treturn (status < 0 ? FALSE : TRUE);\n}", "static BOOL rdg_process_unknown_packet(rdpRdg* rdg, int type)\n{\n\tWINPR_UNUSED(rdg);\n\tWINPR_UNUSED(type);\n\tWLog_WARN(TAG, \"Unknown Control Packet received: %X\", type);\n\treturn TRUE;\n}", "static BOOL rdg_process_control_packet(rdpRdg* rdg, int type, size_t packetLength)\n{\n\twStream* s = NULL;\n\tsize_t readCount = 0;\n\tint status;\n\tsize_t payloadSize = packetLength - sizeof(RdgPacketHeader);", "\tif (packetLength < sizeof(RdgPacketHeader))\n\t\treturn FALSE;", "\tassert(sizeof(RdgPacketHeader) < INT_MAX);", "\tif (payloadSize)\n\t{\n\t\ts = Stream_New(NULL, payloadSize);", "\t\tif (!s)\n\t\t\treturn FALSE;", "\t\twhile (readCount < payloadSize)\n\t\t{\n\t\t\tstatus =\n\t\t\t BIO_read(rdg->tlsOut->bio, Stream_Pointer(s), (int)payloadSize - (int)readCount);", "\t\t\tif (status <= 0)\n\t\t\t{\n\t\t\t\tif (!BIO_should_retry(rdg->tlsOut->bio))\n\t\t\t\t{\n\t\t\t\t\tStream_Free(s, TRUE);\n\t\t\t\t\treturn FALSE;\n\t\t\t\t}", "\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tStream_Seek(s, (size_t)status);\n\t\t\treadCount += (size_t)status;", "\t\t\tif (readCount > INT_MAX)\n\t\t\t{\n\t\t\t\tStream_Free(s, TRUE);\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t}\n\t}", "\tswitch (type)\n\t{\n\t\tcase PKT_TYPE_CLOSE_CHANNEL:\n\t\t\tEnterCriticalSection(&rdg->writeSection);\n\t\t\tstatus = rdg_process_close_packet(rdg);\n\t\t\tLeaveCriticalSection(&rdg->writeSection);\n\t\t\tbreak;", "\t\tcase PKT_TYPE_KEEPALIVE:\n\t\t\tEnterCriticalSection(&rdg->writeSection);\n\t\t\tstatus = rdg_process_keep_alive_packet(rdg);\n\t\t\tLeaveCriticalSection(&rdg->writeSection);\n\t\t\tbreak;", "\t\tdefault:\n\t\t\tstatus = rdg_process_unknown_packet(rdg, type);\n\t\t\tbreak;\n\t}", "\tStream_Free(s, TRUE);\n\treturn status;\n}", "static int rdg_read_data_packet(rdpRdg* rdg, BYTE* buffer, int size)\n{\n\tRdgPacketHeader header;\n\tsize_t readCount = 0;\n\tint readSize;\n\tint status;", "\tif (!rdg->packetRemainingCount)\n\t{\n\t\tassert(sizeof(RdgPacketHeader) < INT_MAX);", "\t\twhile (readCount < sizeof(RdgPacketHeader))\n\t\t{\n\t\t\tstatus = BIO_read(rdg->tlsOut->bio, (BYTE*)(&header) + readCount,\n\t\t\t (int)sizeof(RdgPacketHeader) - (int)readCount);", "\t\t\tif (status <= 0)\n\t\t\t{\n\t\t\t\tif (!BIO_should_retry(rdg->tlsOut->bio))\n\t\t\t\t\treturn -1;", "\t\t\t\tif (!readCount)\n\t\t\t\t\treturn 0;", "\t\t\t\tBIO_wait_read(rdg->tlsOut->bio, 50);\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\treadCount += (size_t)status;", "\t\t\tif (readCount > INT_MAX)\n\t\t\t\treturn -1;\n\t\t}", "\t\tif (header.type != PKT_TYPE_DATA)\n\t\t{\n\t\t\tstatus = rdg_process_control_packet(rdg, header.type, header.packetLength);", "\t\t\tif (!status)\n\t\t\t\treturn -1;", "\t\t\treturn 0;\n\t\t}", "\t\treadCount = 0;", "\t\twhile (readCount < 2)\n\t\t{\n\t\t\tstatus = BIO_read(rdg->tlsOut->bio, (BYTE*)(&rdg->packetRemainingCount) + readCount,\n\t\t\t 2 - (int)readCount);", "\t\t\tif (status < 0)\n\t\t\t{\n\t\t\t\tif (!BIO_should_retry(rdg->tlsOut->bio))\n\t\t\t\t\treturn -1;", "\t\t\t\tBIO_wait_read(rdg->tlsOut->bio, 50);\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\treadCount += (size_t)status;\n\t\t}\n\t}", "\treadSize = (rdg->packetRemainingCount < size ? rdg->packetRemainingCount : size);\n\tstatus = BIO_read(rdg->tlsOut->bio, buffer, readSize);", "\tif (status <= 0)\n\t{\n\t\tif (!BIO_should_retry(rdg->tlsOut->bio))\n\t\t{\n\t\t\treturn -1;\n\t\t}", "\t\treturn 0;\n\t}", "\trdg->packetRemainingCount -= status;\n\treturn status;\n}", "static int rdg_bio_write(BIO* bio, const char* buf, int num)\n{\n\tint status;\n\trdpRdg* rdg = (rdpRdg*)BIO_get_data(bio);\n\tBIO_clear_flags(bio, BIO_FLAGS_WRITE);\n\tEnterCriticalSection(&rdg->writeSection);\n\tstatus = rdg_write_data_packet(rdg, (const BYTE*)buf, num);\n\tLeaveCriticalSection(&rdg->writeSection);", "\tif (status < 0)\n\t{\n\t\tBIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);\n\t\treturn -1;\n\t}\n\telse if (status < num)\n\t{\n\t\tBIO_set_flags(bio, BIO_FLAGS_WRITE);\n\t\tWSASetLastError(WSAEWOULDBLOCK);\n\t}\n\telse\n\t{\n\t\tBIO_set_flags(bio, BIO_FLAGS_WRITE);\n\t}", "\treturn status;\n}", "static int rdg_bio_read(BIO* bio, char* buf, int size)\n{\n\tint status;\n\trdpRdg* rdg = (rdpRdg*)BIO_get_data(bio);\n\tstatus = rdg_read_data_packet(rdg, (BYTE*)buf, size);", "\tif (status < 0)\n\t{\n\t\tBIO_clear_retry_flags(bio);\n\t\treturn -1;\n\t}\n\telse if (status == 0)\n\t{\n\t\tBIO_set_retry_read(bio);\n\t\tWSASetLastError(WSAEWOULDBLOCK);\n\t\treturn -1;\n\t}\n\telse\n\t{\n\t\tBIO_set_flags(bio, BIO_FLAGS_READ);\n\t}", "\treturn status;\n}", "static int rdg_bio_puts(BIO* bio, const char* str)\n{\n\tWINPR_UNUSED(bio);\n\tWINPR_UNUSED(str);\n\treturn -2;\n}", "static int rdg_bio_gets(BIO* bio, char* str, int size)\n{\n\tWINPR_UNUSED(bio);\n\tWINPR_UNUSED(str);\n\tWINPR_UNUSED(size);\n\treturn -2;\n}", "static long rdg_bio_ctrl(BIO* bio, int cmd, long arg1, void* arg2)\n{\n\tlong status = -1;\n\trdpRdg* rdg = (rdpRdg*)BIO_get_data(bio);\n\trdpTls* tlsOut = rdg->tlsOut;\n\trdpTls* tlsIn = rdg->tlsIn;", "\tif (cmd == BIO_CTRL_FLUSH)\n\t{\n\t\t(void)BIO_flush(tlsOut->bio);\n\t\t(void)BIO_flush(tlsIn->bio);\n\t\tstatus = 1;\n\t}\n\telse if (cmd == BIO_C_SET_NONBLOCK)\n\t{\n\t\tstatus = 1;\n\t}\n\telse if (cmd == BIO_C_READ_BLOCKED)\n\t{\n\t\tBIO* bio = tlsOut->bio;\n\t\tstatus = BIO_read_blocked(bio);\n\t}\n\telse if (cmd == BIO_C_WRITE_BLOCKED)\n\t{\n\t\tBIO* bio = tlsIn->bio;\n\t\tstatus = BIO_write_blocked(bio);\n\t}\n\telse if (cmd == BIO_C_WAIT_READ)\n\t{\n\t\tint timeout = (int)arg1;\n\t\tBIO* bio = tlsOut->bio;", "\t\tif (BIO_read_blocked(bio))\n\t\t\treturn BIO_wait_read(bio, timeout);\n\t\telse if (BIO_write_blocked(bio))\n\t\t\treturn BIO_wait_write(bio, timeout);\n\t\telse\n\t\t\tstatus = 1;\n\t}\n\telse if (cmd == BIO_C_WAIT_WRITE)\n\t{\n\t\tint timeout = (int)arg1;\n\t\tBIO* bio = tlsIn->bio;", "\t\tif (BIO_write_blocked(bio))\n\t\t\tstatus = BIO_wait_write(bio, timeout);\n\t\telse if (BIO_read_blocked(bio))\n\t\t\tstatus = BIO_wait_read(bio, timeout);\n\t\telse\n\t\t\tstatus = 1;\n\t}\n\telse if (cmd == BIO_C_GET_EVENT || cmd == BIO_C_GET_FD)\n\t{\n\t\t/*\n\t\t * A note about BIO_C_GET_FD:\n\t\t * Even if two FDs are part of RDG, only one FD can be returned here.\n\t\t *\n\t\t * In FreeRDP, BIO FDs are only used for polling, so it is safe to use the outgoing FD only\n\t\t *\n\t\t * See issue #3602\n\t\t */\n\t\tstatus = BIO_ctrl(tlsOut->bio, cmd, arg1, arg2);\n\t}", "\treturn status;\n}", "static int rdg_bio_new(BIO* bio)\n{\n\tBIO_set_init(bio, 1);\n\tBIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY);\n\treturn 1;\n}", "static int rdg_bio_free(BIO* bio)\n{\n\tWINPR_UNUSED(bio);\n\treturn 1;\n}", "static BIO_METHOD* BIO_s_rdg(void)\n{\n\tstatic BIO_METHOD* bio_methods = NULL;", "\tif (bio_methods == NULL)\n\t{\n\t\tif (!(bio_methods = BIO_meth_new(BIO_TYPE_TSG, \"RDGateway\")))\n\t\t\treturn NULL;", "\t\tBIO_meth_set_write(bio_methods, rdg_bio_write);\n\t\tBIO_meth_set_read(bio_methods, rdg_bio_read);\n\t\tBIO_meth_set_puts(bio_methods, rdg_bio_puts);\n\t\tBIO_meth_set_gets(bio_methods, rdg_bio_gets);\n\t\tBIO_meth_set_ctrl(bio_methods, rdg_bio_ctrl);\n\t\tBIO_meth_set_create(bio_methods, rdg_bio_new);\n\t\tBIO_meth_set_destroy(bio_methods, rdg_bio_free);\n\t}", "\treturn bio_methods;\n}", "rdpRdg* rdg_new(rdpContext* context)\n{\n\trdpRdg* rdg;\n\tRPC_CSTR stringUuid;\n\tchar bracedUuid[40];\n\tRPC_STATUS rpcStatus;", "\tif (!context)\n\t\treturn NULL;", "\trdg = (rdpRdg*)calloc(1, sizeof(rdpRdg));", "\tif (rdg)\n\t{\n\t\trdg->state = RDG_CLIENT_STATE_INITIAL;\n\t\trdg->context = context;\n\t\trdg->settings = rdg->context->settings;\n\t\trdg->extAuth = HTTP_EXTENDED_AUTH_NONE;", "\t\tif (rdg->settings->GatewayAccessToken)\n\t\t\trdg->extAuth = HTTP_EXTENDED_AUTH_PAA;", "\t\tUuidCreate(&rdg->guid);\n\t\trpcStatus = UuidToStringA(&rdg->guid, &stringUuid);", "\t\tif (rpcStatus == RPC_S_OUT_OF_MEMORY)\n\t\t\tgoto rdg_alloc_error;", "\t\tsprintf_s(bracedUuid, sizeof(bracedUuid), \"{%s}\", stringUuid);\n\t\tRpcStringFreeA(&stringUuid);\n\t\trdg->tlsOut = tls_new(rdg->settings);", "\t\tif (!rdg->tlsOut)\n\t\t\tgoto rdg_alloc_error;", "\t\trdg->tlsIn = tls_new(rdg->settings);", "\t\tif (!rdg->tlsIn)\n\t\t\tgoto rdg_alloc_error;", "\t\trdg->http = http_context_new();", "\t\tif (!rdg->http)\n\t\t\tgoto rdg_alloc_error;", "\t\tif (!http_context_set_uri(rdg->http, \"/remoteDesktopGateway/\") ||\n\t\t !http_context_set_accept(rdg->http, \"*/*\") ||\n\t\t !http_context_set_cache_control(rdg->http, \"no-cache\") ||\n\t\t !http_context_set_pragma(rdg->http, \"no-cache\") ||\n\t\t !http_context_set_connection(rdg->http, \"Keep-Alive\") ||\n\t\t !http_context_set_user_agent(rdg->http, \"MS-RDGateway/1.0\") ||\n\t\t !http_context_set_host(rdg->http, rdg->settings->GatewayHostname) ||\n\t\t !http_context_set_rdg_connection_id(rdg->http, bracedUuid))\n\t\t{\n\t\t\tgoto rdg_alloc_error;\n\t\t}", "\t\tif (rdg->extAuth != HTTP_EXTENDED_AUTH_NONE)\n\t\t{\n\t\t\tswitch (rdg->extAuth)\n\t\t\t{\n\t\t\t\tcase HTTP_EXTENDED_AUTH_PAA:\n\t\t\t\t\tif (!http_context_set_rdg_auth_scheme(rdg->http, \"PAA\"))\n\t\t\t\t\t\tgoto rdg_alloc_error;", "\t\t\t\t\tbreak;", "\t\t\t\tdefault:\n\t\t\t\t\tWLog_DBG(TAG, \"RDG extended authentication method %d not supported\",\n\t\t\t\t\t rdg->extAuth);\n\t\t\t}\n\t\t}", "\t\trdg->frontBio = BIO_new(BIO_s_rdg());", "\t\tif (!rdg->frontBio)\n\t\t\tgoto rdg_alloc_error;", "\t\tBIO_set_data(rdg->frontBio, rdg);\n\t\tInitializeCriticalSection(&rdg->writeSection);\n\t}", "\treturn rdg;\nrdg_alloc_error:\n\trdg_free(rdg);\n\treturn NULL;\n}", "void rdg_free(rdpRdg* rdg)\n{\n\tif (!rdg)\n\t\treturn;", "\ttls_free(rdg->tlsOut);\n\ttls_free(rdg->tlsIn);\n\thttp_context_free(rdg->http);\n\tntlm_free(rdg->ntlm);", "\tif (!rdg->attached)\n\t\tBIO_free_all(rdg->frontBio);", "\tDeleteCriticalSection(&rdg->writeSection);\n\tfree(rdg);\n}", "BIO* rdg_get_front_bio_and_take_ownership(rdpRdg* rdg)\n{\n\tif (!rdg)\n\t\treturn NULL;", "\trdg->attached = TRUE;\n\treturn rdg->frontBio;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [357, 496, 447, 322, 308, 1001], "buggy_code_start_loc": [333, 480, 447, 145, 307, 94], "filenames": ["channels/drive/client/drive_main.c", "channels/printer/client/printer_main.c", "channels/rdpei/client/rdpei_main.c", "channels/serial/client/serial_main.c", "libfreerdp/core/gateway/rdg.c", "libfreerdp/core/nego.c"], "fixing_code_end_loc": [361, 502, 451, 327, 309, 1013], "fixing_code_start_loc": [334, 481, 448, 145, 307, 94], "message": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:freerdp:freerdp:*:*:*:*:*:*:*:*", "matchCriteriaId": "5C5F8D57-1D22-42B4-9E08-9131F7BE8FA5", "versionEndExcluding": "2.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "B620311B-34A3-48A6-82DF-6F078D7A4493", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0."}, {"lang": "es", "value": "En FreeRDP versiones anteriores a 2.1.0, se presenta una lectura fuera de l\u00edmite en las funciones de irp (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). Esto ha sido corregido en la versi\u00f3n 2.1.0."}], "evaluatorComment": null, "id": "CVE-2020-11089", "lastModified": "2022-07-19T11:52:15.420", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:L/I:L/A:L", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 2.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-05-29T20:15:11.017", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2020-07/msg00080.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/795842f4096501fcefc1a7f535ccc8132feb31d7"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/security/advisories/GHSA-hfc7-c5gv-8c2h"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-125"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, "type": "CWE-125"}
320
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * FreeRDP: A Remote Desktop Protocol Implementation\n * RDP Protocol Security Negotiation\n *\n * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com>\n * Copyright 2014 Norbert Federa <norbert.federa@thincast.com>\n * Copyright 2015 Thincast Technologies GmbH\n * Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */", "#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif", "#include <winpr/crt.h>", "#include <freerdp/log.h>", "#include \"tpkt.h\"", "#include \"nego.h\"", "#include \"transport.h\"", "#define TAG FREERDP_TAG(\"core.nego\")", "struct rdp_nego\n{\n\tUINT16 port;\n\tUINT32 flags;\n\tconst char* hostname;\n\tchar* cookie;\n\tBYTE* RoutingToken;\n\tDWORD RoutingTokenLength;\n\tBOOL SendPreconnectionPdu;\n\tUINT32 PreconnectionId;\n\tchar* PreconnectionBlob;", "\tNEGO_STATE state;\n\tBOOL TcpConnected;\n\tBOOL SecurityConnected;\n\tUINT32 CookieMaxLength;", "\tBOOL sendNegoData;\n\tUINT32 SelectedProtocol;\n\tUINT32 RequestedProtocols;\n\tBOOL NegotiateSecurityLayer;\n\tBOOL EnabledProtocols[16];\n\tBOOL RestrictedAdminModeRequired;\n\tBOOL GatewayEnabled;\n\tBOOL GatewayBypassLocal;", "\trdpTransport* transport;\n};", "static const char* nego_state_string(NEGO_STATE state)\n{\n\tstatic const char* const NEGO_STATE_STRINGS[] = { \"NEGO_STATE_INITIAL\", \"NEGO_STATE_EXT\",\n\t\t \"NEGO_STATE_NLA\", \"NEGO_STATE_TLS\",\n\t\t \"NEGO_STATE_RDP\", \"NEGO_STATE_FAIL\",\n\t\t \"NEGO_STATE_FINAL\", \"NEGO_STATE_INVALID\" };\n\tif (state >= ARRAYSIZE(NEGO_STATE_STRINGS))\n\t\treturn NEGO_STATE_STRINGS[ARRAYSIZE(NEGO_STATE_STRINGS) - 1];\n\treturn NEGO_STATE_STRINGS[state];\n}", "static const char* protocol_security_string(UINT32 security)\n{\n\tstatic const char* PROTOCOL_SECURITY_STRINGS[] = { \"RDP\", \"TLS\", \"NLA\", \"UNK\", \"UNK\",\n\t\t \"UNK\", \"UNK\", \"UNK\", \"EXT\", \"UNK\" };\n\tif (security >= ARRAYSIZE(PROTOCOL_SECURITY_STRINGS))\n\t\treturn PROTOCOL_SECURITY_STRINGS[ARRAYSIZE(PROTOCOL_SECURITY_STRINGS) - 1];\n\treturn PROTOCOL_SECURITY_STRINGS[security];\n}", "static BOOL nego_transport_connect(rdpNego* nego);\nstatic BOOL nego_transport_disconnect(rdpNego* nego);\nstatic BOOL nego_security_connect(rdpNego* nego);\nstatic BOOL nego_send_preconnection_pdu(rdpNego* nego);\nstatic BOOL nego_recv_response(rdpNego* nego);\nstatic void nego_send(rdpNego* nego);", "static void nego_process_negotiation_request(rdpNego* nego, wStream* s);\nstatic void nego_process_negotiation_response(rdpNego* nego, wStream* s);\nstatic void nego_process_negotiation_failure(rdpNego* nego, wStream* s);", "\n/**\n * Negotiate protocol security and connect.\n * @param nego\n * @return\n */", "BOOL nego_connect(rdpNego* nego)\n{\n\trdpSettings* settings = nego->transport->settings;", "\tif (nego->state == NEGO_STATE_INITIAL)\n\t{\n\t\tif (nego->EnabledProtocols[PROTOCOL_HYBRID_EX])\n\t\t{\n\t\t\tnego->state = NEGO_STATE_EXT;\n\t\t}\n\t\telse if (nego->EnabledProtocols[PROTOCOL_HYBRID])\n\t\t{\n\t\t\tnego->state = NEGO_STATE_NLA;\n\t\t}\n\t\telse if (nego->EnabledProtocols[PROTOCOL_SSL])\n\t\t{\n\t\t\tnego->state = NEGO_STATE_TLS;\n\t\t}\n\t\telse if (nego->EnabledProtocols[PROTOCOL_RDP])\n\t\t{\n\t\t\tnego->state = NEGO_STATE_RDP;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tWLog_ERR(TAG, \"No security protocol is enabled\");\n\t\t\tnego->state = NEGO_STATE_FAIL;\n\t\t\treturn FALSE;\n\t\t}", "\t\tif (!nego->NegotiateSecurityLayer)\n\t\t{\n\t\t\tWLog_DBG(TAG, \"Security Layer Negotiation is disabled\");\n\t\t\t/* attempt only the highest enabled protocol (see nego_attempt_*) */\n\t\t\tnego->EnabledProtocols[PROTOCOL_HYBRID] = FALSE;\n\t\t\tnego->EnabledProtocols[PROTOCOL_SSL] = FALSE;\n\t\t\tnego->EnabledProtocols[PROTOCOL_RDP] = FALSE;\n\t\t\tnego->EnabledProtocols[PROTOCOL_HYBRID_EX] = FALSE;", "\t\t\tif (nego->state == NEGO_STATE_EXT)\n\t\t\t{\n\t\t\t\tnego->EnabledProtocols[PROTOCOL_HYBRID_EX] = TRUE;\n\t\t\t\tnego->EnabledProtocols[PROTOCOL_HYBRID] = TRUE;\n\t\t\t\tnego->SelectedProtocol = PROTOCOL_HYBRID_EX;\n\t\t\t}\n\t\t\telse if (nego->state == NEGO_STATE_NLA)\n\t\t\t{\n\t\t\t\tnego->EnabledProtocols[PROTOCOL_HYBRID] = TRUE;\n\t\t\t\tnego->SelectedProtocol = PROTOCOL_HYBRID;\n\t\t\t}\n\t\t\telse if (nego->state == NEGO_STATE_TLS)\n\t\t\t{\n\t\t\t\tnego->EnabledProtocols[PROTOCOL_SSL] = TRUE;\n\t\t\t\tnego->SelectedProtocol = PROTOCOL_SSL;\n\t\t\t}\n\t\t\telse if (nego->state == NEGO_STATE_RDP)\n\t\t\t{\n\t\t\t\tnego->EnabledProtocols[PROTOCOL_RDP] = TRUE;\n\t\t\t\tnego->SelectedProtocol = PROTOCOL_RDP;\n\t\t\t}\n\t\t}", "\t\tif (nego->SendPreconnectionPdu)\n\t\t{\n\t\t\tif (!nego_send_preconnection_pdu(nego))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"Failed to send preconnection pdu\");\n\t\t\t\tnego->state = NEGO_STATE_FINAL;\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t}\n\t}", "\tif (!nego->NegotiateSecurityLayer)\n\t{\n\t\tnego->state = NEGO_STATE_FINAL;\n\t}\n\telse\n\t{\n\t\tdo\n\t\t{\n\t\t\tWLog_DBG(TAG, \"state: %s\", nego_state_string(nego->state));\n\t\t\tnego_send(nego);", "\t\t\tif (nego->state == NEGO_STATE_FAIL)\n\t\t\t{\n\t\t\t\tif (freerdp_get_last_error(nego->transport->context) == FREERDP_ERROR_SUCCESS)\n\t\t\t\t\tWLog_ERR(TAG, \"Protocol Security Negotiation Failure\");", "\t\t\t\tnego->state = NEGO_STATE_FINAL;\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t} while (nego->state != NEGO_STATE_FINAL);\n\t}", "\tWLog_DBG(TAG, \"Negotiated %s security\", protocol_security_string(nego->SelectedProtocol));\n\t/* update settings with negotiated protocol security */\n\tsettings->RequestedProtocols = nego->RequestedProtocols;\n\tsettings->SelectedProtocol = nego->SelectedProtocol;\n\tsettings->NegotiationFlags = nego->flags;", "\tif (nego->SelectedProtocol == PROTOCOL_RDP)\n\t{\n\t\tsettings->UseRdpSecurityLayer = TRUE;", "\t\tif (!settings->EncryptionMethods)\n\t\t{\n\t\t\t/**\n\t\t\t * Advertise all supported encryption methods if the client\n\t\t\t * implementation did not set any security methods\n\t\t\t */\n\t\t\tsettings->EncryptionMethods = ENCRYPTION_METHOD_40BIT | ENCRYPTION_METHOD_56BIT |\n\t\t\t ENCRYPTION_METHOD_128BIT | ENCRYPTION_METHOD_FIPS;\n\t\t}\n\t}", "\t/* finally connect security layer (if not already done) */\n\tif (!nego_security_connect(nego))\n\t{\n\t\tWLog_DBG(TAG, \"Failed to connect with %s security\",\n\t\t protocol_security_string(nego->SelectedProtocol));\n\t\treturn FALSE;\n\t}", "\treturn TRUE;\n}", "BOOL nego_disconnect(rdpNego* nego)\n{\n\tnego->state = NEGO_STATE_INITIAL;\n\treturn nego_transport_disconnect(nego);\n}", "/* connect to selected security layer */\nBOOL nego_security_connect(rdpNego* nego)\n{\n\tif (!nego->TcpConnected)\n\t{\n\t\tnego->SecurityConnected = FALSE;\n\t}\n\telse if (!nego->SecurityConnected)\n\t{\n\t\tif (nego->SelectedProtocol == PROTOCOL_HYBRID)\n\t\t{\n\t\t\tWLog_DBG(TAG, \"nego_security_connect with PROTOCOL_HYBRID\");\n\t\t\tnego->SecurityConnected = transport_connect_nla(nego->transport);\n\t\t}\n\t\telse if (nego->SelectedProtocol == PROTOCOL_SSL)\n\t\t{\n\t\t\tWLog_DBG(TAG, \"nego_security_connect with PROTOCOL_SSL\");\n\t\t\tnego->SecurityConnected = transport_connect_tls(nego->transport);\n\t\t}\n\t\telse if (nego->SelectedProtocol == PROTOCOL_RDP)\n\t\t{\n\t\t\tWLog_DBG(TAG, \"nego_security_connect with PROTOCOL_RDP\");\n\t\t\tnego->SecurityConnected = transport_connect_rdp(nego->transport);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tWLog_ERR(TAG,\n\t\t\t \"cannot connect security layer because no protocol has been selected yet.\");\n\t\t}\n\t}", "\treturn nego->SecurityConnected;\n}", "/**\n * Connect TCP layer.\n * @param nego\n * @return\n */", "static BOOL nego_tcp_connect(rdpNego* nego)\n{\n\tif (!nego->TcpConnected)\n\t{\n\t\tif (nego->GatewayEnabled)\n\t\t{\n\t\t\tif (nego->GatewayBypassLocal)\n\t\t\t{\n\t\t\t\t/* Attempt a direct connection first, and then fallback to using the gateway */\n\t\t\t\tWLog_INFO(TAG,\n\t\t\t\t \"Detecting if host can be reached locally. - This might take some time.\");\n\t\t\t\tWLog_INFO(TAG, \"To disable auto detection use /gateway-usage-method:direct\");\n\t\t\t\ttransport_set_gateway_enabled(nego->transport, FALSE);\n\t\t\t\tnego->TcpConnected =\n\t\t\t\t transport_connect(nego->transport, nego->hostname, nego->port, 1);\n\t\t\t}", "\t\t\tif (!nego->TcpConnected)\n\t\t\t{\n\t\t\t\ttransport_set_gateway_enabled(nego->transport, TRUE);\n\t\t\t\tnego->TcpConnected =\n\t\t\t\t transport_connect(nego->transport, nego->hostname, nego->port, 15);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tnego->TcpConnected = transport_connect(nego->transport, nego->hostname, nego->port, 15);\n\t\t}\n\t}", "\treturn nego->TcpConnected;\n}", "/**\n * Connect TCP layer. For direct approach, connect security layer as well.\n * @param nego\n * @return\n */", "BOOL nego_transport_connect(rdpNego* nego)\n{\n\tif (!nego_tcp_connect(nego))\n\t\treturn FALSE;", "\tif (nego->TcpConnected && !nego->NegotiateSecurityLayer)\n\t\treturn nego_security_connect(nego);", "\treturn nego->TcpConnected;\n}", "/**\n * Disconnect TCP layer.\n * @param nego\n * @return\n */", "BOOL nego_transport_disconnect(rdpNego* nego)\n{\n\tif (nego->TcpConnected)\n\t\ttransport_disconnect(nego->transport);", "\tnego->TcpConnected = FALSE;\n\tnego->SecurityConnected = FALSE;\n\treturn TRUE;\n}", "/**\n * Send preconnection information if enabled.\n * @param nego\n * @return\n */", "BOOL nego_send_preconnection_pdu(rdpNego* nego)\n{\n\twStream* s;\n\tUINT32 cbSize;\n\tUINT16 cchPCB = 0;\n\tWCHAR* wszPCB = NULL;\n\tWLog_DBG(TAG, \"Sending preconnection PDU\");", "\tif (!nego_tcp_connect(nego))\n\t\treturn FALSE;", "\t/* it's easier to always send the version 2 PDU, and it's just 2 bytes overhead */\n\tcbSize = PRECONNECTION_PDU_V2_MIN_SIZE;", "\tif (nego->PreconnectionBlob)\n\t{\n\t\tcchPCB = (UINT16)ConvertToUnicode(CP_UTF8, 0, nego->PreconnectionBlob, -1, &wszPCB, 0);\n\t\tcchPCB += 1; /* zero-termination */\n\t\tcbSize += cchPCB * 2;\n\t}", "\ts = Stream_New(NULL, cbSize);", "\tif (!s)\n\t{\n\t\tfree(wszPCB);\n\t\tWLog_ERR(TAG, \"Stream_New failed!\");\n\t\treturn FALSE;\n\t}", "\tStream_Write_UINT32(s, cbSize); /* cbSize */\n\tStream_Write_UINT32(s, 0); /* Flags */\n\tStream_Write_UINT32(s, PRECONNECTION_PDU_V2); /* Version */\n\tStream_Write_UINT32(s, nego->PreconnectionId); /* Id */\n\tStream_Write_UINT16(s, cchPCB); /* cchPCB */", "\tif (wszPCB)\n\t{\n\t\tStream_Write(s, wszPCB, cchPCB * 2); /* wszPCB */\n\t\tfree(wszPCB);\n\t}", "\tStream_SealLength(s);", "\tif (transport_write(nego->transport, s) < 0)\n\t{\n\t\tStream_Free(s, TRUE);\n\t\treturn FALSE;\n\t}", "\tStream_Free(s, TRUE);\n\treturn TRUE;\n}", "/**\n * Attempt negotiating NLA + TLS extended security.\n * @param nego\n */", "static void nego_attempt_ext(rdpNego* nego)\n{\n\tnego->RequestedProtocols = PROTOCOL_HYBRID | PROTOCOL_SSL | PROTOCOL_HYBRID_EX;\n\tWLog_DBG(TAG, \"Attempting NLA extended security\");", "\tif (!nego_transport_connect(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}", "\tif (!nego_send_negotiation_request(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}", "\tif (!nego_recv_response(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}", "\tWLog_DBG(TAG, \"state: %s\", nego_state_string(nego->state));", "\tif (nego->state != NEGO_STATE_FINAL)\n\t{\n\t\tnego_transport_disconnect(nego);", "\t\tif (nego->EnabledProtocols[PROTOCOL_HYBRID])\n\t\t\tnego->state = NEGO_STATE_NLA;\n\t\telse if (nego->EnabledProtocols[PROTOCOL_SSL])\n\t\t\tnego->state = NEGO_STATE_TLS;\n\t\telse if (nego->EnabledProtocols[PROTOCOL_RDP])\n\t\t\tnego->state = NEGO_STATE_RDP;\n\t\telse\n\t\t\tnego->state = NEGO_STATE_FAIL;\n\t}\n}", "/**\n * Attempt negotiating NLA + TLS security.\n * @param nego\n */", "static void nego_attempt_nla(rdpNego* nego)\n{\n\tnego->RequestedProtocols = PROTOCOL_HYBRID | PROTOCOL_SSL;\n\tWLog_DBG(TAG, \"Attempting NLA security\");", "\tif (!nego_transport_connect(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}", "\tif (!nego_send_negotiation_request(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}", "\tif (!nego_recv_response(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}", "\tWLog_DBG(TAG, \"state: %s\", nego_state_string(nego->state));", "\tif (nego->state != NEGO_STATE_FINAL)\n\t{\n\t\tnego_transport_disconnect(nego);", "\t\tif (nego->EnabledProtocols[PROTOCOL_SSL])\n\t\t\tnego->state = NEGO_STATE_TLS;\n\t\telse if (nego->EnabledProtocols[PROTOCOL_RDP])\n\t\t\tnego->state = NEGO_STATE_RDP;\n\t\telse\n\t\t\tnego->state = NEGO_STATE_FAIL;\n\t}\n}", "/**\n * Attempt negotiating TLS security.\n * @param nego\n */", "static void nego_attempt_tls(rdpNego* nego)\n{\n\tnego->RequestedProtocols = PROTOCOL_SSL;\n\tWLog_DBG(TAG, \"Attempting TLS security\");", "\tif (!nego_transport_connect(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}", "\tif (!nego_send_negotiation_request(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}", "\tif (!nego_recv_response(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}", "\tif (nego->state != NEGO_STATE_FINAL)\n\t{\n\t\tnego_transport_disconnect(nego);", "\t\tif (nego->EnabledProtocols[PROTOCOL_RDP])\n\t\t\tnego->state = NEGO_STATE_RDP;\n\t\telse\n\t\t\tnego->state = NEGO_STATE_FAIL;\n\t}\n}", "/**\n * Attempt negotiating standard RDP security.\n * @param nego\n */", "static void nego_attempt_rdp(rdpNego* nego)\n{\n\tnego->RequestedProtocols = PROTOCOL_RDP;\n\tWLog_DBG(TAG, \"Attempting RDP security\");", "\tif (!nego_transport_connect(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}", "\tif (!nego_send_negotiation_request(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}", "\tif (!nego_recv_response(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}\n}", "/**\n * Wait to receive a negotiation response\n * @param nego\n */", "BOOL nego_recv_response(rdpNego* nego)\n{\n\tint status;\n\twStream* s;\n\ts = Stream_New(NULL, 1024);", "\tif (!s)\n\t{\n\t\tWLog_ERR(TAG, \"Stream_New failed!\");\n\t\treturn FALSE;\n\t}", "\tstatus = transport_read_pdu(nego->transport, s);", "\tif (status < 0)\n\t{\n\t\tStream_Free(s, TRUE);\n\t\treturn FALSE;\n\t}", "\tstatus = nego_recv(nego->transport, s, nego);\n\tStream_Free(s, TRUE);", "\tif (status < 0)\n\t\treturn FALSE;", "\treturn TRUE;\n}", "/**\n * Receive protocol security negotiation message.\\n\n * @msdn{cc240501}\n * @param transport transport\n * @param s stream\n * @param extra nego pointer\n */", "int nego_recv(rdpTransport* transport, wStream* s, void* extra)\n{\n\tBYTE li;\n\tBYTE type;\n\tUINT16 length;\n\trdpNego* nego = (rdpNego*)extra;", "\tif (!tpkt_read_header(s, &length))\n\t\treturn -1;", "\tif (!tpdu_read_connection_confirm(s, &li, length))\n\t\treturn -1;", "\tif (li > 6)\n\t{\n\t\t/* rdpNegData (optional) */\n\t\tStream_Read_UINT8(s, type); /* Type */", "\t\tswitch (type)\n\t\t{\n\t\t\tcase TYPE_RDP_NEG_RSP:", "\t\t\t\tnego_process_negotiation_response(nego, s);", "\t\t\t\tWLog_DBG(TAG, \"selected_protocol: %\" PRIu32 \"\", nego->SelectedProtocol);", "\t\t\t\t/* enhanced security selected ? */", "\t\t\t\tif (nego->SelectedProtocol)\n\t\t\t\t{\n\t\t\t\t\tif ((nego->SelectedProtocol == PROTOCOL_HYBRID) &&\n\t\t\t\t\t (!nego->EnabledProtocols[PROTOCOL_HYBRID]))\n\t\t\t\t\t{\n\t\t\t\t\t\tnego->state = NEGO_STATE_FAIL;\n\t\t\t\t\t}", "\t\t\t\t\tif ((nego->SelectedProtocol == PROTOCOL_SSL) &&\n\t\t\t\t\t (!nego->EnabledProtocols[PROTOCOL_SSL]))\n\t\t\t\t\t{\n\t\t\t\t\t\tnego->state = NEGO_STATE_FAIL;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (!nego->EnabledProtocols[PROTOCOL_RDP])\n\t\t\t\t{\n\t\t\t\t\tnego->state = NEGO_STATE_FAIL;\n\t\t\t\t}", "\t\t\t\tbreak;", "\t\t\tcase TYPE_RDP_NEG_FAILURE:", "\t\t\t\tnego_process_negotiation_failure(nego, s);", "\t\t\t\tbreak;\n\t\t}\n\t}\n\telse if (li == 6)\n\t{\n\t\tWLog_DBG(TAG, \"no rdpNegData\");", "\t\tif (!nego->EnabledProtocols[PROTOCOL_RDP])\n\t\t\tnego->state = NEGO_STATE_FAIL;\n\t\telse\n\t\t\tnego->state = NEGO_STATE_FINAL;\n\t}\n\telse\n\t{\n\t\tWLog_ERR(TAG, \"invalid negotiation response\");\n\t\tnego->state = NEGO_STATE_FAIL;\n\t}", "\tif (!tpkt_ensure_stream_consumed(s, length))\n\t\treturn -1;\n\treturn 0;\n}", "/**\n * Read optional routing token or cookie of X.224 Connection Request PDU.\n * @msdn{cc240470}\n * @param nego\n * @param s stream\n */", "static BOOL nego_read_request_token_or_cookie(rdpNego* nego, wStream* s)\n{\n\t/* routingToken and cookie are optional and mutually exclusive!\n\t *\n\t * routingToken (variable): An optional and variable-length routing\n\t * token (used for load balancing) terminated by a 0x0D0A two-byte\n\t * sequence: (check [MSFT-SDLBTS] for details!)\n\t * Cookie:[space]msts=[ip address].[port].[reserved][\\x0D\\x0A]\n\t *\n\t * cookie (variable): An optional and variable-length ANSI character\n\t * string terminated by a 0x0D0A two-byte sequence:\n\t * Cookie:[space]mstshash=[ANSISTRING][\\x0D\\x0A]\n\t */\n\tBYTE* str = NULL;\n\tUINT16 crlf = 0;\n\tsize_t pos, len;\n\tBOOL result = FALSE;\n\tBOOL isToken = FALSE;\n\tsize_t remain = Stream_GetRemainingLength(s);\n\tstr = Stream_Pointer(s);\n\tpos = Stream_GetPosition(s);", "\t/* minimum length for token is 15 */\n\tif (remain < 15)\n\t\treturn TRUE;", "\tif (memcmp(Stream_Pointer(s), \"Cookie: mstshash=\", 17) != 0)\n\t{\n\t\tisToken = TRUE;\n\t}\n\telse\n\t{\n\t\t/* not a token, minimum length for cookie is 19 */\n\t\tif (remain < 19)\n\t\t\treturn TRUE;", "\t\tStream_Seek(s, 17);\n\t}", "\twhile ((remain = Stream_GetRemainingLength(s)) >= 2)\n\t{\n\t\tStream_Read_UINT16(s, crlf);", "\t\tif (crlf == 0x0A0D)\n\t\t\tbreak;", "\t\tStream_Rewind(s, 1);\n\t}", "\tif (crlf == 0x0A0D)\n\t{\n\t\tStream_Rewind(s, 2);\n\t\tlen = Stream_GetPosition(s) - pos;\n\t\tremain = Stream_GetRemainingLength(s);\n\t\tStream_Write_UINT16(s, 0);", "\t\tif (strnlen((char*)str, len) == len)\n\t\t{\n\t\t\tif (isToken)\n\t\t\t\tresult = nego_set_routing_token(nego, str, len);\n\t\t\telse\n\t\t\t\tresult = nego_set_cookie(nego, (char*)str);\n\t\t}\n\t}", "\tif (!result)\n\t{\n\t\tStream_SetPosition(s, pos);\n\t\tWLog_ERR(TAG, \"invalid %s received\", isToken ? \"routing token\" : \"cookie\");\n\t}\n\telse\n\t{\n\t\tWLog_DBG(TAG, \"received %s [%s]\", isToken ? \"routing token\" : \"cookie\", str);\n\t}", "\treturn result;\n}", "/**\n * Read protocol security negotiation request message.\\n\n * @param nego\n * @param s stream\n */", "BOOL nego_read_request(rdpNego* nego, wStream* s)\n{\n\tBYTE li;\n\tBYTE type;\n\tUINT16 length;", "\tif (!tpkt_read_header(s, &length))\n\t\treturn FALSE;", "\tif (!tpdu_read_connection_request(s, &li, length))\n\t\treturn FALSE;", "\tif (li != Stream_GetRemainingLength(s) + 6)\n\t{\n\t\tWLog_ERR(TAG, \"Incorrect TPDU length indicator.\");\n\t\treturn FALSE;\n\t}", "\tif (!nego_read_request_token_or_cookie(nego, s))\n\t{\n\t\tWLog_ERR(TAG, \"Failed to parse routing token or cookie.\");\n\t\treturn FALSE;\n\t}", "\tif (Stream_GetRemainingLength(s) >= 8)\n\t{\n\t\t/* rdpNegData (optional) */\n\t\tStream_Read_UINT8(s, type); /* Type */", "\t\tif (type != TYPE_RDP_NEG_REQ)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"Incorrect negotiation request type %\" PRIu8 \"\", type);\n\t\t\treturn FALSE;\n\t\t}\n", "\t\tnego_process_negotiation_request(nego, s);", "\t}", "\treturn tpkt_ensure_stream_consumed(s, length);\n}", "/**\n * Send protocol security negotiation message.\n * @param nego\n */", "void nego_send(rdpNego* nego)\n{\n\tif (nego->state == NEGO_STATE_EXT)\n\t\tnego_attempt_ext(nego);\n\telse if (nego->state == NEGO_STATE_NLA)\n\t\tnego_attempt_nla(nego);\n\telse if (nego->state == NEGO_STATE_TLS)\n\t\tnego_attempt_tls(nego);\n\telse if (nego->state == NEGO_STATE_RDP)\n\t\tnego_attempt_rdp(nego);\n\telse\n\t\tWLog_ERR(TAG, \"invalid negotiation state for sending\");\n}", "/**\n * Send RDP Negotiation Request (RDP_NEG_REQ).\\n\n * @msdn{cc240500}\\n\n * @msdn{cc240470}\n * @param nego\n */", "BOOL nego_send_negotiation_request(rdpNego* nego)\n{\n\tBOOL rc = FALSE;\n\twStream* s;\n\tsize_t length;\n\tsize_t bm, em;\n\tBYTE flags = 0;\n\tsize_t cookie_length;\n\ts = Stream_New(NULL, 512);", "\tif (!s)\n\t{\n\t\tWLog_ERR(TAG, \"Stream_New failed!\");\n\t\treturn FALSE;\n\t}", "\tlength = TPDU_CONNECTION_REQUEST_LENGTH;\n\tbm = Stream_GetPosition(s);\n\tStream_Seek(s, length);", "\tif (nego->RoutingToken)\n\t{\n\t\tStream_Write(s, nego->RoutingToken, nego->RoutingTokenLength);", "\t\t/* Ensure Routing Token is correctly terminated - may already be present in string */", "\t\tif ((nego->RoutingTokenLength > 2) &&\n\t\t (nego->RoutingToken[nego->RoutingTokenLength - 2] == 0x0D) &&\n\t\t (nego->RoutingToken[nego->RoutingTokenLength - 1] == 0x0A))\n\t\t{\n\t\t\tWLog_DBG(TAG, \"Routing token looks correctly terminated - use verbatim\");\n\t\t\tlength += nego->RoutingTokenLength;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tWLog_DBG(TAG, \"Adding terminating CRLF to routing token\");\n\t\t\tStream_Write_UINT8(s, 0x0D); /* CR */\n\t\t\tStream_Write_UINT8(s, 0x0A); /* LF */\n\t\t\tlength += nego->RoutingTokenLength + 2;\n\t\t}\n\t}\n\telse if (nego->cookie)\n\t{\n\t\tcookie_length = strlen(nego->cookie);", "\t\tif (cookie_length > nego->CookieMaxLength)\n\t\t\tcookie_length = nego->CookieMaxLength;", "\t\tStream_Write(s, \"Cookie: mstshash=\", 17);\n\t\tStream_Write(s, (BYTE*)nego->cookie, cookie_length);\n\t\tStream_Write_UINT8(s, 0x0D); /* CR */\n\t\tStream_Write_UINT8(s, 0x0A); /* LF */\n\t\tlength += cookie_length + 19;\n\t}", "\tWLog_DBG(TAG, \"RequestedProtocols: %\" PRIu32 \"\", nego->RequestedProtocols);", "\tif ((nego->RequestedProtocols > PROTOCOL_RDP) || (nego->sendNegoData))\n\t{\n\t\t/* RDP_NEG_DATA must be present for TLS and NLA */\n\t\tif (nego->RestrictedAdminModeRequired)\n\t\t\tflags |= RESTRICTED_ADMIN_MODE_REQUIRED;", "\t\tStream_Write_UINT8(s, TYPE_RDP_NEG_REQ);\n\t\tStream_Write_UINT8(s, flags);\n\t\tStream_Write_UINT16(s, 8); /* RDP_NEG_DATA length (8) */\n\t\tStream_Write_UINT32(s, nego->RequestedProtocols); /* requestedProtocols */\n\t\tlength += 8;\n\t}", "\tif (length > UINT16_MAX)\n\t\tgoto fail;", "\tem = Stream_GetPosition(s);\n\tStream_SetPosition(s, bm);\n\ttpkt_write_header(s, (UINT16)length);\n\ttpdu_write_connection_request(s, (UINT16)length - 5);\n\tStream_SetPosition(s, em);\n\tStream_SealLength(s);\n\trc = (transport_write(nego->transport, s) >= 0);\nfail:\n\tStream_Free(s, TRUE);\n\treturn rc;\n}", "/**\n * Process Negotiation Request from Connection Request message.\n * @param nego\n * @param s\n */\n", "void nego_process_negotiation_request(rdpNego* nego, wStream* s)", "{\n\tBYTE flags;\n\tUINT16 length;", "", "\tStream_Read_UINT8(s, flags);\n\tStream_Read_UINT16(s, length);\n\tStream_Read_UINT32(s, nego->RequestedProtocols);\n\tWLog_DBG(TAG, \"RDP_NEG_REQ: RequestedProtocol: 0x%08\" PRIX32 \"\", nego->RequestedProtocols);\n\tnego->state = NEGO_STATE_FINAL;", "", "}", "/**\n * Process Negotiation Response from Connection Confirm message.\n * @param nego\n * @param s\n */\n", "void nego_process_negotiation_response(rdpNego* nego, wStream* s)", "{\n\tUINT16 length;\n\tWLog_DBG(TAG, \"RDP_NEG_RSP\");", "\tif (Stream_GetRemainingLength(s) < 7)\n\t{\n\t\tWLog_ERR(TAG, \"Invalid RDP_NEG_RSP\");\n\t\tnego->state = NEGO_STATE_FAIL;", "\t\treturn;", "\t}", "\tStream_Read_UINT8(s, nego->flags);\n\tStream_Read_UINT16(s, length);\n\tStream_Read_UINT32(s, nego->SelectedProtocol);\n\tnego->state = NEGO_STATE_FINAL;", "", "}", "/**\n * Process Negotiation Failure from Connection Confirm message.\n * @param nego\n * @param s\n */\n", "void nego_process_negotiation_failure(rdpNego* nego, wStream* s)", "{\n\tBYTE flags;\n\tUINT16 length;\n\tUINT32 failureCode;\n\tWLog_DBG(TAG, \"RDP_NEG_FAILURE\");", "", "\tStream_Read_UINT8(s, flags);\n\tStream_Read_UINT16(s, length);\n\tStream_Read_UINT32(s, failureCode);", "\tswitch (failureCode)\n\t{\n\t\tcase SSL_REQUIRED_BY_SERVER:\n\t\t\tWLog_WARN(TAG, \"Error: SSL_REQUIRED_BY_SERVER\");\n\t\t\tbreak;", "\t\tcase SSL_NOT_ALLOWED_BY_SERVER:\n\t\t\tWLog_WARN(TAG, \"Error: SSL_NOT_ALLOWED_BY_SERVER\");\n\t\t\tnego->sendNegoData = TRUE;\n\t\t\tbreak;", "\t\tcase SSL_CERT_NOT_ON_SERVER:\n\t\t\tWLog_ERR(TAG, \"Error: SSL_CERT_NOT_ON_SERVER\");\n\t\t\tnego->sendNegoData = TRUE;\n\t\t\tbreak;", "\t\tcase INCONSISTENT_FLAGS:\n\t\t\tWLog_ERR(TAG, \"Error: INCONSISTENT_FLAGS\");\n\t\t\tbreak;", "\t\tcase HYBRID_REQUIRED_BY_SERVER:\n\t\t\tWLog_WARN(TAG, \"Error: HYBRID_REQUIRED_BY_SERVER\");\n\t\t\tbreak;", "\t\tdefault:\n\t\t\tWLog_ERR(TAG, \"Error: Unknown protocol security error %\" PRIu32 \"\", failureCode);\n\t\t\tbreak;\n\t}", "\tnego->state = NEGO_STATE_FAIL;", "", "}", "/**\n * Send RDP Negotiation Response (RDP_NEG_RSP).\\n\n * @param nego\n */", "BOOL nego_send_negotiation_response(rdpNego* nego)\n{\n\tUINT16 length;\n\tsize_t bm, em;\n\tBOOL status;\n\twStream* s;\n\tBYTE flags;\n\trdpSettings* settings;\n\tstatus = TRUE;\n\tsettings = nego->transport->settings;\n\ts = Stream_New(NULL, 512);", "\tif (!s)\n\t{\n\t\tWLog_ERR(TAG, \"Stream_New failed!\");\n\t\treturn FALSE;\n\t}", "\tlength = TPDU_CONNECTION_CONFIRM_LENGTH;\n\tbm = Stream_GetPosition(s);\n\tStream_Seek(s, length);", "\tif (nego->SelectedProtocol & PROTOCOL_FAILED_NEGO)\n\t{\n\t\tUINT32 errorCode = (nego->SelectedProtocol & ~PROTOCOL_FAILED_NEGO);\n\t\tflags = 0;\n\t\tStream_Write_UINT8(s, TYPE_RDP_NEG_FAILURE);\n\t\tStream_Write_UINT8(s, flags); /* flags */\n\t\tStream_Write_UINT16(s, 8); /* RDP_NEG_DATA length (8) */\n\t\tStream_Write_UINT32(s, errorCode);\n\t\tlength += 8;\n\t\tstatus = FALSE;\n\t}\n\telse\n\t{\n\t\tflags = EXTENDED_CLIENT_DATA_SUPPORTED;", "\t\tif (settings->SupportGraphicsPipeline)\n\t\t\tflags |= DYNVC_GFX_PROTOCOL_SUPPORTED;", "\t\t/* RDP_NEG_DATA must be present for TLS, NLA, and RDP */\n\t\tStream_Write_UINT8(s, TYPE_RDP_NEG_RSP);\n\t\tStream_Write_UINT8(s, flags); /* flags */\n\t\tStream_Write_UINT16(s, 8); /* RDP_NEG_DATA length (8) */\n\t\tStream_Write_UINT32(s, nego->SelectedProtocol); /* selectedProtocol */\n\t\tlength += 8;\n\t}", "\tem = Stream_GetPosition(s);\n\tStream_SetPosition(s, bm);\n\ttpkt_write_header(s, length);\n\ttpdu_write_connection_confirm(s, length - 5);\n\tStream_SetPosition(s, em);\n\tStream_SealLength(s);", "\tif (transport_write(nego->transport, s) < 0)\n\t{\n\t\tStream_Free(s, TRUE);\n\t\treturn FALSE;\n\t}", "\tStream_Free(s, TRUE);", "\tif (status)\n\t{\n\t\t/* update settings with negotiated protocol security */\n\t\tsettings->RequestedProtocols = nego->RequestedProtocols;\n\t\tsettings->SelectedProtocol = nego->SelectedProtocol;", "\t\tif (settings->SelectedProtocol == PROTOCOL_RDP)\n\t\t{\n\t\t\tsettings->TlsSecurity = FALSE;\n\t\t\tsettings->NlaSecurity = FALSE;\n\t\t\tsettings->RdpSecurity = TRUE;\n\t\t\tsettings->UseRdpSecurityLayer = TRUE;", "\t\t\tif (settings->EncryptionLevel == ENCRYPTION_LEVEL_NONE)\n\t\t\t{\n\t\t\t\t/**\n\t\t\t\t * If the server implementation did not explicitely set a\n\t\t\t\t * encryption level we default to client compatible\n\t\t\t\t */\n\t\t\t\tsettings->EncryptionLevel = ENCRYPTION_LEVEL_CLIENT_COMPATIBLE;\n\t\t\t}", "\t\t\tif (settings->LocalConnection)\n\t\t\t{\n\t\t\t\t/**\n\t\t\t\t * Note: This hack was firstly introduced in commit 95f5e115 to\n\t\t\t\t * disable the unnecessary encryption with peers connecting to\n\t\t\t\t * 127.0.0.1 or local unix sockets.\n\t\t\t\t * This also affects connections via port tunnels! (e.g. ssh -L)\n\t\t\t\t */\n\t\t\t\tWLog_INFO(TAG, \"Turning off encryption for local peer with standard rdp security\");\n\t\t\t\tsettings->UseRdpSecurityLayer = FALSE;\n\t\t\t\tsettings->EncryptionLevel = ENCRYPTION_LEVEL_NONE;\n\t\t\t}", "\t\t\tif (!settings->RdpServerRsaKey && !settings->RdpKeyFile && !settings->RdpKeyContent)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"Missing server certificate\");\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t}\n\t\telse if (settings->SelectedProtocol == PROTOCOL_SSL)\n\t\t{\n\t\t\tsettings->TlsSecurity = TRUE;\n\t\t\tsettings->NlaSecurity = FALSE;\n\t\t\tsettings->RdpSecurity = FALSE;\n\t\t\tsettings->UseRdpSecurityLayer = FALSE;\n\t\t\tsettings->EncryptionLevel = ENCRYPTION_LEVEL_NONE;\n\t\t}\n\t\telse if (settings->SelectedProtocol == PROTOCOL_HYBRID)\n\t\t{\n\t\t\tsettings->TlsSecurity = TRUE;\n\t\t\tsettings->NlaSecurity = TRUE;\n\t\t\tsettings->RdpSecurity = FALSE;\n\t\t\tsettings->UseRdpSecurityLayer = FALSE;\n\t\t\tsettings->EncryptionLevel = ENCRYPTION_LEVEL_NONE;\n\t\t}\n\t}", "\treturn status;\n}", "/**\n * Initialize NEGO state machine.\n * @param nego\n */", "void nego_init(rdpNego* nego)\n{\n\tnego->state = NEGO_STATE_INITIAL;\n\tnego->RequestedProtocols = PROTOCOL_RDP;\n\tnego->CookieMaxLength = DEFAULT_COOKIE_MAX_LENGTH;\n\tnego->sendNegoData = FALSE;\n\tnego->flags = 0;\n}", "/**\n * Create a new NEGO state machine instance.\n * @param transport\n * @return\n */", "rdpNego* nego_new(rdpTransport* transport)\n{\n\trdpNego* nego = (rdpNego*)calloc(1, sizeof(rdpNego));", "\tif (!nego)\n\t\treturn NULL;", "\tnego->transport = transport;\n\tnego_init(nego);\n\treturn nego;\n}", "/**\n * Free NEGO state machine.\n * @param nego\n */", "void nego_free(rdpNego* nego)\n{\n\tif (nego)\n\t{\n\t\tfree(nego->RoutingToken);\n\t\tfree(nego->cookie);\n\t\tfree(nego);\n\t}\n}", "/**\n * Set target hostname and port.\n * @param nego\n * @param hostname\n * @param port\n */", "BOOL nego_set_target(rdpNego* nego, const char* hostname, UINT16 port)\n{\n\tif (!nego || !hostname)\n\t\treturn FALSE;", "\tnego->hostname = hostname;\n\tnego->port = port;\n\treturn TRUE;\n}", "/**\n * Enable security layer negotiation.\n * @param nego pointer to the negotiation structure\n * @param enable_rdp whether to enable security layer negotiation (TRUE for enabled, FALSE for\n * disabled)\n */", "void nego_set_negotiation_enabled(rdpNego* nego, BOOL NegotiateSecurityLayer)\n{\n\tWLog_DBG(TAG, \"Enabling security layer negotiation: %s\",\n\t NegotiateSecurityLayer ? \"TRUE\" : \"FALSE\");\n\tnego->NegotiateSecurityLayer = NegotiateSecurityLayer;\n}", "/**\n * Enable restricted admin mode.\n * @param nego pointer to the negotiation structure\n * @param enable_restricted whether to enable security layer negotiation (TRUE for enabled, FALSE\n * for disabled)\n */", "void nego_set_restricted_admin_mode_required(rdpNego* nego, BOOL RestrictedAdminModeRequired)\n{\n\tWLog_DBG(TAG, \"Enabling restricted admin mode: %s\",\n\t RestrictedAdminModeRequired ? \"TRUE\" : \"FALSE\");\n\tnego->RestrictedAdminModeRequired = RestrictedAdminModeRequired;\n}", "void nego_set_gateway_enabled(rdpNego* nego, BOOL GatewayEnabled)\n{\n\tnego->GatewayEnabled = GatewayEnabled;\n}", "void nego_set_gateway_bypass_local(rdpNego* nego, BOOL GatewayBypassLocal)\n{\n\tnego->GatewayBypassLocal = GatewayBypassLocal;\n}", "/**\n * Enable RDP security protocol.\n * @param nego pointer to the negotiation structure\n * @param enable_rdp whether to enable normal RDP protocol (TRUE for enabled, FALSE for disabled)\n */", "void nego_enable_rdp(rdpNego* nego, BOOL enable_rdp)\n{\n\tWLog_DBG(TAG, \"Enabling RDP security: %s\", enable_rdp ? \"TRUE\" : \"FALSE\");\n\tnego->EnabledProtocols[PROTOCOL_RDP] = enable_rdp;\n}", "/**\n * Enable TLS security protocol.\n * @param nego pointer to the negotiation structure\n * @param enable_tls whether to enable TLS + RDP protocol (TRUE for enabled, FALSE for disabled)\n */", "void nego_enable_tls(rdpNego* nego, BOOL enable_tls)\n{\n\tWLog_DBG(TAG, \"Enabling TLS security: %s\", enable_tls ? \"TRUE\" : \"FALSE\");\n\tnego->EnabledProtocols[PROTOCOL_SSL] = enable_tls;\n}", "/**\n * Enable NLA security protocol.\n * @param nego pointer to the negotiation structure\n * @param enable_nla whether to enable network level authentication protocol (TRUE for enabled,\n * FALSE for disabled)\n */", "void nego_enable_nla(rdpNego* nego, BOOL enable_nla)\n{\n\tWLog_DBG(TAG, \"Enabling NLA security: %s\", enable_nla ? \"TRUE\" : \"FALSE\");\n\tnego->EnabledProtocols[PROTOCOL_HYBRID] = enable_nla;\n}", "/**\n * Enable NLA extended security protocol.\n * @param nego pointer to the negotiation structure\n * @param enable_ext whether to enable network level authentication extended protocol (TRUE for\n * enabled, FALSE for disabled)\n */", "void nego_enable_ext(rdpNego* nego, BOOL enable_ext)\n{\n\tWLog_DBG(TAG, \"Enabling NLA extended security: %s\", enable_ext ? \"TRUE\" : \"FALSE\");\n\tnego->EnabledProtocols[PROTOCOL_HYBRID_EX] = enable_ext;\n}", "/**\n * Set routing token.\n * @param nego\n * @param RoutingToken\n * @param RoutingTokenLength\n */", "BOOL nego_set_routing_token(rdpNego* nego, BYTE* RoutingToken, DWORD RoutingTokenLength)\n{\n\tif (RoutingTokenLength == 0)\n\t\treturn FALSE;", "\tfree(nego->RoutingToken);\n\tnego->RoutingTokenLength = RoutingTokenLength;\n\tnego->RoutingToken = (BYTE*)malloc(nego->RoutingTokenLength);", "\tif (!nego->RoutingToken)\n\t\treturn FALSE;", "\tCopyMemory(nego->RoutingToken, RoutingToken, nego->RoutingTokenLength);\n\treturn TRUE;\n}", "/**\n * Set cookie.\n * @param nego\n * @param cookie\n */", "BOOL nego_set_cookie(rdpNego* nego, char* cookie)\n{\n\tif (nego->cookie)\n\t{\n\t\tfree(nego->cookie);\n\t\tnego->cookie = NULL;\n\t}", "\tif (!cookie)\n\t\treturn TRUE;", "\tnego->cookie = _strdup(cookie);", "\tif (!nego->cookie)\n\t\treturn FALSE;", "\treturn TRUE;\n}", "/**\n * Set cookie maximum length\n * @param nego\n * @param CookieMaxLength\n */", "void nego_set_cookie_max_length(rdpNego* nego, UINT32 CookieMaxLength)\n{\n\tnego->CookieMaxLength = CookieMaxLength;\n}", "/**\n * Enable / disable preconnection PDU.\n * @param nego\n * @param send_pcpdu\n */", "void nego_set_send_preconnection_pdu(rdpNego* nego, BOOL SendPreconnectionPdu)\n{\n\tnego->SendPreconnectionPdu = SendPreconnectionPdu;\n}", "/**\n * Set preconnection id.\n * @param nego\n * @param id\n */", "void nego_set_preconnection_id(rdpNego* nego, UINT32 PreconnectionId)\n{\n\tnego->PreconnectionId = PreconnectionId;\n}", "/**\n * Set preconnection blob.\n * @param nego\n * @param blob\n */", "void nego_set_preconnection_blob(rdpNego* nego, char* PreconnectionBlob)\n{\n\tnego->PreconnectionBlob = PreconnectionBlob;\n}", "UINT32 nego_get_selected_protocol(rdpNego* nego)\n{\n\tif (!nego)\n\t\treturn 0;", "\treturn nego->SelectedProtocol;\n}", "BOOL nego_set_selected_protocol(rdpNego* nego, UINT32 SelectedProtocol)\n{\n\tif (!nego)\n\t\treturn FALSE;", "\tnego->SelectedProtocol = SelectedProtocol;\n\treturn TRUE;\n}", "UINT32 nego_get_requested_protocols(rdpNego* nego)\n{\n\tif (!nego)\n\t\treturn 0;", "\treturn nego->RequestedProtocols;\n}", "BOOL nego_set_requested_protocols(rdpNego* nego, UINT32 RequestedProtocols)\n{\n\tif (!nego)\n\t\treturn FALSE;", "\tnego->RequestedProtocols = RequestedProtocols;\n\treturn TRUE;\n}", "NEGO_STATE nego_get_state(rdpNego* nego)\n{\n\tif (!nego)\n\t\treturn NEGO_STATE_FAIL;", "\treturn nego->state;\n}", "BOOL nego_set_state(rdpNego* nego, NEGO_STATE state)\n{\n\tif (!nego)\n\t\treturn FALSE;", "\tnego->state = state;\n\treturn TRUE;\n}", "SEC_WINNT_AUTH_IDENTITY* nego_get_identity(rdpNego* nego)\n{\n\tif (!nego)\n\t\treturn NULL;", "\treturn nla_get_identity(nego->transport->nla);\n}", "void nego_free_nla(rdpNego* nego)\n{\n\tif (!nego || !nego->transport)\n\t\treturn;", "\tnla_free(nego->transport->nla);\n\tnego->transport->nla = NULL;\n}", "const BYTE* nego_get_routing_token(rdpNego* nego, DWORD* RoutingTokenLength)\n{\n\tif (!nego)\n\t\treturn NULL;\n\tif (RoutingTokenLength)\n\t\t*RoutingTokenLength = nego->RoutingTokenLength;\n\treturn nego->RoutingToken;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [357, 496, 447, 322, 308, 1001], "buggy_code_start_loc": [333, 480, 447, 145, 307, 94], "filenames": ["channels/drive/client/drive_main.c", "channels/printer/client/printer_main.c", "channels/rdpei/client/rdpei_main.c", "channels/serial/client/serial_main.c", "libfreerdp/core/gateway/rdg.c", "libfreerdp/core/nego.c"], "fixing_code_end_loc": [361, 502, 451, 327, 309, 1013], "fixing_code_start_loc": [334, 481, 448, 145, 307, 94], "message": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:freerdp:freerdp:*:*:*:*:*:*:*:*", "matchCriteriaId": "5C5F8D57-1D22-42B4-9E08-9131F7BE8FA5", "versionEndExcluding": "2.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "B620311B-34A3-48A6-82DF-6F078D7A4493", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0."}, {"lang": "es", "value": "En FreeRDP versiones anteriores a 2.1.0, se presenta una lectura fuera de l\u00edmite en las funciones de irp (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). Esto ha sido corregido en la versi\u00f3n 2.1.0."}], "evaluatorComment": null, "id": "CVE-2020-11089", "lastModified": "2022-07-19T11:52:15.420", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:L/I:L/A:L", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 2.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-05-29T20:15:11.017", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2020-07/msg00080.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/795842f4096501fcefc1a7f535ccc8132feb31d7"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/security/advisories/GHSA-hfc7-c5gv-8c2h"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-125"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, "type": "CWE-125"}
320
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * FreeRDP: A Remote Desktop Protocol Implementation\n * RDP Protocol Security Negotiation\n *\n * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com>\n * Copyright 2014 Norbert Federa <norbert.federa@thincast.com>\n * Copyright 2015 Thincast Technologies GmbH\n * Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */", "#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif", "#include <winpr/crt.h>", "#include <freerdp/log.h>", "#include \"tpkt.h\"", "#include \"nego.h\"", "#include \"transport.h\"", "#define TAG FREERDP_TAG(\"core.nego\")", "struct rdp_nego\n{\n\tUINT16 port;\n\tUINT32 flags;\n\tconst char* hostname;\n\tchar* cookie;\n\tBYTE* RoutingToken;\n\tDWORD RoutingTokenLength;\n\tBOOL SendPreconnectionPdu;\n\tUINT32 PreconnectionId;\n\tchar* PreconnectionBlob;", "\tNEGO_STATE state;\n\tBOOL TcpConnected;\n\tBOOL SecurityConnected;\n\tUINT32 CookieMaxLength;", "\tBOOL sendNegoData;\n\tUINT32 SelectedProtocol;\n\tUINT32 RequestedProtocols;\n\tBOOL NegotiateSecurityLayer;\n\tBOOL EnabledProtocols[16];\n\tBOOL RestrictedAdminModeRequired;\n\tBOOL GatewayEnabled;\n\tBOOL GatewayBypassLocal;", "\trdpTransport* transport;\n};", "static const char* nego_state_string(NEGO_STATE state)\n{\n\tstatic const char* const NEGO_STATE_STRINGS[] = { \"NEGO_STATE_INITIAL\", \"NEGO_STATE_EXT\",\n\t\t \"NEGO_STATE_NLA\", \"NEGO_STATE_TLS\",\n\t\t \"NEGO_STATE_RDP\", \"NEGO_STATE_FAIL\",\n\t\t \"NEGO_STATE_FINAL\", \"NEGO_STATE_INVALID\" };\n\tif (state >= ARRAYSIZE(NEGO_STATE_STRINGS))\n\t\treturn NEGO_STATE_STRINGS[ARRAYSIZE(NEGO_STATE_STRINGS) - 1];\n\treturn NEGO_STATE_STRINGS[state];\n}", "static const char* protocol_security_string(UINT32 security)\n{\n\tstatic const char* PROTOCOL_SECURITY_STRINGS[] = { \"RDP\", \"TLS\", \"NLA\", \"UNK\", \"UNK\",\n\t\t \"UNK\", \"UNK\", \"UNK\", \"EXT\", \"UNK\" };\n\tif (security >= ARRAYSIZE(PROTOCOL_SECURITY_STRINGS))\n\t\treturn PROTOCOL_SECURITY_STRINGS[ARRAYSIZE(PROTOCOL_SECURITY_STRINGS) - 1];\n\treturn PROTOCOL_SECURITY_STRINGS[security];\n}", "static BOOL nego_transport_connect(rdpNego* nego);\nstatic BOOL nego_transport_disconnect(rdpNego* nego);\nstatic BOOL nego_security_connect(rdpNego* nego);\nstatic BOOL nego_send_preconnection_pdu(rdpNego* nego);\nstatic BOOL nego_recv_response(rdpNego* nego);\nstatic void nego_send(rdpNego* nego);", "static BOOL nego_process_negotiation_request(rdpNego* nego, wStream* s);\nstatic BOOL nego_process_negotiation_response(rdpNego* nego, wStream* s);\nstatic BOOL nego_process_negotiation_failure(rdpNego* nego, wStream* s);", "\n/**\n * Negotiate protocol security and connect.\n * @param nego\n * @return\n */", "BOOL nego_connect(rdpNego* nego)\n{\n\trdpSettings* settings = nego->transport->settings;", "\tif (nego->state == NEGO_STATE_INITIAL)\n\t{\n\t\tif (nego->EnabledProtocols[PROTOCOL_HYBRID_EX])\n\t\t{\n\t\t\tnego->state = NEGO_STATE_EXT;\n\t\t}\n\t\telse if (nego->EnabledProtocols[PROTOCOL_HYBRID])\n\t\t{\n\t\t\tnego->state = NEGO_STATE_NLA;\n\t\t}\n\t\telse if (nego->EnabledProtocols[PROTOCOL_SSL])\n\t\t{\n\t\t\tnego->state = NEGO_STATE_TLS;\n\t\t}\n\t\telse if (nego->EnabledProtocols[PROTOCOL_RDP])\n\t\t{\n\t\t\tnego->state = NEGO_STATE_RDP;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tWLog_ERR(TAG, \"No security protocol is enabled\");\n\t\t\tnego->state = NEGO_STATE_FAIL;\n\t\t\treturn FALSE;\n\t\t}", "\t\tif (!nego->NegotiateSecurityLayer)\n\t\t{\n\t\t\tWLog_DBG(TAG, \"Security Layer Negotiation is disabled\");\n\t\t\t/* attempt only the highest enabled protocol (see nego_attempt_*) */\n\t\t\tnego->EnabledProtocols[PROTOCOL_HYBRID] = FALSE;\n\t\t\tnego->EnabledProtocols[PROTOCOL_SSL] = FALSE;\n\t\t\tnego->EnabledProtocols[PROTOCOL_RDP] = FALSE;\n\t\t\tnego->EnabledProtocols[PROTOCOL_HYBRID_EX] = FALSE;", "\t\t\tif (nego->state == NEGO_STATE_EXT)\n\t\t\t{\n\t\t\t\tnego->EnabledProtocols[PROTOCOL_HYBRID_EX] = TRUE;\n\t\t\t\tnego->EnabledProtocols[PROTOCOL_HYBRID] = TRUE;\n\t\t\t\tnego->SelectedProtocol = PROTOCOL_HYBRID_EX;\n\t\t\t}\n\t\t\telse if (nego->state == NEGO_STATE_NLA)\n\t\t\t{\n\t\t\t\tnego->EnabledProtocols[PROTOCOL_HYBRID] = TRUE;\n\t\t\t\tnego->SelectedProtocol = PROTOCOL_HYBRID;\n\t\t\t}\n\t\t\telse if (nego->state == NEGO_STATE_TLS)\n\t\t\t{\n\t\t\t\tnego->EnabledProtocols[PROTOCOL_SSL] = TRUE;\n\t\t\t\tnego->SelectedProtocol = PROTOCOL_SSL;\n\t\t\t}\n\t\t\telse if (nego->state == NEGO_STATE_RDP)\n\t\t\t{\n\t\t\t\tnego->EnabledProtocols[PROTOCOL_RDP] = TRUE;\n\t\t\t\tnego->SelectedProtocol = PROTOCOL_RDP;\n\t\t\t}\n\t\t}", "\t\tif (nego->SendPreconnectionPdu)\n\t\t{\n\t\t\tif (!nego_send_preconnection_pdu(nego))\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"Failed to send preconnection pdu\");\n\t\t\t\tnego->state = NEGO_STATE_FINAL;\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t}\n\t}", "\tif (!nego->NegotiateSecurityLayer)\n\t{\n\t\tnego->state = NEGO_STATE_FINAL;\n\t}\n\telse\n\t{\n\t\tdo\n\t\t{\n\t\t\tWLog_DBG(TAG, \"state: %s\", nego_state_string(nego->state));\n\t\t\tnego_send(nego);", "\t\t\tif (nego->state == NEGO_STATE_FAIL)\n\t\t\t{\n\t\t\t\tif (freerdp_get_last_error(nego->transport->context) == FREERDP_ERROR_SUCCESS)\n\t\t\t\t\tWLog_ERR(TAG, \"Protocol Security Negotiation Failure\");", "\t\t\t\tnego->state = NEGO_STATE_FINAL;\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t} while (nego->state != NEGO_STATE_FINAL);\n\t}", "\tWLog_DBG(TAG, \"Negotiated %s security\", protocol_security_string(nego->SelectedProtocol));\n\t/* update settings with negotiated protocol security */\n\tsettings->RequestedProtocols = nego->RequestedProtocols;\n\tsettings->SelectedProtocol = nego->SelectedProtocol;\n\tsettings->NegotiationFlags = nego->flags;", "\tif (nego->SelectedProtocol == PROTOCOL_RDP)\n\t{\n\t\tsettings->UseRdpSecurityLayer = TRUE;", "\t\tif (!settings->EncryptionMethods)\n\t\t{\n\t\t\t/**\n\t\t\t * Advertise all supported encryption methods if the client\n\t\t\t * implementation did not set any security methods\n\t\t\t */\n\t\t\tsettings->EncryptionMethods = ENCRYPTION_METHOD_40BIT | ENCRYPTION_METHOD_56BIT |\n\t\t\t ENCRYPTION_METHOD_128BIT | ENCRYPTION_METHOD_FIPS;\n\t\t}\n\t}", "\t/* finally connect security layer (if not already done) */\n\tif (!nego_security_connect(nego))\n\t{\n\t\tWLog_DBG(TAG, \"Failed to connect with %s security\",\n\t\t protocol_security_string(nego->SelectedProtocol));\n\t\treturn FALSE;\n\t}", "\treturn TRUE;\n}", "BOOL nego_disconnect(rdpNego* nego)\n{\n\tnego->state = NEGO_STATE_INITIAL;\n\treturn nego_transport_disconnect(nego);\n}", "/* connect to selected security layer */\nBOOL nego_security_connect(rdpNego* nego)\n{\n\tif (!nego->TcpConnected)\n\t{\n\t\tnego->SecurityConnected = FALSE;\n\t}\n\telse if (!nego->SecurityConnected)\n\t{\n\t\tif (nego->SelectedProtocol == PROTOCOL_HYBRID)\n\t\t{\n\t\t\tWLog_DBG(TAG, \"nego_security_connect with PROTOCOL_HYBRID\");\n\t\t\tnego->SecurityConnected = transport_connect_nla(nego->transport);\n\t\t}\n\t\telse if (nego->SelectedProtocol == PROTOCOL_SSL)\n\t\t{\n\t\t\tWLog_DBG(TAG, \"nego_security_connect with PROTOCOL_SSL\");\n\t\t\tnego->SecurityConnected = transport_connect_tls(nego->transport);\n\t\t}\n\t\telse if (nego->SelectedProtocol == PROTOCOL_RDP)\n\t\t{\n\t\t\tWLog_DBG(TAG, \"nego_security_connect with PROTOCOL_RDP\");\n\t\t\tnego->SecurityConnected = transport_connect_rdp(nego->transport);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tWLog_ERR(TAG,\n\t\t\t \"cannot connect security layer because no protocol has been selected yet.\");\n\t\t}\n\t}", "\treturn nego->SecurityConnected;\n}", "/**\n * Connect TCP layer.\n * @param nego\n * @return\n */", "static BOOL nego_tcp_connect(rdpNego* nego)\n{\n\tif (!nego->TcpConnected)\n\t{\n\t\tif (nego->GatewayEnabled)\n\t\t{\n\t\t\tif (nego->GatewayBypassLocal)\n\t\t\t{\n\t\t\t\t/* Attempt a direct connection first, and then fallback to using the gateway */\n\t\t\t\tWLog_INFO(TAG,\n\t\t\t\t \"Detecting if host can be reached locally. - This might take some time.\");\n\t\t\t\tWLog_INFO(TAG, \"To disable auto detection use /gateway-usage-method:direct\");\n\t\t\t\ttransport_set_gateway_enabled(nego->transport, FALSE);\n\t\t\t\tnego->TcpConnected =\n\t\t\t\t transport_connect(nego->transport, nego->hostname, nego->port, 1);\n\t\t\t}", "\t\t\tif (!nego->TcpConnected)\n\t\t\t{\n\t\t\t\ttransport_set_gateway_enabled(nego->transport, TRUE);\n\t\t\t\tnego->TcpConnected =\n\t\t\t\t transport_connect(nego->transport, nego->hostname, nego->port, 15);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tnego->TcpConnected = transport_connect(nego->transport, nego->hostname, nego->port, 15);\n\t\t}\n\t}", "\treturn nego->TcpConnected;\n}", "/**\n * Connect TCP layer. For direct approach, connect security layer as well.\n * @param nego\n * @return\n */", "BOOL nego_transport_connect(rdpNego* nego)\n{\n\tif (!nego_tcp_connect(nego))\n\t\treturn FALSE;", "\tif (nego->TcpConnected && !nego->NegotiateSecurityLayer)\n\t\treturn nego_security_connect(nego);", "\treturn nego->TcpConnected;\n}", "/**\n * Disconnect TCP layer.\n * @param nego\n * @return\n */", "BOOL nego_transport_disconnect(rdpNego* nego)\n{\n\tif (nego->TcpConnected)\n\t\ttransport_disconnect(nego->transport);", "\tnego->TcpConnected = FALSE;\n\tnego->SecurityConnected = FALSE;\n\treturn TRUE;\n}", "/**\n * Send preconnection information if enabled.\n * @param nego\n * @return\n */", "BOOL nego_send_preconnection_pdu(rdpNego* nego)\n{\n\twStream* s;\n\tUINT32 cbSize;\n\tUINT16 cchPCB = 0;\n\tWCHAR* wszPCB = NULL;\n\tWLog_DBG(TAG, \"Sending preconnection PDU\");", "\tif (!nego_tcp_connect(nego))\n\t\treturn FALSE;", "\t/* it's easier to always send the version 2 PDU, and it's just 2 bytes overhead */\n\tcbSize = PRECONNECTION_PDU_V2_MIN_SIZE;", "\tif (nego->PreconnectionBlob)\n\t{\n\t\tcchPCB = (UINT16)ConvertToUnicode(CP_UTF8, 0, nego->PreconnectionBlob, -1, &wszPCB, 0);\n\t\tcchPCB += 1; /* zero-termination */\n\t\tcbSize += cchPCB * 2;\n\t}", "\ts = Stream_New(NULL, cbSize);", "\tif (!s)\n\t{\n\t\tfree(wszPCB);\n\t\tWLog_ERR(TAG, \"Stream_New failed!\");\n\t\treturn FALSE;\n\t}", "\tStream_Write_UINT32(s, cbSize); /* cbSize */\n\tStream_Write_UINT32(s, 0); /* Flags */\n\tStream_Write_UINT32(s, PRECONNECTION_PDU_V2); /* Version */\n\tStream_Write_UINT32(s, nego->PreconnectionId); /* Id */\n\tStream_Write_UINT16(s, cchPCB); /* cchPCB */", "\tif (wszPCB)\n\t{\n\t\tStream_Write(s, wszPCB, cchPCB * 2); /* wszPCB */\n\t\tfree(wszPCB);\n\t}", "\tStream_SealLength(s);", "\tif (transport_write(nego->transport, s) < 0)\n\t{\n\t\tStream_Free(s, TRUE);\n\t\treturn FALSE;\n\t}", "\tStream_Free(s, TRUE);\n\treturn TRUE;\n}", "/**\n * Attempt negotiating NLA + TLS extended security.\n * @param nego\n */", "static void nego_attempt_ext(rdpNego* nego)\n{\n\tnego->RequestedProtocols = PROTOCOL_HYBRID | PROTOCOL_SSL | PROTOCOL_HYBRID_EX;\n\tWLog_DBG(TAG, \"Attempting NLA extended security\");", "\tif (!nego_transport_connect(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}", "\tif (!nego_send_negotiation_request(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}", "\tif (!nego_recv_response(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}", "\tWLog_DBG(TAG, \"state: %s\", nego_state_string(nego->state));", "\tif (nego->state != NEGO_STATE_FINAL)\n\t{\n\t\tnego_transport_disconnect(nego);", "\t\tif (nego->EnabledProtocols[PROTOCOL_HYBRID])\n\t\t\tnego->state = NEGO_STATE_NLA;\n\t\telse if (nego->EnabledProtocols[PROTOCOL_SSL])\n\t\t\tnego->state = NEGO_STATE_TLS;\n\t\telse if (nego->EnabledProtocols[PROTOCOL_RDP])\n\t\t\tnego->state = NEGO_STATE_RDP;\n\t\telse\n\t\t\tnego->state = NEGO_STATE_FAIL;\n\t}\n}", "/**\n * Attempt negotiating NLA + TLS security.\n * @param nego\n */", "static void nego_attempt_nla(rdpNego* nego)\n{\n\tnego->RequestedProtocols = PROTOCOL_HYBRID | PROTOCOL_SSL;\n\tWLog_DBG(TAG, \"Attempting NLA security\");", "\tif (!nego_transport_connect(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}", "\tif (!nego_send_negotiation_request(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}", "\tif (!nego_recv_response(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}", "\tWLog_DBG(TAG, \"state: %s\", nego_state_string(nego->state));", "\tif (nego->state != NEGO_STATE_FINAL)\n\t{\n\t\tnego_transport_disconnect(nego);", "\t\tif (nego->EnabledProtocols[PROTOCOL_SSL])\n\t\t\tnego->state = NEGO_STATE_TLS;\n\t\telse if (nego->EnabledProtocols[PROTOCOL_RDP])\n\t\t\tnego->state = NEGO_STATE_RDP;\n\t\telse\n\t\t\tnego->state = NEGO_STATE_FAIL;\n\t}\n}", "/**\n * Attempt negotiating TLS security.\n * @param nego\n */", "static void nego_attempt_tls(rdpNego* nego)\n{\n\tnego->RequestedProtocols = PROTOCOL_SSL;\n\tWLog_DBG(TAG, \"Attempting TLS security\");", "\tif (!nego_transport_connect(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}", "\tif (!nego_send_negotiation_request(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}", "\tif (!nego_recv_response(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}", "\tif (nego->state != NEGO_STATE_FINAL)\n\t{\n\t\tnego_transport_disconnect(nego);", "\t\tif (nego->EnabledProtocols[PROTOCOL_RDP])\n\t\t\tnego->state = NEGO_STATE_RDP;\n\t\telse\n\t\t\tnego->state = NEGO_STATE_FAIL;\n\t}\n}", "/**\n * Attempt negotiating standard RDP security.\n * @param nego\n */", "static void nego_attempt_rdp(rdpNego* nego)\n{\n\tnego->RequestedProtocols = PROTOCOL_RDP;\n\tWLog_DBG(TAG, \"Attempting RDP security\");", "\tif (!nego_transport_connect(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}", "\tif (!nego_send_negotiation_request(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}", "\tif (!nego_recv_response(nego))\n\t{\n\t\tnego->state = NEGO_STATE_FAIL;\n\t\treturn;\n\t}\n}", "/**\n * Wait to receive a negotiation response\n * @param nego\n */", "BOOL nego_recv_response(rdpNego* nego)\n{\n\tint status;\n\twStream* s;\n\ts = Stream_New(NULL, 1024);", "\tif (!s)\n\t{\n\t\tWLog_ERR(TAG, \"Stream_New failed!\");\n\t\treturn FALSE;\n\t}", "\tstatus = transport_read_pdu(nego->transport, s);", "\tif (status < 0)\n\t{\n\t\tStream_Free(s, TRUE);\n\t\treturn FALSE;\n\t}", "\tstatus = nego_recv(nego->transport, s, nego);\n\tStream_Free(s, TRUE);", "\tif (status < 0)\n\t\treturn FALSE;", "\treturn TRUE;\n}", "/**\n * Receive protocol security negotiation message.\\n\n * @msdn{cc240501}\n * @param transport transport\n * @param s stream\n * @param extra nego pointer\n */", "int nego_recv(rdpTransport* transport, wStream* s, void* extra)\n{\n\tBYTE li;\n\tBYTE type;\n\tUINT16 length;\n\trdpNego* nego = (rdpNego*)extra;", "\tif (!tpkt_read_header(s, &length))\n\t\treturn -1;", "\tif (!tpdu_read_connection_confirm(s, &li, length))\n\t\treturn -1;", "\tif (li > 6)\n\t{\n\t\t/* rdpNegData (optional) */\n\t\tStream_Read_UINT8(s, type); /* Type */", "\t\tswitch (type)\n\t\t{\n\t\t\tcase TYPE_RDP_NEG_RSP:", "\t\t\t\tif (!nego_process_negotiation_response(nego, s))\n\t\t\t\t\treturn -1;", "\t\t\t\tWLog_DBG(TAG, \"selected_protocol: %\" PRIu32 \"\", nego->SelectedProtocol);", "\t\t\t\t/* enhanced security selected ? */", "\t\t\t\tif (nego->SelectedProtocol)\n\t\t\t\t{\n\t\t\t\t\tif ((nego->SelectedProtocol == PROTOCOL_HYBRID) &&\n\t\t\t\t\t (!nego->EnabledProtocols[PROTOCOL_HYBRID]))\n\t\t\t\t\t{\n\t\t\t\t\t\tnego->state = NEGO_STATE_FAIL;\n\t\t\t\t\t}", "\t\t\t\t\tif ((nego->SelectedProtocol == PROTOCOL_SSL) &&\n\t\t\t\t\t (!nego->EnabledProtocols[PROTOCOL_SSL]))\n\t\t\t\t\t{\n\t\t\t\t\t\tnego->state = NEGO_STATE_FAIL;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (!nego->EnabledProtocols[PROTOCOL_RDP])\n\t\t\t\t{\n\t\t\t\t\tnego->state = NEGO_STATE_FAIL;\n\t\t\t\t}", "\t\t\t\tbreak;", "\t\t\tcase TYPE_RDP_NEG_FAILURE:", "\t\t\t\tif (!nego_process_negotiation_failure(nego, s))\n\t\t\t\t\treturn -1;", "\t\t\t\tbreak;\n\t\t}\n\t}\n\telse if (li == 6)\n\t{\n\t\tWLog_DBG(TAG, \"no rdpNegData\");", "\t\tif (!nego->EnabledProtocols[PROTOCOL_RDP])\n\t\t\tnego->state = NEGO_STATE_FAIL;\n\t\telse\n\t\t\tnego->state = NEGO_STATE_FINAL;\n\t}\n\telse\n\t{\n\t\tWLog_ERR(TAG, \"invalid negotiation response\");\n\t\tnego->state = NEGO_STATE_FAIL;\n\t}", "\tif (!tpkt_ensure_stream_consumed(s, length))\n\t\treturn -1;\n\treturn 0;\n}", "/**\n * Read optional routing token or cookie of X.224 Connection Request PDU.\n * @msdn{cc240470}\n * @param nego\n * @param s stream\n */", "static BOOL nego_read_request_token_or_cookie(rdpNego* nego, wStream* s)\n{\n\t/* routingToken and cookie are optional and mutually exclusive!\n\t *\n\t * routingToken (variable): An optional and variable-length routing\n\t * token (used for load balancing) terminated by a 0x0D0A two-byte\n\t * sequence: (check [MSFT-SDLBTS] for details!)\n\t * Cookie:[space]msts=[ip address].[port].[reserved][\\x0D\\x0A]\n\t *\n\t * cookie (variable): An optional and variable-length ANSI character\n\t * string terminated by a 0x0D0A two-byte sequence:\n\t * Cookie:[space]mstshash=[ANSISTRING][\\x0D\\x0A]\n\t */\n\tBYTE* str = NULL;\n\tUINT16 crlf = 0;\n\tsize_t pos, len;\n\tBOOL result = FALSE;\n\tBOOL isToken = FALSE;\n\tsize_t remain = Stream_GetRemainingLength(s);\n\tstr = Stream_Pointer(s);\n\tpos = Stream_GetPosition(s);", "\t/* minimum length for token is 15 */\n\tif (remain < 15)\n\t\treturn TRUE;", "\tif (memcmp(Stream_Pointer(s), \"Cookie: mstshash=\", 17) != 0)\n\t{\n\t\tisToken = TRUE;\n\t}\n\telse\n\t{\n\t\t/* not a token, minimum length for cookie is 19 */\n\t\tif (remain < 19)\n\t\t\treturn TRUE;", "\t\tStream_Seek(s, 17);\n\t}", "\twhile ((remain = Stream_GetRemainingLength(s)) >= 2)\n\t{\n\t\tStream_Read_UINT16(s, crlf);", "\t\tif (crlf == 0x0A0D)\n\t\t\tbreak;", "\t\tStream_Rewind(s, 1);\n\t}", "\tif (crlf == 0x0A0D)\n\t{\n\t\tStream_Rewind(s, 2);\n\t\tlen = Stream_GetPosition(s) - pos;\n\t\tremain = Stream_GetRemainingLength(s);\n\t\tStream_Write_UINT16(s, 0);", "\t\tif (strnlen((char*)str, len) == len)\n\t\t{\n\t\t\tif (isToken)\n\t\t\t\tresult = nego_set_routing_token(nego, str, len);\n\t\t\telse\n\t\t\t\tresult = nego_set_cookie(nego, (char*)str);\n\t\t}\n\t}", "\tif (!result)\n\t{\n\t\tStream_SetPosition(s, pos);\n\t\tWLog_ERR(TAG, \"invalid %s received\", isToken ? \"routing token\" : \"cookie\");\n\t}\n\telse\n\t{\n\t\tWLog_DBG(TAG, \"received %s [%s]\", isToken ? \"routing token\" : \"cookie\", str);\n\t}", "\treturn result;\n}", "/**\n * Read protocol security negotiation request message.\\n\n * @param nego\n * @param s stream\n */", "BOOL nego_read_request(rdpNego* nego, wStream* s)\n{\n\tBYTE li;\n\tBYTE type;\n\tUINT16 length;", "\tif (!tpkt_read_header(s, &length))\n\t\treturn FALSE;", "\tif (!tpdu_read_connection_request(s, &li, length))\n\t\treturn FALSE;", "\tif (li != Stream_GetRemainingLength(s) + 6)\n\t{\n\t\tWLog_ERR(TAG, \"Incorrect TPDU length indicator.\");\n\t\treturn FALSE;\n\t}", "\tif (!nego_read_request_token_or_cookie(nego, s))\n\t{\n\t\tWLog_ERR(TAG, \"Failed to parse routing token or cookie.\");\n\t\treturn FALSE;\n\t}", "\tif (Stream_GetRemainingLength(s) >= 8)\n\t{\n\t\t/* rdpNegData (optional) */\n\t\tStream_Read_UINT8(s, type); /* Type */", "\t\tif (type != TYPE_RDP_NEG_REQ)\n\t\t{\n\t\t\tWLog_ERR(TAG, \"Incorrect negotiation request type %\" PRIu8 \"\", type);\n\t\t\treturn FALSE;\n\t\t}\n", "\t\tif (!nego_process_negotiation_request(nego, s))\n\t\t\treturn FALSE;", "\t}", "\treturn tpkt_ensure_stream_consumed(s, length);\n}", "/**\n * Send protocol security negotiation message.\n * @param nego\n */", "void nego_send(rdpNego* nego)\n{\n\tif (nego->state == NEGO_STATE_EXT)\n\t\tnego_attempt_ext(nego);\n\telse if (nego->state == NEGO_STATE_NLA)\n\t\tnego_attempt_nla(nego);\n\telse if (nego->state == NEGO_STATE_TLS)\n\t\tnego_attempt_tls(nego);\n\telse if (nego->state == NEGO_STATE_RDP)\n\t\tnego_attempt_rdp(nego);\n\telse\n\t\tWLog_ERR(TAG, \"invalid negotiation state for sending\");\n}", "/**\n * Send RDP Negotiation Request (RDP_NEG_REQ).\\n\n * @msdn{cc240500}\\n\n * @msdn{cc240470}\n * @param nego\n */", "BOOL nego_send_negotiation_request(rdpNego* nego)\n{\n\tBOOL rc = FALSE;\n\twStream* s;\n\tsize_t length;\n\tsize_t bm, em;\n\tBYTE flags = 0;\n\tsize_t cookie_length;\n\ts = Stream_New(NULL, 512);", "\tif (!s)\n\t{\n\t\tWLog_ERR(TAG, \"Stream_New failed!\");\n\t\treturn FALSE;\n\t}", "\tlength = TPDU_CONNECTION_REQUEST_LENGTH;\n\tbm = Stream_GetPosition(s);\n\tStream_Seek(s, length);", "\tif (nego->RoutingToken)\n\t{\n\t\tStream_Write(s, nego->RoutingToken, nego->RoutingTokenLength);", "\t\t/* Ensure Routing Token is correctly terminated - may already be present in string */", "\t\tif ((nego->RoutingTokenLength > 2) &&\n\t\t (nego->RoutingToken[nego->RoutingTokenLength - 2] == 0x0D) &&\n\t\t (nego->RoutingToken[nego->RoutingTokenLength - 1] == 0x0A))\n\t\t{\n\t\t\tWLog_DBG(TAG, \"Routing token looks correctly terminated - use verbatim\");\n\t\t\tlength += nego->RoutingTokenLength;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tWLog_DBG(TAG, \"Adding terminating CRLF to routing token\");\n\t\t\tStream_Write_UINT8(s, 0x0D); /* CR */\n\t\t\tStream_Write_UINT8(s, 0x0A); /* LF */\n\t\t\tlength += nego->RoutingTokenLength + 2;\n\t\t}\n\t}\n\telse if (nego->cookie)\n\t{\n\t\tcookie_length = strlen(nego->cookie);", "\t\tif (cookie_length > nego->CookieMaxLength)\n\t\t\tcookie_length = nego->CookieMaxLength;", "\t\tStream_Write(s, \"Cookie: mstshash=\", 17);\n\t\tStream_Write(s, (BYTE*)nego->cookie, cookie_length);\n\t\tStream_Write_UINT8(s, 0x0D); /* CR */\n\t\tStream_Write_UINT8(s, 0x0A); /* LF */\n\t\tlength += cookie_length + 19;\n\t}", "\tWLog_DBG(TAG, \"RequestedProtocols: %\" PRIu32 \"\", nego->RequestedProtocols);", "\tif ((nego->RequestedProtocols > PROTOCOL_RDP) || (nego->sendNegoData))\n\t{\n\t\t/* RDP_NEG_DATA must be present for TLS and NLA */\n\t\tif (nego->RestrictedAdminModeRequired)\n\t\t\tflags |= RESTRICTED_ADMIN_MODE_REQUIRED;", "\t\tStream_Write_UINT8(s, TYPE_RDP_NEG_REQ);\n\t\tStream_Write_UINT8(s, flags);\n\t\tStream_Write_UINT16(s, 8); /* RDP_NEG_DATA length (8) */\n\t\tStream_Write_UINT32(s, nego->RequestedProtocols); /* requestedProtocols */\n\t\tlength += 8;\n\t}", "\tif (length > UINT16_MAX)\n\t\tgoto fail;", "\tem = Stream_GetPosition(s);\n\tStream_SetPosition(s, bm);\n\ttpkt_write_header(s, (UINT16)length);\n\ttpdu_write_connection_request(s, (UINT16)length - 5);\n\tStream_SetPosition(s, em);\n\tStream_SealLength(s);\n\trc = (transport_write(nego->transport, s) >= 0);\nfail:\n\tStream_Free(s, TRUE);\n\treturn rc;\n}", "/**\n * Process Negotiation Request from Connection Request message.\n * @param nego\n * @param s\n */\n", "BOOL nego_process_negotiation_request(rdpNego* nego, wStream* s)", "{\n\tBYTE flags;\n\tUINT16 length;", "\n\tif (Stream_GetRemainingLength(s) < 7)\n\t\treturn FALSE;", "\tStream_Read_UINT8(s, flags);\n\tStream_Read_UINT16(s, length);\n\tStream_Read_UINT32(s, nego->RequestedProtocols);\n\tWLog_DBG(TAG, \"RDP_NEG_REQ: RequestedProtocol: 0x%08\" PRIX32 \"\", nego->RequestedProtocols);\n\tnego->state = NEGO_STATE_FINAL;", "\treturn TRUE;", "}", "/**\n * Process Negotiation Response from Connection Confirm message.\n * @param nego\n * @param s\n */\n", "BOOL nego_process_negotiation_response(rdpNego* nego, wStream* s)", "{\n\tUINT16 length;\n\tWLog_DBG(TAG, \"RDP_NEG_RSP\");", "\tif (Stream_GetRemainingLength(s) < 7)\n\t{\n\t\tWLog_ERR(TAG, \"Invalid RDP_NEG_RSP\");\n\t\tnego->state = NEGO_STATE_FAIL;", "\t\treturn FALSE;", "\t}", "\tStream_Read_UINT8(s, nego->flags);\n\tStream_Read_UINT16(s, length);\n\tStream_Read_UINT32(s, nego->SelectedProtocol);\n\tnego->state = NEGO_STATE_FINAL;", "\treturn TRUE;", "}", "/**\n * Process Negotiation Failure from Connection Confirm message.\n * @param nego\n * @param s\n */\n", "BOOL nego_process_negotiation_failure(rdpNego* nego, wStream* s)", "{\n\tBYTE flags;\n\tUINT16 length;\n\tUINT32 failureCode;\n\tWLog_DBG(TAG, \"RDP_NEG_FAILURE\");", "\tif (Stream_GetRemainingLength(s) < 7)\n\t\treturn FALSE;", "\tStream_Read_UINT8(s, flags);\n\tStream_Read_UINT16(s, length);\n\tStream_Read_UINT32(s, failureCode);", "\tswitch (failureCode)\n\t{\n\t\tcase SSL_REQUIRED_BY_SERVER:\n\t\t\tWLog_WARN(TAG, \"Error: SSL_REQUIRED_BY_SERVER\");\n\t\t\tbreak;", "\t\tcase SSL_NOT_ALLOWED_BY_SERVER:\n\t\t\tWLog_WARN(TAG, \"Error: SSL_NOT_ALLOWED_BY_SERVER\");\n\t\t\tnego->sendNegoData = TRUE;\n\t\t\tbreak;", "\t\tcase SSL_CERT_NOT_ON_SERVER:\n\t\t\tWLog_ERR(TAG, \"Error: SSL_CERT_NOT_ON_SERVER\");\n\t\t\tnego->sendNegoData = TRUE;\n\t\t\tbreak;", "\t\tcase INCONSISTENT_FLAGS:\n\t\t\tWLog_ERR(TAG, \"Error: INCONSISTENT_FLAGS\");\n\t\t\tbreak;", "\t\tcase HYBRID_REQUIRED_BY_SERVER:\n\t\t\tWLog_WARN(TAG, \"Error: HYBRID_REQUIRED_BY_SERVER\");\n\t\t\tbreak;", "\t\tdefault:\n\t\t\tWLog_ERR(TAG, \"Error: Unknown protocol security error %\" PRIu32 \"\", failureCode);\n\t\t\tbreak;\n\t}", "\tnego->state = NEGO_STATE_FAIL;", "\treturn TRUE;", "}", "/**\n * Send RDP Negotiation Response (RDP_NEG_RSP).\\n\n * @param nego\n */", "BOOL nego_send_negotiation_response(rdpNego* nego)\n{\n\tUINT16 length;\n\tsize_t bm, em;\n\tBOOL status;\n\twStream* s;\n\tBYTE flags;\n\trdpSettings* settings;\n\tstatus = TRUE;\n\tsettings = nego->transport->settings;\n\ts = Stream_New(NULL, 512);", "\tif (!s)\n\t{\n\t\tWLog_ERR(TAG, \"Stream_New failed!\");\n\t\treturn FALSE;\n\t}", "\tlength = TPDU_CONNECTION_CONFIRM_LENGTH;\n\tbm = Stream_GetPosition(s);\n\tStream_Seek(s, length);", "\tif (nego->SelectedProtocol & PROTOCOL_FAILED_NEGO)\n\t{\n\t\tUINT32 errorCode = (nego->SelectedProtocol & ~PROTOCOL_FAILED_NEGO);\n\t\tflags = 0;\n\t\tStream_Write_UINT8(s, TYPE_RDP_NEG_FAILURE);\n\t\tStream_Write_UINT8(s, flags); /* flags */\n\t\tStream_Write_UINT16(s, 8); /* RDP_NEG_DATA length (8) */\n\t\tStream_Write_UINT32(s, errorCode);\n\t\tlength += 8;\n\t\tstatus = FALSE;\n\t}\n\telse\n\t{\n\t\tflags = EXTENDED_CLIENT_DATA_SUPPORTED;", "\t\tif (settings->SupportGraphicsPipeline)\n\t\t\tflags |= DYNVC_GFX_PROTOCOL_SUPPORTED;", "\t\t/* RDP_NEG_DATA must be present for TLS, NLA, and RDP */\n\t\tStream_Write_UINT8(s, TYPE_RDP_NEG_RSP);\n\t\tStream_Write_UINT8(s, flags); /* flags */\n\t\tStream_Write_UINT16(s, 8); /* RDP_NEG_DATA length (8) */\n\t\tStream_Write_UINT32(s, nego->SelectedProtocol); /* selectedProtocol */\n\t\tlength += 8;\n\t}", "\tem = Stream_GetPosition(s);\n\tStream_SetPosition(s, bm);\n\ttpkt_write_header(s, length);\n\ttpdu_write_connection_confirm(s, length - 5);\n\tStream_SetPosition(s, em);\n\tStream_SealLength(s);", "\tif (transport_write(nego->transport, s) < 0)\n\t{\n\t\tStream_Free(s, TRUE);\n\t\treturn FALSE;\n\t}", "\tStream_Free(s, TRUE);", "\tif (status)\n\t{\n\t\t/* update settings with negotiated protocol security */\n\t\tsettings->RequestedProtocols = nego->RequestedProtocols;\n\t\tsettings->SelectedProtocol = nego->SelectedProtocol;", "\t\tif (settings->SelectedProtocol == PROTOCOL_RDP)\n\t\t{\n\t\t\tsettings->TlsSecurity = FALSE;\n\t\t\tsettings->NlaSecurity = FALSE;\n\t\t\tsettings->RdpSecurity = TRUE;\n\t\t\tsettings->UseRdpSecurityLayer = TRUE;", "\t\t\tif (settings->EncryptionLevel == ENCRYPTION_LEVEL_NONE)\n\t\t\t{\n\t\t\t\t/**\n\t\t\t\t * If the server implementation did not explicitely set a\n\t\t\t\t * encryption level we default to client compatible\n\t\t\t\t */\n\t\t\t\tsettings->EncryptionLevel = ENCRYPTION_LEVEL_CLIENT_COMPATIBLE;\n\t\t\t}", "\t\t\tif (settings->LocalConnection)\n\t\t\t{\n\t\t\t\t/**\n\t\t\t\t * Note: This hack was firstly introduced in commit 95f5e115 to\n\t\t\t\t * disable the unnecessary encryption with peers connecting to\n\t\t\t\t * 127.0.0.1 or local unix sockets.\n\t\t\t\t * This also affects connections via port tunnels! (e.g. ssh -L)\n\t\t\t\t */\n\t\t\t\tWLog_INFO(TAG, \"Turning off encryption for local peer with standard rdp security\");\n\t\t\t\tsettings->UseRdpSecurityLayer = FALSE;\n\t\t\t\tsettings->EncryptionLevel = ENCRYPTION_LEVEL_NONE;\n\t\t\t}", "\t\t\tif (!settings->RdpServerRsaKey && !settings->RdpKeyFile && !settings->RdpKeyContent)\n\t\t\t{\n\t\t\t\tWLog_ERR(TAG, \"Missing server certificate\");\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t}\n\t\telse if (settings->SelectedProtocol == PROTOCOL_SSL)\n\t\t{\n\t\t\tsettings->TlsSecurity = TRUE;\n\t\t\tsettings->NlaSecurity = FALSE;\n\t\t\tsettings->RdpSecurity = FALSE;\n\t\t\tsettings->UseRdpSecurityLayer = FALSE;\n\t\t\tsettings->EncryptionLevel = ENCRYPTION_LEVEL_NONE;\n\t\t}\n\t\telse if (settings->SelectedProtocol == PROTOCOL_HYBRID)\n\t\t{\n\t\t\tsettings->TlsSecurity = TRUE;\n\t\t\tsettings->NlaSecurity = TRUE;\n\t\t\tsettings->RdpSecurity = FALSE;\n\t\t\tsettings->UseRdpSecurityLayer = FALSE;\n\t\t\tsettings->EncryptionLevel = ENCRYPTION_LEVEL_NONE;\n\t\t}\n\t}", "\treturn status;\n}", "/**\n * Initialize NEGO state machine.\n * @param nego\n */", "void nego_init(rdpNego* nego)\n{\n\tnego->state = NEGO_STATE_INITIAL;\n\tnego->RequestedProtocols = PROTOCOL_RDP;\n\tnego->CookieMaxLength = DEFAULT_COOKIE_MAX_LENGTH;\n\tnego->sendNegoData = FALSE;\n\tnego->flags = 0;\n}", "/**\n * Create a new NEGO state machine instance.\n * @param transport\n * @return\n */", "rdpNego* nego_new(rdpTransport* transport)\n{\n\trdpNego* nego = (rdpNego*)calloc(1, sizeof(rdpNego));", "\tif (!nego)\n\t\treturn NULL;", "\tnego->transport = transport;\n\tnego_init(nego);\n\treturn nego;\n}", "/**\n * Free NEGO state machine.\n * @param nego\n */", "void nego_free(rdpNego* nego)\n{\n\tif (nego)\n\t{\n\t\tfree(nego->RoutingToken);\n\t\tfree(nego->cookie);\n\t\tfree(nego);\n\t}\n}", "/**\n * Set target hostname and port.\n * @param nego\n * @param hostname\n * @param port\n */", "BOOL nego_set_target(rdpNego* nego, const char* hostname, UINT16 port)\n{\n\tif (!nego || !hostname)\n\t\treturn FALSE;", "\tnego->hostname = hostname;\n\tnego->port = port;\n\treturn TRUE;\n}", "/**\n * Enable security layer negotiation.\n * @param nego pointer to the negotiation structure\n * @param enable_rdp whether to enable security layer negotiation (TRUE for enabled, FALSE for\n * disabled)\n */", "void nego_set_negotiation_enabled(rdpNego* nego, BOOL NegotiateSecurityLayer)\n{\n\tWLog_DBG(TAG, \"Enabling security layer negotiation: %s\",\n\t NegotiateSecurityLayer ? \"TRUE\" : \"FALSE\");\n\tnego->NegotiateSecurityLayer = NegotiateSecurityLayer;\n}", "/**\n * Enable restricted admin mode.\n * @param nego pointer to the negotiation structure\n * @param enable_restricted whether to enable security layer negotiation (TRUE for enabled, FALSE\n * for disabled)\n */", "void nego_set_restricted_admin_mode_required(rdpNego* nego, BOOL RestrictedAdminModeRequired)\n{\n\tWLog_DBG(TAG, \"Enabling restricted admin mode: %s\",\n\t RestrictedAdminModeRequired ? \"TRUE\" : \"FALSE\");\n\tnego->RestrictedAdminModeRequired = RestrictedAdminModeRequired;\n}", "void nego_set_gateway_enabled(rdpNego* nego, BOOL GatewayEnabled)\n{\n\tnego->GatewayEnabled = GatewayEnabled;\n}", "void nego_set_gateway_bypass_local(rdpNego* nego, BOOL GatewayBypassLocal)\n{\n\tnego->GatewayBypassLocal = GatewayBypassLocal;\n}", "/**\n * Enable RDP security protocol.\n * @param nego pointer to the negotiation structure\n * @param enable_rdp whether to enable normal RDP protocol (TRUE for enabled, FALSE for disabled)\n */", "void nego_enable_rdp(rdpNego* nego, BOOL enable_rdp)\n{\n\tWLog_DBG(TAG, \"Enabling RDP security: %s\", enable_rdp ? \"TRUE\" : \"FALSE\");\n\tnego->EnabledProtocols[PROTOCOL_RDP] = enable_rdp;\n}", "/**\n * Enable TLS security protocol.\n * @param nego pointer to the negotiation structure\n * @param enable_tls whether to enable TLS + RDP protocol (TRUE for enabled, FALSE for disabled)\n */", "void nego_enable_tls(rdpNego* nego, BOOL enable_tls)\n{\n\tWLog_DBG(TAG, \"Enabling TLS security: %s\", enable_tls ? \"TRUE\" : \"FALSE\");\n\tnego->EnabledProtocols[PROTOCOL_SSL] = enable_tls;\n}", "/**\n * Enable NLA security protocol.\n * @param nego pointer to the negotiation structure\n * @param enable_nla whether to enable network level authentication protocol (TRUE for enabled,\n * FALSE for disabled)\n */", "void nego_enable_nla(rdpNego* nego, BOOL enable_nla)\n{\n\tWLog_DBG(TAG, \"Enabling NLA security: %s\", enable_nla ? \"TRUE\" : \"FALSE\");\n\tnego->EnabledProtocols[PROTOCOL_HYBRID] = enable_nla;\n}", "/**\n * Enable NLA extended security protocol.\n * @param nego pointer to the negotiation structure\n * @param enable_ext whether to enable network level authentication extended protocol (TRUE for\n * enabled, FALSE for disabled)\n */", "void nego_enable_ext(rdpNego* nego, BOOL enable_ext)\n{\n\tWLog_DBG(TAG, \"Enabling NLA extended security: %s\", enable_ext ? \"TRUE\" : \"FALSE\");\n\tnego->EnabledProtocols[PROTOCOL_HYBRID_EX] = enable_ext;\n}", "/**\n * Set routing token.\n * @param nego\n * @param RoutingToken\n * @param RoutingTokenLength\n */", "BOOL nego_set_routing_token(rdpNego* nego, BYTE* RoutingToken, DWORD RoutingTokenLength)\n{\n\tif (RoutingTokenLength == 0)\n\t\treturn FALSE;", "\tfree(nego->RoutingToken);\n\tnego->RoutingTokenLength = RoutingTokenLength;\n\tnego->RoutingToken = (BYTE*)malloc(nego->RoutingTokenLength);", "\tif (!nego->RoutingToken)\n\t\treturn FALSE;", "\tCopyMemory(nego->RoutingToken, RoutingToken, nego->RoutingTokenLength);\n\treturn TRUE;\n}", "/**\n * Set cookie.\n * @param nego\n * @param cookie\n */", "BOOL nego_set_cookie(rdpNego* nego, char* cookie)\n{\n\tif (nego->cookie)\n\t{\n\t\tfree(nego->cookie);\n\t\tnego->cookie = NULL;\n\t}", "\tif (!cookie)\n\t\treturn TRUE;", "\tnego->cookie = _strdup(cookie);", "\tif (!nego->cookie)\n\t\treturn FALSE;", "\treturn TRUE;\n}", "/**\n * Set cookie maximum length\n * @param nego\n * @param CookieMaxLength\n */", "void nego_set_cookie_max_length(rdpNego* nego, UINT32 CookieMaxLength)\n{\n\tnego->CookieMaxLength = CookieMaxLength;\n}", "/**\n * Enable / disable preconnection PDU.\n * @param nego\n * @param send_pcpdu\n */", "void nego_set_send_preconnection_pdu(rdpNego* nego, BOOL SendPreconnectionPdu)\n{\n\tnego->SendPreconnectionPdu = SendPreconnectionPdu;\n}", "/**\n * Set preconnection id.\n * @param nego\n * @param id\n */", "void nego_set_preconnection_id(rdpNego* nego, UINT32 PreconnectionId)\n{\n\tnego->PreconnectionId = PreconnectionId;\n}", "/**\n * Set preconnection blob.\n * @param nego\n * @param blob\n */", "void nego_set_preconnection_blob(rdpNego* nego, char* PreconnectionBlob)\n{\n\tnego->PreconnectionBlob = PreconnectionBlob;\n}", "UINT32 nego_get_selected_protocol(rdpNego* nego)\n{\n\tif (!nego)\n\t\treturn 0;", "\treturn nego->SelectedProtocol;\n}", "BOOL nego_set_selected_protocol(rdpNego* nego, UINT32 SelectedProtocol)\n{\n\tif (!nego)\n\t\treturn FALSE;", "\tnego->SelectedProtocol = SelectedProtocol;\n\treturn TRUE;\n}", "UINT32 nego_get_requested_protocols(rdpNego* nego)\n{\n\tif (!nego)\n\t\treturn 0;", "\treturn nego->RequestedProtocols;\n}", "BOOL nego_set_requested_protocols(rdpNego* nego, UINT32 RequestedProtocols)\n{\n\tif (!nego)\n\t\treturn FALSE;", "\tnego->RequestedProtocols = RequestedProtocols;\n\treturn TRUE;\n}", "NEGO_STATE nego_get_state(rdpNego* nego)\n{\n\tif (!nego)\n\t\treturn NEGO_STATE_FAIL;", "\treturn nego->state;\n}", "BOOL nego_set_state(rdpNego* nego, NEGO_STATE state)\n{\n\tif (!nego)\n\t\treturn FALSE;", "\tnego->state = state;\n\treturn TRUE;\n}", "SEC_WINNT_AUTH_IDENTITY* nego_get_identity(rdpNego* nego)\n{\n\tif (!nego)\n\t\treturn NULL;", "\treturn nla_get_identity(nego->transport->nla);\n}", "void nego_free_nla(rdpNego* nego)\n{\n\tif (!nego || !nego->transport)\n\t\treturn;", "\tnla_free(nego->transport->nla);\n\tnego->transport->nla = NULL;\n}", "const BYTE* nego_get_routing_token(rdpNego* nego, DWORD* RoutingTokenLength)\n{\n\tif (!nego)\n\t\treturn NULL;\n\tif (RoutingTokenLength)\n\t\t*RoutingTokenLength = nego->RoutingTokenLength;\n\treturn nego->RoutingToken;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [357, 496, 447, 322, 308, 1001], "buggy_code_start_loc": [333, 480, 447, 145, 307, 94], "filenames": ["channels/drive/client/drive_main.c", "channels/printer/client/printer_main.c", "channels/rdpei/client/rdpei_main.c", "channels/serial/client/serial_main.c", "libfreerdp/core/gateway/rdg.c", "libfreerdp/core/nego.c"], "fixing_code_end_loc": [361, 502, 451, 327, 309, 1013], "fixing_code_start_loc": [334, 481, 448, 145, 307, 94], "message": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:freerdp:freerdp:*:*:*:*:*:*:*:*", "matchCriteriaId": "5C5F8D57-1D22-42B4-9E08-9131F7BE8FA5", "versionEndExcluding": "2.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "B620311B-34A3-48A6-82DF-6F078D7A4493", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In FreeRDP before 2.1.0, there is an out-of-bound read in irp functions (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). This has been fixed in 2.1.0."}, {"lang": "es", "value": "En FreeRDP versiones anteriores a 2.1.0, se presenta una lectura fuera de l\u00edmite en las funciones de irp (parallel_process_irp_create, serial_process_irp_create, drive_process_irp_write, printer_process_irp_write, rdpei_recv_pdu, serial_process_irp_write). Esto ha sido corregido en la versi\u00f3n 2.1.0."}], "evaluatorComment": null, "id": "CVE-2020-11089", "lastModified": "2022-07-19T11:52:15.420", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:L/I:L/A:L", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:R/S:U/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 2.5, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-05-29T20:15:11.017", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2020-07/msg00080.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/commit/795842f4096501fcefc1a7f535ccc8132feb31d7"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/FreeRDP/FreeRDP/security/advisories/GHSA-hfc7-c5gv-8c2h"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-125"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/FreeRDP/FreeRDP/commit/6b485b146a1b9d6ce72dfd7b5f36456c166e7a16"}, "type": "CWE-125"}
320
Determine whether the {function_name} code is vulnerable or not.
[ "/************************************************************\n * Copyright (c) 1994 by Silicon Graphics Computer Systems, Inc.\n *\n * Permission to use, copy, modify, and distribute this\n * software and its documentation for any purpose and without\n * fee is hereby granted, provided that the above copyright\n * notice appear in all copies and that both that copyright\n * notice and this permission notice appear in supporting\n * documentation, and that the name of Silicon Graphics not be\n * used in advertising or publicity pertaining to distribution\n * of the software without specific prior written permission.\n * Silicon Graphics makes no representation about the suitability\n * of this software for any purpose. It is provided \"as is\"\n * without any express or implied warranty.\n *\n * SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS\n * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n * AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON\n * GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\n * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,\n * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE\n * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH\n * THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n ********************************************************/", "/*\n * Copyright © 2012 Intel Corporation\n * Copyright © 2012 Ran Benita <ran234@gmail.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\n * Author: Daniel Stone <daniel@fooishbar.org>\n * Ran Benita <ran234@gmail.com>\n */", "#include \"xkbcomp-priv.h\"\n#include \"ast-build.h\"\n#include \"include.h\"", "ParseCommon *\nAppendStmt(ParseCommon *to, ParseCommon *append)\n{\n ParseCommon *iter;", " if (!to)\n return append;", " for (iter = to; iter->next; iter = iter->next);", " iter->next = append;\n return to;\n}", "static ExprDef *\nExprCreate(enum expr_op_type op, enum expr_value_type type, size_t size)\n{\n ExprDef *expr = malloc(size);\n if (!expr)\n return NULL;", " expr->common.type = STMT_EXPR;\n expr->common.next = NULL;\n expr->expr.op = op;\n expr->expr.value_type = type;", " return expr;\n}", "#define EXPR_CREATE(type_, name_, op_, value_type_) \\\n ExprDef *name_ = ExprCreate(op_, value_type_, sizeof(type_)); \\\n if (!name_) \\\n return NULL;", "ExprDef *\nExprCreateString(xkb_atom_t str)\n{\n EXPR_CREATE(ExprString, expr, EXPR_VALUE, EXPR_TYPE_STRING);\n expr->string.str = str;\n return expr;\n}", "ExprDef *\nExprCreateInteger(int ival)\n{\n EXPR_CREATE(ExprInteger, expr, EXPR_VALUE, EXPR_TYPE_INT);\n expr->integer.ival = ival;\n return expr;\n}", "ExprDef *", "", "ExprCreateBoolean(bool set)\n{\n EXPR_CREATE(ExprBoolean, expr, EXPR_VALUE, EXPR_TYPE_BOOLEAN);\n expr->boolean.set = set;\n return expr;\n}", "ExprDef *\nExprCreateKeyName(xkb_atom_t key_name)\n{\n EXPR_CREATE(ExprKeyName, expr, EXPR_VALUE, EXPR_TYPE_KEYNAME);\n expr->key_name.key_name = key_name;\n return expr;\n}", "ExprDef *\nExprCreateIdent(xkb_atom_t ident)\n{\n EXPR_CREATE(ExprIdent, expr, EXPR_IDENT, EXPR_TYPE_UNKNOWN);\n expr->ident.ident = ident;\n return expr;\n}", "ExprDef *\nExprCreateUnary(enum expr_op_type op, enum expr_value_type type,\n ExprDef *child)\n{\n EXPR_CREATE(ExprUnary, expr, op, type);\n expr->unary.child = child;\n return expr;\n}", "ExprDef *\nExprCreateBinary(enum expr_op_type op, ExprDef *left, ExprDef *right)\n{\n EXPR_CREATE(ExprBinary, expr, op, EXPR_TYPE_UNKNOWN);", " if (op == EXPR_ASSIGN || left->expr.value_type == EXPR_TYPE_UNKNOWN)\n expr->expr.value_type = right->expr.value_type;\n else if (left->expr.value_type == right->expr.value_type ||\n right->expr.value_type == EXPR_TYPE_UNKNOWN)\n expr->expr.value_type = left->expr.value_type;\n expr->binary.left = left;\n expr->binary.right = right;", " return expr;\n}", "ExprDef *\nExprCreateFieldRef(xkb_atom_t element, xkb_atom_t field)\n{\n EXPR_CREATE(ExprFieldRef, expr, EXPR_FIELD_REF, EXPR_TYPE_UNKNOWN);\n expr->field_ref.element = element;\n expr->field_ref.field = field;\n return expr;\n}", "ExprDef *\nExprCreateArrayRef(xkb_atom_t element, xkb_atom_t field, ExprDef *entry)\n{\n EXPR_CREATE(ExprArrayRef, expr, EXPR_ARRAY_REF, EXPR_TYPE_UNKNOWN);\n expr->array_ref.element = element;\n expr->array_ref.field = field;\n expr->array_ref.entry = entry;\n return expr;\n}", "ExprDef *\nExprCreateAction(xkb_atom_t name, ExprDef *args)\n{\n EXPR_CREATE(ExprAction, expr, EXPR_ACTION_DECL, EXPR_TYPE_UNKNOWN);\n expr->action.name = name;\n expr->action.args = args;\n return expr;\n}", "ExprDef *\nExprCreateKeysymList(xkb_keysym_t sym)\n{\n EXPR_CREATE(ExprKeysymList, expr, EXPR_KEYSYM_LIST, EXPR_TYPE_SYMBOLS);", " darray_init(expr->keysym_list.syms);\n darray_init(expr->keysym_list.symsMapIndex);\n darray_init(expr->keysym_list.symsNumEntries);", " darray_append(expr->keysym_list.syms, sym);\n darray_append(expr->keysym_list.symsMapIndex, 0);\n darray_append(expr->keysym_list.symsNumEntries, 1);", " return expr;\n}", "ExprDef *\nExprCreateMultiKeysymList(ExprDef *expr)\n{\n unsigned nLevels = darray_size(expr->keysym_list.symsMapIndex);", " darray_resize(expr->keysym_list.symsMapIndex, 1);\n darray_resize(expr->keysym_list.symsNumEntries, 1);\n darray_item(expr->keysym_list.symsMapIndex, 0) = 0;\n darray_item(expr->keysym_list.symsNumEntries, 0) = nLevels;", " return expr;\n}", "ExprDef *\nExprAppendKeysymList(ExprDef *expr, xkb_keysym_t sym)\n{\n unsigned nSyms = darray_size(expr->keysym_list.syms);", " darray_append(expr->keysym_list.symsMapIndex, nSyms);\n darray_append(expr->keysym_list.symsNumEntries, 1);\n darray_append(expr->keysym_list.syms, sym);", " return expr;\n}", "ExprDef *\nExprAppendMultiKeysymList(ExprDef *expr, ExprDef *append)\n{\n unsigned nSyms = darray_size(expr->keysym_list.syms);\n unsigned numEntries = darray_size(append->keysym_list.syms);", " darray_append(expr->keysym_list.symsMapIndex, nSyms);\n darray_append(expr->keysym_list.symsNumEntries, numEntries);\n darray_concat(expr->keysym_list.syms, append->keysym_list.syms);", " FreeStmt((ParseCommon *) &append);", " return expr;\n}", "KeycodeDef *\nKeycodeCreate(xkb_atom_t name, int64_t value)\n{\n KeycodeDef *def = malloc(sizeof(*def));\n if (!def)\n return NULL;", " def->common.type = STMT_KEYCODE;\n def->common.next = NULL;\n def->name = name;\n def->value = value;", " return def;\n}", "KeyAliasDef *\nKeyAliasCreate(xkb_atom_t alias, xkb_atom_t real)\n{\n KeyAliasDef *def = malloc(sizeof(*def));\n if (!def)\n return NULL;", " def->common.type = STMT_ALIAS;\n def->common.next = NULL;\n def->alias = alias;\n def->real = real;", " return def;\n}", "VModDef *\nVModCreate(xkb_atom_t name, ExprDef *value)\n{\n VModDef *def = malloc(sizeof(*def));\n if (!def)\n return NULL;", " def->common.type = STMT_VMOD;\n def->common.next = NULL;\n def->name = name;\n def->value = value;", " return def;\n}", "VarDef *\nVarCreate(ExprDef *name, ExprDef *value)\n{\n VarDef *def = malloc(sizeof(*def));\n if (!def)\n return NULL;", " def->common.type = STMT_VAR;\n def->common.next = NULL;\n def->name = name;\n def->value = value;", " return def;\n}", "VarDef *\nBoolVarCreate(xkb_atom_t ident, bool set)\n{\n ExprDef *name, *value;\n VarDef *def;\n if (!(name = ExprCreateIdent(ident))) {\n return NULL;\n }\n if (!(value = ExprCreateBoolean(set))) {\n FreeStmt((ParseCommon *) name);\n return NULL;\n }\n if (!(def = VarCreate(name, value))) {\n FreeStmt((ParseCommon *) name);\n FreeStmt((ParseCommon *) value);\n return NULL;\n }\n return def;\n}", "InterpDef *\nInterpCreate(xkb_keysym_t sym, ExprDef *match)\n{\n InterpDef *def = malloc(sizeof(*def));\n if (!def)\n return NULL;", " def->common.type = STMT_INTERP;\n def->common.next = NULL;\n def->sym = sym;\n def->match = match;\n def->def = NULL;", " return def;\n}", "KeyTypeDef *\nKeyTypeCreate(xkb_atom_t name, VarDef *body)\n{\n KeyTypeDef *def = malloc(sizeof(*def));\n if (!def)\n return NULL;", " def->common.type = STMT_TYPE;\n def->common.next = NULL;\n def->merge = MERGE_DEFAULT;\n def->name = name;\n def->body = body;", " return def;\n}", "SymbolsDef *\nSymbolsCreate(xkb_atom_t keyName, VarDef *symbols)\n{\n SymbolsDef *def = malloc(sizeof(*def));\n if (!def)\n return NULL;", " def->common.type = STMT_SYMBOLS;\n def->common.next = NULL;\n def->merge = MERGE_DEFAULT;\n def->keyName = keyName;\n def->symbols = symbols;", " return def;\n}", "GroupCompatDef *\nGroupCompatCreate(unsigned group, ExprDef *val)\n{\n GroupCompatDef *def = malloc(sizeof(*def));\n if (!def)\n return NULL;", " def->common.type = STMT_GROUP_COMPAT;\n def->common.next = NULL;\n def->merge = MERGE_DEFAULT;\n def->group = group;\n def->def = val;", " return def;\n}", "ModMapDef *\nModMapCreate(xkb_atom_t modifier, ExprDef *keys)\n{\n ModMapDef *def = malloc(sizeof(*def));\n if (!def)\n return NULL;", " def->common.type = STMT_MODMAP;\n def->common.next = NULL;\n def->merge = MERGE_DEFAULT;\n def->modifier = modifier;\n def->keys = keys;", " return def;\n}", "LedMapDef *\nLedMapCreate(xkb_atom_t name, VarDef *body)\n{\n LedMapDef *def = malloc(sizeof(*def));\n if (!def)\n return NULL;", " def->common.type = STMT_LED_MAP;\n def->common.next = NULL;\n def->merge = MERGE_DEFAULT;\n def->name = name;\n def->body = body;", " return def;\n}", "LedNameDef *\nLedNameCreate(unsigned ndx, ExprDef *name, bool virtual)\n{\n LedNameDef *def = malloc(sizeof(*def));\n if (!def)\n return NULL;", " def->common.type = STMT_LED_NAME;\n def->common.next = NULL;\n def->merge = MERGE_DEFAULT;\n def->ndx = ndx;\n def->name = name;\n def->virtual = virtual;", " return def;\n}", "static void\nFreeInclude(IncludeStmt *incl);", "IncludeStmt *\nIncludeCreate(struct xkb_context *ctx, char *str, enum merge_mode merge)\n{\n IncludeStmt *incl, *first;\n char *file, *map, *stmt, *tmp, *extra_data;\n char nextop;", " incl = first = NULL;\n file = map = NULL;\n tmp = str;\n stmt = strdup_safe(str);\n while (tmp && *tmp)\n {\n if (!ParseIncludeMap(&tmp, &file, &map, &nextop, &extra_data))\n goto err;", " /*\n * Given an RMLVO (here layout) like 'us,,fr', the rules parser\n * will give out something like 'pc+us+:2+fr:3+inet(evdev)'.\n * We should just skip the ':2' in this case and leave it to the\n * appropriate section to deal with the empty group.\n */\n if (isempty(file)) {\n free(file);\n free(map);\n free(extra_data);\n continue;\n }", " if (first == NULL) {\n first = incl = malloc(sizeof(*first));\n } else {\n incl->next_incl = malloc(sizeof(*first));\n incl = incl->next_incl;\n }", " if (!incl)\n break;", " incl->common.type = STMT_INCLUDE;\n incl->common.next = NULL;\n incl->merge = merge;\n incl->stmt = NULL;\n incl->file = file;\n incl->map = map;\n incl->modifier = extra_data;\n incl->next_incl = NULL;", " if (nextop == '|')\n merge = MERGE_AUGMENT;\n else\n merge = MERGE_OVERRIDE;\n }", " if (first)\n first->stmt = stmt;\n else\n free(stmt);", " return first;", "err:\n log_err(ctx, \"Illegal include statement \\\"%s\\\"; Ignored\\n\", stmt);\n FreeInclude(first);\n free(stmt);\n return NULL;\n}", "XkbFile *\nXkbFileCreate(enum xkb_file_type type, char *name, ParseCommon *defs,\n enum xkb_map_flags flags)\n{\n XkbFile *file;", " file = calloc(1, sizeof(*file));\n if (!file)\n return NULL;", " XkbEscapeMapName(name);\n file->file_type = type;\n file->name = name ? name : strdup(\"(unnamed)\");\n file->defs = defs;\n file->flags = flags;", " return file;\n}", "XkbFile *\nXkbFileFromComponents(struct xkb_context *ctx,\n const struct xkb_component_names *kkctgs)\n{\n char *const components[] = {\n kkctgs->keycodes, kkctgs->types,\n kkctgs->compat, kkctgs->symbols,\n };\n enum xkb_file_type type;\n IncludeStmt *include = NULL;\n XkbFile *file = NULL;\n ParseCommon *defs = NULL;", " for (type = FIRST_KEYMAP_FILE_TYPE; type <= LAST_KEYMAP_FILE_TYPE; type++) {\n include = IncludeCreate(ctx, components[type], MERGE_DEFAULT);\n if (!include)\n goto err;", " file = XkbFileCreate(type, NULL, (ParseCommon *) include, 0);\n if (!file) {\n FreeInclude(include);\n goto err;\n }", " defs = AppendStmt(defs, &file->common);\n }", " file = XkbFileCreate(FILE_TYPE_KEYMAP, NULL, defs, 0);\n if (!file)\n goto err;", " return file;", "err:\n FreeXkbFile((XkbFile *) defs);\n return NULL;\n}", "static void\nFreeExpr(ExprDef *expr)\n{\n if (!expr)\n return;", " switch (expr->expr.op) {\n case EXPR_ACTION_LIST:\n case EXPR_NEGATE:\n case EXPR_UNARY_PLUS:\n case EXPR_NOT:\n case EXPR_INVERT:\n FreeStmt((ParseCommon *) expr->unary.child);\n break;", " case EXPR_DIVIDE:\n case EXPR_ADD:\n case EXPR_SUBTRACT:\n case EXPR_MULTIPLY:\n case EXPR_ASSIGN:\n FreeStmt((ParseCommon *) expr->binary.left);\n FreeStmt((ParseCommon *) expr->binary.right);\n break;", " case EXPR_ACTION_DECL:\n FreeStmt((ParseCommon *) expr->action.args);\n break;", " case EXPR_ARRAY_REF:\n FreeStmt((ParseCommon *) expr->array_ref.entry);\n break;", " case EXPR_KEYSYM_LIST:\n darray_free(expr->keysym_list.syms);\n darray_free(expr->keysym_list.symsMapIndex);\n darray_free(expr->keysym_list.symsNumEntries);\n break;", " default:\n break;\n }\n}", "static void\nFreeInclude(IncludeStmt *incl)\n{\n IncludeStmt *next;", " while (incl)\n {\n next = incl->next_incl;", " free(incl->file);\n free(incl->map);\n free(incl->modifier);\n free(incl->stmt);", " free(incl);\n incl = next;\n }\n}", "void\nFreeStmt(ParseCommon *stmt)\n{\n ParseCommon *next;", " while (stmt)\n {\n next = stmt->next;", " switch (stmt->type) {\n case STMT_INCLUDE:\n FreeInclude((IncludeStmt *) stmt);\n /* stmt is already free'd here. */\n stmt = NULL;\n break;\n case STMT_EXPR:\n FreeExpr((ExprDef *) stmt);\n break;\n case STMT_VAR:\n FreeStmt((ParseCommon *) ((VarDef *) stmt)->name);\n FreeStmt((ParseCommon *) ((VarDef *) stmt)->value);\n break;\n case STMT_TYPE:\n FreeStmt((ParseCommon *) ((KeyTypeDef *) stmt)->body);\n break;\n case STMT_INTERP:\n FreeStmt((ParseCommon *) ((InterpDef *) stmt)->match);\n FreeStmt((ParseCommon *) ((InterpDef *) stmt)->def);\n break;\n case STMT_VMOD:\n FreeStmt((ParseCommon *) ((VModDef *) stmt)->value);\n break;\n case STMT_SYMBOLS:\n FreeStmt((ParseCommon *) ((SymbolsDef *) stmt)->symbols);\n break;\n case STMT_MODMAP:\n FreeStmt((ParseCommon *) ((ModMapDef *) stmt)->keys);\n break;\n case STMT_GROUP_COMPAT:\n FreeStmt((ParseCommon *) ((GroupCompatDef *) stmt)->def);\n break;\n case STMT_LED_MAP:\n FreeStmt((ParseCommon *) ((LedMapDef *) stmt)->body);\n break;\n case STMT_LED_NAME:\n FreeStmt((ParseCommon *) ((LedNameDef *) stmt)->name);\n break;\n default:\n break;\n }", " free(stmt);\n stmt = next;\n }\n}", "void\nFreeXkbFile(XkbFile *file)\n{\n XkbFile *next;", " while (file)\n {\n next = (XkbFile *) file->common.next;", " switch (file->file_type) {\n case FILE_TYPE_KEYMAP:\n FreeXkbFile((XkbFile *) file->defs);\n break;", " case FILE_TYPE_TYPES:\n case FILE_TYPE_COMPAT:\n case FILE_TYPE_SYMBOLS:\n case FILE_TYPE_KEYCODES:\n case FILE_TYPE_GEOMETRY:\n FreeStmt(file->defs);\n break;", " default:\n break;\n }", " free(file->name);\n free(file);\n file = next;\n }\n}", "static const char *xkb_file_type_strings[_FILE_TYPE_NUM_ENTRIES] = {\n [FILE_TYPE_KEYCODES] = \"xkb_keycodes\",\n [FILE_TYPE_TYPES] = \"xkb_types\",\n [FILE_TYPE_COMPAT] = \"xkb_compatibility\",\n [FILE_TYPE_SYMBOLS] = \"xkb_symbols\",\n [FILE_TYPE_GEOMETRY] = \"xkb_geometry\",\n [FILE_TYPE_KEYMAP] = \"xkb_keymap\",\n [FILE_TYPE_RULES] = \"rules\",\n};", "const char *\nxkb_file_type_to_string(enum xkb_file_type type)\n{\n if (type > _FILE_TYPE_NUM_ENTRIES)\n return \"unknown\";\n return xkb_file_type_strings[type];\n}", "static const char *stmt_type_strings[_STMT_NUM_VALUES] = {\n [STMT_UNKNOWN] = \"unknown statement\",\n [STMT_INCLUDE] = \"include statement\",\n [STMT_KEYCODE] = \"key name definition\",\n [STMT_ALIAS] = \"key alias definition\",\n [STMT_EXPR] = \"expression\",\n [STMT_VAR] = \"variable definition\",\n [STMT_TYPE] = \"key type definition\",\n [STMT_INTERP] = \"symbol interpretation definition\",\n [STMT_VMOD] = \"virtual modifiers definition\",\n [STMT_SYMBOLS] = \"key symbols definition\",\n [STMT_MODMAP] = \"modifier map declaration\",\n [STMT_GROUP_COMPAT] = \"group declaration\",\n [STMT_LED_MAP] = \"indicator map declaration\",\n [STMT_LED_NAME] = \"indicator name declaration\",\n};", "const char *\nstmt_type_to_string(enum stmt_type type)\n{\n if (type >= _STMT_NUM_VALUES)\n return NULL;\n return stmt_type_strings[type];\n}", "static const char *expr_op_type_strings[_EXPR_NUM_VALUES] = {\n [EXPR_VALUE] = \"literal\",\n [EXPR_IDENT] = \"identifier\",\n [EXPR_ACTION_DECL] = \"action declaration\",\n [EXPR_FIELD_REF] = \"field reference\",\n [EXPR_ARRAY_REF] = \"array reference\",\n [EXPR_KEYSYM_LIST] = \"list of keysyms\",\n [EXPR_ACTION_LIST] = \"list of actions\",\n [EXPR_ADD] = \"addition\",\n [EXPR_SUBTRACT] = \"subtraction\",\n [EXPR_MULTIPLY] = \"multiplication\",\n [EXPR_DIVIDE] = \"division\",\n [EXPR_ASSIGN] = \"assignment\",\n [EXPR_NOT] = \"logical negation\",\n [EXPR_NEGATE] = \"arithmetic negation\",\n [EXPR_INVERT] = \"bitwise inversion\",\n [EXPR_UNARY_PLUS] = \"unary plus\",\n};", "const char *\nexpr_op_type_to_string(enum expr_op_type type)\n{\n if (type >= _EXPR_NUM_VALUES)\n return NULL;\n return expr_op_type_strings[type];\n}", "static const char *expr_value_type_strings[_EXPR_TYPE_NUM_VALUES] = {\n [EXPR_TYPE_UNKNOWN] = \"unknown\",\n [EXPR_TYPE_BOOLEAN] = \"boolean\",\n [EXPR_TYPE_INT] = \"int\",", "", " [EXPR_TYPE_STRING] = \"string\",\n [EXPR_TYPE_ACTION] = \"action\",\n [EXPR_TYPE_KEYNAME] = \"keyname\",\n [EXPR_TYPE_SYMBOLS] = \"symbols\",\n};", "const char *\nexpr_value_type_to_string(enum expr_value_type type)\n{\n if (type >= _EXPR_TYPE_NUM_VALUES)\n return NULL;\n return expr_value_type_strings[type];\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [785, 37, 190, 691], "buggy_code_start_loc": [108, 37, 97, 594], "filenames": ["src/xkbcomp/ast-build.c", "src/xkbcomp/ast-build.h", "src/xkbcomp/ast.h", "src/xkbcomp/parser.y"], "fixing_code_end_loc": [794, 41, 198, 691], "fixing_code_start_loc": [109, 38, 98, 594], "message": "Unchecked NULL pointer usage in xkbcommon before 0.8.1 could be used by local attackers to crash (NULL pointer dereference) the xkbcommon parser by supplying a crafted keymap file, because geometry tokens were desupported incorrectly.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xkbcommon_project:xkbcommon:*:*:*:*:*:*:*:*", "matchCriteriaId": "2F9BAF72-405A-41EA-AA6D-509128B3E4AD", "versionEndExcluding": "0.8.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:lts:*:*:*", "matchCriteriaId": "B5A6F2F3-4894-4392-8296-3B8DD2679084", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:16.04:*:*:*:lts:*:*:*", "matchCriteriaId": "F7016A2A-8365-4F1A-89A2-7A19F2BCAE5B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:18.04:*:*:*:lts:*:*:*", "matchCriteriaId": "23A7C53F-B80F-4E6A-AFA9-58EEA84BE11D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Unchecked NULL pointer usage in xkbcommon before 0.8.1 could be used by local attackers to crash (NULL pointer dereference) the xkbcommon parser by supplying a crafted keymap file, because geometry tokens were desupported incorrectly."}, {"lang": "es", "value": "El uso de un puntero NULL no verificado en xkbcommon en versiones anteriores a la 0.8.1 podr\u00eda ser aprovechado por atacantes locales para provocar el cierre inesperado (desreferencia de puntero NULL) del analizador xkbcommon proporcionando un archivo keymap manipulado, debido a que los tokens de geometr\u00eda dejaron de ser soportados incorrectamente."}], "evaluatorComment": null, "id": "CVE-2018-15854", "lastModified": "2019-08-06T17:15:24.947", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 2.1, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-08-25T21:29:01.593", "references": [{"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2019:2079"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/xkbcommon/libxkbcommon/commit/e3cacae7b1bfda0d839c280494f23284a1187adf"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://lists.freedesktop.org/archives/wayland-devel/2018-August/039232.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/201810-05"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3786-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3786-2/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/xkbcommon/libxkbcommon/commit/e3cacae7b1bfda0d839c280494f23284a1187adf"}, "type": "CWE-476"}
321
Determine whether the {function_name} code is vulnerable or not.
[ "/************************************************************\n * Copyright (c) 1994 by Silicon Graphics Computer Systems, Inc.\n *\n * Permission to use, copy, modify, and distribute this\n * software and its documentation for any purpose and without\n * fee is hereby granted, provided that the above copyright\n * notice appear in all copies and that both that copyright\n * notice and this permission notice appear in supporting\n * documentation, and that the name of Silicon Graphics not be\n * used in advertising or publicity pertaining to distribution\n * of the software without specific prior written permission.\n * Silicon Graphics makes no representation about the suitability\n * of this software for any purpose. It is provided \"as is\"\n * without any express or implied warranty.\n *\n * SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS\n * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n * AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON\n * GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\n * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,\n * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE\n * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH\n * THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n ********************************************************/", "/*\n * Copyright © 2012 Intel Corporation\n * Copyright © 2012 Ran Benita <ran234@gmail.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\n * Author: Daniel Stone <daniel@fooishbar.org>\n * Ran Benita <ran234@gmail.com>\n */", "#include \"xkbcomp-priv.h\"\n#include \"ast-build.h\"\n#include \"include.h\"", "ParseCommon *\nAppendStmt(ParseCommon *to, ParseCommon *append)\n{\n ParseCommon *iter;", " if (!to)\n return append;", " for (iter = to; iter->next; iter = iter->next);", " iter->next = append;\n return to;\n}", "static ExprDef *\nExprCreate(enum expr_op_type op, enum expr_value_type type, size_t size)\n{\n ExprDef *expr = malloc(size);\n if (!expr)\n return NULL;", " expr->common.type = STMT_EXPR;\n expr->common.next = NULL;\n expr->expr.op = op;\n expr->expr.value_type = type;", " return expr;\n}", "#define EXPR_CREATE(type_, name_, op_, value_type_) \\\n ExprDef *name_ = ExprCreate(op_, value_type_, sizeof(type_)); \\\n if (!name_) \\\n return NULL;", "ExprDef *\nExprCreateString(xkb_atom_t str)\n{\n EXPR_CREATE(ExprString, expr, EXPR_VALUE, EXPR_TYPE_STRING);\n expr->string.str = str;\n return expr;\n}", "ExprDef *\nExprCreateInteger(int ival)\n{\n EXPR_CREATE(ExprInteger, expr, EXPR_VALUE, EXPR_TYPE_INT);\n expr->integer.ival = ival;\n return expr;\n}", "ExprDef *", "ExprCreateFloat(void)\n{\n EXPR_CREATE(ExprFloat, expr, EXPR_VALUE, EXPR_TYPE_FLOAT);\n return expr;\n}", "ExprDef *", "ExprCreateBoolean(bool set)\n{\n EXPR_CREATE(ExprBoolean, expr, EXPR_VALUE, EXPR_TYPE_BOOLEAN);\n expr->boolean.set = set;\n return expr;\n}", "ExprDef *\nExprCreateKeyName(xkb_atom_t key_name)\n{\n EXPR_CREATE(ExprKeyName, expr, EXPR_VALUE, EXPR_TYPE_KEYNAME);\n expr->key_name.key_name = key_name;\n return expr;\n}", "ExprDef *\nExprCreateIdent(xkb_atom_t ident)\n{\n EXPR_CREATE(ExprIdent, expr, EXPR_IDENT, EXPR_TYPE_UNKNOWN);\n expr->ident.ident = ident;\n return expr;\n}", "ExprDef *\nExprCreateUnary(enum expr_op_type op, enum expr_value_type type,\n ExprDef *child)\n{\n EXPR_CREATE(ExprUnary, expr, op, type);\n expr->unary.child = child;\n return expr;\n}", "ExprDef *\nExprCreateBinary(enum expr_op_type op, ExprDef *left, ExprDef *right)\n{\n EXPR_CREATE(ExprBinary, expr, op, EXPR_TYPE_UNKNOWN);", " if (op == EXPR_ASSIGN || left->expr.value_type == EXPR_TYPE_UNKNOWN)\n expr->expr.value_type = right->expr.value_type;\n else if (left->expr.value_type == right->expr.value_type ||\n right->expr.value_type == EXPR_TYPE_UNKNOWN)\n expr->expr.value_type = left->expr.value_type;\n expr->binary.left = left;\n expr->binary.right = right;", " return expr;\n}", "ExprDef *\nExprCreateFieldRef(xkb_atom_t element, xkb_atom_t field)\n{\n EXPR_CREATE(ExprFieldRef, expr, EXPR_FIELD_REF, EXPR_TYPE_UNKNOWN);\n expr->field_ref.element = element;\n expr->field_ref.field = field;\n return expr;\n}", "ExprDef *\nExprCreateArrayRef(xkb_atom_t element, xkb_atom_t field, ExprDef *entry)\n{\n EXPR_CREATE(ExprArrayRef, expr, EXPR_ARRAY_REF, EXPR_TYPE_UNKNOWN);\n expr->array_ref.element = element;\n expr->array_ref.field = field;\n expr->array_ref.entry = entry;\n return expr;\n}", "ExprDef *\nExprCreateAction(xkb_atom_t name, ExprDef *args)\n{\n EXPR_CREATE(ExprAction, expr, EXPR_ACTION_DECL, EXPR_TYPE_UNKNOWN);\n expr->action.name = name;\n expr->action.args = args;\n return expr;\n}", "ExprDef *\nExprCreateKeysymList(xkb_keysym_t sym)\n{\n EXPR_CREATE(ExprKeysymList, expr, EXPR_KEYSYM_LIST, EXPR_TYPE_SYMBOLS);", " darray_init(expr->keysym_list.syms);\n darray_init(expr->keysym_list.symsMapIndex);\n darray_init(expr->keysym_list.symsNumEntries);", " darray_append(expr->keysym_list.syms, sym);\n darray_append(expr->keysym_list.symsMapIndex, 0);\n darray_append(expr->keysym_list.symsNumEntries, 1);", " return expr;\n}", "ExprDef *\nExprCreateMultiKeysymList(ExprDef *expr)\n{\n unsigned nLevels = darray_size(expr->keysym_list.symsMapIndex);", " darray_resize(expr->keysym_list.symsMapIndex, 1);\n darray_resize(expr->keysym_list.symsNumEntries, 1);\n darray_item(expr->keysym_list.symsMapIndex, 0) = 0;\n darray_item(expr->keysym_list.symsNumEntries, 0) = nLevels;", " return expr;\n}", "ExprDef *\nExprAppendKeysymList(ExprDef *expr, xkb_keysym_t sym)\n{\n unsigned nSyms = darray_size(expr->keysym_list.syms);", " darray_append(expr->keysym_list.symsMapIndex, nSyms);\n darray_append(expr->keysym_list.symsNumEntries, 1);\n darray_append(expr->keysym_list.syms, sym);", " return expr;\n}", "ExprDef *\nExprAppendMultiKeysymList(ExprDef *expr, ExprDef *append)\n{\n unsigned nSyms = darray_size(expr->keysym_list.syms);\n unsigned numEntries = darray_size(append->keysym_list.syms);", " darray_append(expr->keysym_list.symsMapIndex, nSyms);\n darray_append(expr->keysym_list.symsNumEntries, numEntries);\n darray_concat(expr->keysym_list.syms, append->keysym_list.syms);", " FreeStmt((ParseCommon *) &append);", " return expr;\n}", "KeycodeDef *\nKeycodeCreate(xkb_atom_t name, int64_t value)\n{\n KeycodeDef *def = malloc(sizeof(*def));\n if (!def)\n return NULL;", " def->common.type = STMT_KEYCODE;\n def->common.next = NULL;\n def->name = name;\n def->value = value;", " return def;\n}", "KeyAliasDef *\nKeyAliasCreate(xkb_atom_t alias, xkb_atom_t real)\n{\n KeyAliasDef *def = malloc(sizeof(*def));\n if (!def)\n return NULL;", " def->common.type = STMT_ALIAS;\n def->common.next = NULL;\n def->alias = alias;\n def->real = real;", " return def;\n}", "VModDef *\nVModCreate(xkb_atom_t name, ExprDef *value)\n{\n VModDef *def = malloc(sizeof(*def));\n if (!def)\n return NULL;", " def->common.type = STMT_VMOD;\n def->common.next = NULL;\n def->name = name;\n def->value = value;", " return def;\n}", "VarDef *\nVarCreate(ExprDef *name, ExprDef *value)\n{\n VarDef *def = malloc(sizeof(*def));\n if (!def)\n return NULL;", " def->common.type = STMT_VAR;\n def->common.next = NULL;\n def->name = name;\n def->value = value;", " return def;\n}", "VarDef *\nBoolVarCreate(xkb_atom_t ident, bool set)\n{\n ExprDef *name, *value;\n VarDef *def;\n if (!(name = ExprCreateIdent(ident))) {\n return NULL;\n }\n if (!(value = ExprCreateBoolean(set))) {\n FreeStmt((ParseCommon *) name);\n return NULL;\n }\n if (!(def = VarCreate(name, value))) {\n FreeStmt((ParseCommon *) name);\n FreeStmt((ParseCommon *) value);\n return NULL;\n }\n return def;\n}", "InterpDef *\nInterpCreate(xkb_keysym_t sym, ExprDef *match)\n{\n InterpDef *def = malloc(sizeof(*def));\n if (!def)\n return NULL;", " def->common.type = STMT_INTERP;\n def->common.next = NULL;\n def->sym = sym;\n def->match = match;\n def->def = NULL;", " return def;\n}", "KeyTypeDef *\nKeyTypeCreate(xkb_atom_t name, VarDef *body)\n{\n KeyTypeDef *def = malloc(sizeof(*def));\n if (!def)\n return NULL;", " def->common.type = STMT_TYPE;\n def->common.next = NULL;\n def->merge = MERGE_DEFAULT;\n def->name = name;\n def->body = body;", " return def;\n}", "SymbolsDef *\nSymbolsCreate(xkb_atom_t keyName, VarDef *symbols)\n{\n SymbolsDef *def = malloc(sizeof(*def));\n if (!def)\n return NULL;", " def->common.type = STMT_SYMBOLS;\n def->common.next = NULL;\n def->merge = MERGE_DEFAULT;\n def->keyName = keyName;\n def->symbols = symbols;", " return def;\n}", "GroupCompatDef *\nGroupCompatCreate(unsigned group, ExprDef *val)\n{\n GroupCompatDef *def = malloc(sizeof(*def));\n if (!def)\n return NULL;", " def->common.type = STMT_GROUP_COMPAT;\n def->common.next = NULL;\n def->merge = MERGE_DEFAULT;\n def->group = group;\n def->def = val;", " return def;\n}", "ModMapDef *\nModMapCreate(xkb_atom_t modifier, ExprDef *keys)\n{\n ModMapDef *def = malloc(sizeof(*def));\n if (!def)\n return NULL;", " def->common.type = STMT_MODMAP;\n def->common.next = NULL;\n def->merge = MERGE_DEFAULT;\n def->modifier = modifier;\n def->keys = keys;", " return def;\n}", "LedMapDef *\nLedMapCreate(xkb_atom_t name, VarDef *body)\n{\n LedMapDef *def = malloc(sizeof(*def));\n if (!def)\n return NULL;", " def->common.type = STMT_LED_MAP;\n def->common.next = NULL;\n def->merge = MERGE_DEFAULT;\n def->name = name;\n def->body = body;", " return def;\n}", "LedNameDef *\nLedNameCreate(unsigned ndx, ExprDef *name, bool virtual)\n{\n LedNameDef *def = malloc(sizeof(*def));\n if (!def)\n return NULL;", " def->common.type = STMT_LED_NAME;\n def->common.next = NULL;\n def->merge = MERGE_DEFAULT;\n def->ndx = ndx;\n def->name = name;\n def->virtual = virtual;", " return def;\n}", "static void\nFreeInclude(IncludeStmt *incl);", "IncludeStmt *\nIncludeCreate(struct xkb_context *ctx, char *str, enum merge_mode merge)\n{\n IncludeStmt *incl, *first;\n char *file, *map, *stmt, *tmp, *extra_data;\n char nextop;", " incl = first = NULL;\n file = map = NULL;\n tmp = str;\n stmt = strdup_safe(str);\n while (tmp && *tmp)\n {\n if (!ParseIncludeMap(&tmp, &file, &map, &nextop, &extra_data))\n goto err;", " /*\n * Given an RMLVO (here layout) like 'us,,fr', the rules parser\n * will give out something like 'pc+us+:2+fr:3+inet(evdev)'.\n * We should just skip the ':2' in this case and leave it to the\n * appropriate section to deal with the empty group.\n */\n if (isempty(file)) {\n free(file);\n free(map);\n free(extra_data);\n continue;\n }", " if (first == NULL) {\n first = incl = malloc(sizeof(*first));\n } else {\n incl->next_incl = malloc(sizeof(*first));\n incl = incl->next_incl;\n }", " if (!incl)\n break;", " incl->common.type = STMT_INCLUDE;\n incl->common.next = NULL;\n incl->merge = merge;\n incl->stmt = NULL;\n incl->file = file;\n incl->map = map;\n incl->modifier = extra_data;\n incl->next_incl = NULL;", " if (nextop == '|')\n merge = MERGE_AUGMENT;\n else\n merge = MERGE_OVERRIDE;\n }", " if (first)\n first->stmt = stmt;\n else\n free(stmt);", " return first;", "err:\n log_err(ctx, \"Illegal include statement \\\"%s\\\"; Ignored\\n\", stmt);\n FreeInclude(first);\n free(stmt);\n return NULL;\n}", "XkbFile *\nXkbFileCreate(enum xkb_file_type type, char *name, ParseCommon *defs,\n enum xkb_map_flags flags)\n{\n XkbFile *file;", " file = calloc(1, sizeof(*file));\n if (!file)\n return NULL;", " XkbEscapeMapName(name);\n file->file_type = type;\n file->name = name ? name : strdup(\"(unnamed)\");\n file->defs = defs;\n file->flags = flags;", " return file;\n}", "XkbFile *\nXkbFileFromComponents(struct xkb_context *ctx,\n const struct xkb_component_names *kkctgs)\n{\n char *const components[] = {\n kkctgs->keycodes, kkctgs->types,\n kkctgs->compat, kkctgs->symbols,\n };\n enum xkb_file_type type;\n IncludeStmt *include = NULL;\n XkbFile *file = NULL;\n ParseCommon *defs = NULL;", " for (type = FIRST_KEYMAP_FILE_TYPE; type <= LAST_KEYMAP_FILE_TYPE; type++) {\n include = IncludeCreate(ctx, components[type], MERGE_DEFAULT);\n if (!include)\n goto err;", " file = XkbFileCreate(type, NULL, (ParseCommon *) include, 0);\n if (!file) {\n FreeInclude(include);\n goto err;\n }", " defs = AppendStmt(defs, &file->common);\n }", " file = XkbFileCreate(FILE_TYPE_KEYMAP, NULL, defs, 0);\n if (!file)\n goto err;", " return file;", "err:\n FreeXkbFile((XkbFile *) defs);\n return NULL;\n}", "static void\nFreeExpr(ExprDef *expr)\n{\n if (!expr)\n return;", " switch (expr->expr.op) {\n case EXPR_ACTION_LIST:\n case EXPR_NEGATE:\n case EXPR_UNARY_PLUS:\n case EXPR_NOT:\n case EXPR_INVERT:\n FreeStmt((ParseCommon *) expr->unary.child);\n break;", " case EXPR_DIVIDE:\n case EXPR_ADD:\n case EXPR_SUBTRACT:\n case EXPR_MULTIPLY:\n case EXPR_ASSIGN:\n FreeStmt((ParseCommon *) expr->binary.left);\n FreeStmt((ParseCommon *) expr->binary.right);\n break;", " case EXPR_ACTION_DECL:\n FreeStmt((ParseCommon *) expr->action.args);\n break;", " case EXPR_ARRAY_REF:\n FreeStmt((ParseCommon *) expr->array_ref.entry);\n break;", " case EXPR_KEYSYM_LIST:\n darray_free(expr->keysym_list.syms);\n darray_free(expr->keysym_list.symsMapIndex);\n darray_free(expr->keysym_list.symsNumEntries);\n break;", " default:\n break;\n }\n}", "static void\nFreeInclude(IncludeStmt *incl)\n{\n IncludeStmt *next;", " while (incl)\n {\n next = incl->next_incl;", " free(incl->file);\n free(incl->map);\n free(incl->modifier);\n free(incl->stmt);", " free(incl);\n incl = next;\n }\n}", "void\nFreeStmt(ParseCommon *stmt)\n{\n ParseCommon *next;", " while (stmt)\n {\n next = stmt->next;", " switch (stmt->type) {\n case STMT_INCLUDE:\n FreeInclude((IncludeStmt *) stmt);\n /* stmt is already free'd here. */\n stmt = NULL;\n break;\n case STMT_EXPR:\n FreeExpr((ExprDef *) stmt);\n break;\n case STMT_VAR:\n FreeStmt((ParseCommon *) ((VarDef *) stmt)->name);\n FreeStmt((ParseCommon *) ((VarDef *) stmt)->value);\n break;\n case STMT_TYPE:\n FreeStmt((ParseCommon *) ((KeyTypeDef *) stmt)->body);\n break;\n case STMT_INTERP:\n FreeStmt((ParseCommon *) ((InterpDef *) stmt)->match);\n FreeStmt((ParseCommon *) ((InterpDef *) stmt)->def);\n break;\n case STMT_VMOD:\n FreeStmt((ParseCommon *) ((VModDef *) stmt)->value);\n break;\n case STMT_SYMBOLS:\n FreeStmt((ParseCommon *) ((SymbolsDef *) stmt)->symbols);\n break;\n case STMT_MODMAP:\n FreeStmt((ParseCommon *) ((ModMapDef *) stmt)->keys);\n break;\n case STMT_GROUP_COMPAT:\n FreeStmt((ParseCommon *) ((GroupCompatDef *) stmt)->def);\n break;\n case STMT_LED_MAP:\n FreeStmt((ParseCommon *) ((LedMapDef *) stmt)->body);\n break;\n case STMT_LED_NAME:\n FreeStmt((ParseCommon *) ((LedNameDef *) stmt)->name);\n break;\n default:\n break;\n }", " free(stmt);\n stmt = next;\n }\n}", "void\nFreeXkbFile(XkbFile *file)\n{\n XkbFile *next;", " while (file)\n {\n next = (XkbFile *) file->common.next;", " switch (file->file_type) {\n case FILE_TYPE_KEYMAP:\n FreeXkbFile((XkbFile *) file->defs);\n break;", " case FILE_TYPE_TYPES:\n case FILE_TYPE_COMPAT:\n case FILE_TYPE_SYMBOLS:\n case FILE_TYPE_KEYCODES:\n case FILE_TYPE_GEOMETRY:\n FreeStmt(file->defs);\n break;", " default:\n break;\n }", " free(file->name);\n free(file);\n file = next;\n }\n}", "static const char *xkb_file_type_strings[_FILE_TYPE_NUM_ENTRIES] = {\n [FILE_TYPE_KEYCODES] = \"xkb_keycodes\",\n [FILE_TYPE_TYPES] = \"xkb_types\",\n [FILE_TYPE_COMPAT] = \"xkb_compatibility\",\n [FILE_TYPE_SYMBOLS] = \"xkb_symbols\",\n [FILE_TYPE_GEOMETRY] = \"xkb_geometry\",\n [FILE_TYPE_KEYMAP] = \"xkb_keymap\",\n [FILE_TYPE_RULES] = \"rules\",\n};", "const char *\nxkb_file_type_to_string(enum xkb_file_type type)\n{\n if (type > _FILE_TYPE_NUM_ENTRIES)\n return \"unknown\";\n return xkb_file_type_strings[type];\n}", "static const char *stmt_type_strings[_STMT_NUM_VALUES] = {\n [STMT_UNKNOWN] = \"unknown statement\",\n [STMT_INCLUDE] = \"include statement\",\n [STMT_KEYCODE] = \"key name definition\",\n [STMT_ALIAS] = \"key alias definition\",\n [STMT_EXPR] = \"expression\",\n [STMT_VAR] = \"variable definition\",\n [STMT_TYPE] = \"key type definition\",\n [STMT_INTERP] = \"symbol interpretation definition\",\n [STMT_VMOD] = \"virtual modifiers definition\",\n [STMT_SYMBOLS] = \"key symbols definition\",\n [STMT_MODMAP] = \"modifier map declaration\",\n [STMT_GROUP_COMPAT] = \"group declaration\",\n [STMT_LED_MAP] = \"indicator map declaration\",\n [STMT_LED_NAME] = \"indicator name declaration\",\n};", "const char *\nstmt_type_to_string(enum stmt_type type)\n{\n if (type >= _STMT_NUM_VALUES)\n return NULL;\n return stmt_type_strings[type];\n}", "static const char *expr_op_type_strings[_EXPR_NUM_VALUES] = {\n [EXPR_VALUE] = \"literal\",\n [EXPR_IDENT] = \"identifier\",\n [EXPR_ACTION_DECL] = \"action declaration\",\n [EXPR_FIELD_REF] = \"field reference\",\n [EXPR_ARRAY_REF] = \"array reference\",\n [EXPR_KEYSYM_LIST] = \"list of keysyms\",\n [EXPR_ACTION_LIST] = \"list of actions\",\n [EXPR_ADD] = \"addition\",\n [EXPR_SUBTRACT] = \"subtraction\",\n [EXPR_MULTIPLY] = \"multiplication\",\n [EXPR_DIVIDE] = \"division\",\n [EXPR_ASSIGN] = \"assignment\",\n [EXPR_NOT] = \"logical negation\",\n [EXPR_NEGATE] = \"arithmetic negation\",\n [EXPR_INVERT] = \"bitwise inversion\",\n [EXPR_UNARY_PLUS] = \"unary plus\",\n};", "const char *\nexpr_op_type_to_string(enum expr_op_type type)\n{\n if (type >= _EXPR_NUM_VALUES)\n return NULL;\n return expr_op_type_strings[type];\n}", "static const char *expr_value_type_strings[_EXPR_TYPE_NUM_VALUES] = {\n [EXPR_TYPE_UNKNOWN] = \"unknown\",\n [EXPR_TYPE_BOOLEAN] = \"boolean\",\n [EXPR_TYPE_INT] = \"int\",", " [EXPR_TYPE_FLOAT] = \"float\",", " [EXPR_TYPE_STRING] = \"string\",\n [EXPR_TYPE_ACTION] = \"action\",\n [EXPR_TYPE_KEYNAME] = \"keyname\",\n [EXPR_TYPE_SYMBOLS] = \"symbols\",\n};", "const char *\nexpr_value_type_to_string(enum expr_value_type type)\n{\n if (type >= _EXPR_TYPE_NUM_VALUES)\n return NULL;\n return expr_value_type_strings[type];\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [785, 37, 190, 691], "buggy_code_start_loc": [108, 37, 97, 594], "filenames": ["src/xkbcomp/ast-build.c", "src/xkbcomp/ast-build.h", "src/xkbcomp/ast.h", "src/xkbcomp/parser.y"], "fixing_code_end_loc": [794, 41, 198, 691], "fixing_code_start_loc": [109, 38, 98, 594], "message": "Unchecked NULL pointer usage in xkbcommon before 0.8.1 could be used by local attackers to crash (NULL pointer dereference) the xkbcommon parser by supplying a crafted keymap file, because geometry tokens were desupported incorrectly.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xkbcommon_project:xkbcommon:*:*:*:*:*:*:*:*", "matchCriteriaId": "2F9BAF72-405A-41EA-AA6D-509128B3E4AD", "versionEndExcluding": "0.8.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:lts:*:*:*", "matchCriteriaId": "B5A6F2F3-4894-4392-8296-3B8DD2679084", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:16.04:*:*:*:lts:*:*:*", "matchCriteriaId": "F7016A2A-8365-4F1A-89A2-7A19F2BCAE5B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:18.04:*:*:*:lts:*:*:*", "matchCriteriaId": "23A7C53F-B80F-4E6A-AFA9-58EEA84BE11D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Unchecked NULL pointer usage in xkbcommon before 0.8.1 could be used by local attackers to crash (NULL pointer dereference) the xkbcommon parser by supplying a crafted keymap file, because geometry tokens were desupported incorrectly."}, {"lang": "es", "value": "El uso de un puntero NULL no verificado en xkbcommon en versiones anteriores a la 0.8.1 podr\u00eda ser aprovechado por atacantes locales para provocar el cierre inesperado (desreferencia de puntero NULL) del analizador xkbcommon proporcionando un archivo keymap manipulado, debido a que los tokens de geometr\u00eda dejaron de ser soportados incorrectamente."}], "evaluatorComment": null, "id": "CVE-2018-15854", "lastModified": "2019-08-06T17:15:24.947", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 2.1, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-08-25T21:29:01.593", "references": [{"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2019:2079"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/xkbcommon/libxkbcommon/commit/e3cacae7b1bfda0d839c280494f23284a1187adf"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://lists.freedesktop.org/archives/wayland-devel/2018-August/039232.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/201810-05"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3786-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3786-2/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/xkbcommon/libxkbcommon/commit/e3cacae7b1bfda0d839c280494f23284a1187adf"}, "type": "CWE-476"}
321
Determine whether the {function_name} code is vulnerable or not.
[ "/************************************************************\n * Copyright (c) 1994 by Silicon Graphics Computer Systems, Inc.\n *\n * Permission to use, copy, modify, and distribute this\n * software and its documentation for any purpose and without\n * fee is hereby granted, provided that the above copyright\n * notice appear in all copies and that both that copyright\n * notice and this permission notice appear in supporting\n * documentation, and that the name of Silicon Graphics not be\n * used in advertising or publicity pertaining to distribution\n * of the software without specific prior written permission.\n * Silicon Graphics makes no representation about the suitability\n * of this software for any purpose. It is provided \"as is\"\n * without any express or implied warranty.\n *\n * SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS\n * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n * AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON\n * GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\n * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,\n * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE\n * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH\n * THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n ********************************************************/", "#ifndef XKBCOMP_AST_BUILD_H\n#define XKBCOMP_AST_BUILD_H", "ParseCommon *\nAppendStmt(ParseCommon *to, ParseCommon *append);", "ExprDef *\nExprCreateString(xkb_atom_t str);", "ExprDef *\nExprCreateInteger(int ival);", "", "\nExprDef *\nExprCreateBoolean(bool set);", "ExprDef *\nExprCreateKeyName(xkb_atom_t key_name);", "ExprDef *\nExprCreateIdent(xkb_atom_t ident);", "ExprDef *\nExprCreateUnary(enum expr_op_type op, enum expr_value_type type,\n ExprDef *child);", "ExprDef *\nExprCreateBinary(enum expr_op_type op, ExprDef *left, ExprDef *right);", "ExprDef *\nExprCreateFieldRef(xkb_atom_t element, xkb_atom_t field);", "ExprDef *\nExprCreateArrayRef(xkb_atom_t element, xkb_atom_t field, ExprDef *entry);", "ExprDef *\nExprCreateAction(xkb_atom_t name, ExprDef *args);", "ExprDef *\nExprCreateMultiKeysymList(ExprDef *list);", "ExprDef *\nExprCreateKeysymList(xkb_keysym_t sym);", "ExprDef *\nExprAppendMultiKeysymList(ExprDef *list, ExprDef *append);", "ExprDef *\nExprAppendKeysymList(ExprDef *list, xkb_keysym_t sym);", "KeycodeDef *\nKeycodeCreate(xkb_atom_t name, int64_t value);", "KeyAliasDef *\nKeyAliasCreate(xkb_atom_t alias, xkb_atom_t real);", "VModDef *\nVModCreate(xkb_atom_t name, ExprDef *value);", "VarDef *\nVarCreate(ExprDef *name, ExprDef *value);", "VarDef *\nBoolVarCreate(xkb_atom_t ident, bool set);", "InterpDef *\nInterpCreate(xkb_keysym_t sym, ExprDef *match);", "KeyTypeDef *\nKeyTypeCreate(xkb_atom_t name, VarDef *body);", "SymbolsDef *\nSymbolsCreate(xkb_atom_t keyName, VarDef *symbols);", "GroupCompatDef *\nGroupCompatCreate(unsigned group, ExprDef *def);", "ModMapDef *\nModMapCreate(xkb_atom_t modifier, ExprDef *keys);", "LedMapDef *\nLedMapCreate(xkb_atom_t name, VarDef *body);", "LedNameDef *\nLedNameCreate(unsigned ndx, ExprDef *name, bool virtual);", "IncludeStmt *\nIncludeCreate(struct xkb_context *ctx, char *str, enum merge_mode merge);", "XkbFile *\nXkbFileCreate(enum xkb_file_type type, char *name, ParseCommon *defs,\n enum xkb_map_flags flags);", "void\nFreeStmt(ParseCommon *stmt);", "#endif" ]
[ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [785, 37, 190, 691], "buggy_code_start_loc": [108, 37, 97, 594], "filenames": ["src/xkbcomp/ast-build.c", "src/xkbcomp/ast-build.h", "src/xkbcomp/ast.h", "src/xkbcomp/parser.y"], "fixing_code_end_loc": [794, 41, 198, 691], "fixing_code_start_loc": [109, 38, 98, 594], "message": "Unchecked NULL pointer usage in xkbcommon before 0.8.1 could be used by local attackers to crash (NULL pointer dereference) the xkbcommon parser by supplying a crafted keymap file, because geometry tokens were desupported incorrectly.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xkbcommon_project:xkbcommon:*:*:*:*:*:*:*:*", "matchCriteriaId": "2F9BAF72-405A-41EA-AA6D-509128B3E4AD", "versionEndExcluding": "0.8.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:lts:*:*:*", "matchCriteriaId": "B5A6F2F3-4894-4392-8296-3B8DD2679084", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:16.04:*:*:*:lts:*:*:*", "matchCriteriaId": "F7016A2A-8365-4F1A-89A2-7A19F2BCAE5B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:18.04:*:*:*:lts:*:*:*", "matchCriteriaId": "23A7C53F-B80F-4E6A-AFA9-58EEA84BE11D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Unchecked NULL pointer usage in xkbcommon before 0.8.1 could be used by local attackers to crash (NULL pointer dereference) the xkbcommon parser by supplying a crafted keymap file, because geometry tokens were desupported incorrectly."}, {"lang": "es", "value": "El uso de un puntero NULL no verificado en xkbcommon en versiones anteriores a la 0.8.1 podr\u00eda ser aprovechado por atacantes locales para provocar el cierre inesperado (desreferencia de puntero NULL) del analizador xkbcommon proporcionando un archivo keymap manipulado, debido a que los tokens de geometr\u00eda dejaron de ser soportados incorrectamente."}], "evaluatorComment": null, "id": "CVE-2018-15854", "lastModified": "2019-08-06T17:15:24.947", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 2.1, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-08-25T21:29:01.593", "references": [{"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2019:2079"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/xkbcommon/libxkbcommon/commit/e3cacae7b1bfda0d839c280494f23284a1187adf"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://lists.freedesktop.org/archives/wayland-devel/2018-August/039232.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/201810-05"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3786-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3786-2/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/xkbcommon/libxkbcommon/commit/e3cacae7b1bfda0d839c280494f23284a1187adf"}, "type": "CWE-476"}
321
Determine whether the {function_name} code is vulnerable or not.
[ "/************************************************************\n * Copyright (c) 1994 by Silicon Graphics Computer Systems, Inc.\n *\n * Permission to use, copy, modify, and distribute this\n * software and its documentation for any purpose and without\n * fee is hereby granted, provided that the above copyright\n * notice appear in all copies and that both that copyright\n * notice and this permission notice appear in supporting\n * documentation, and that the name of Silicon Graphics not be\n * used in advertising or publicity pertaining to distribution\n * of the software without specific prior written permission.\n * Silicon Graphics makes no representation about the suitability\n * of this software for any purpose. It is provided \"as is\"\n * without any express or implied warranty.\n *\n * SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS\n * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n * AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON\n * GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\n * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,\n * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE\n * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH\n * THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n ********************************************************/", "#ifndef XKBCOMP_AST_BUILD_H\n#define XKBCOMP_AST_BUILD_H", "ParseCommon *\nAppendStmt(ParseCommon *to, ParseCommon *append);", "ExprDef *\nExprCreateString(xkb_atom_t str);", "ExprDef *\nExprCreateInteger(int ival);", "\nExprDef *\nExprCreateFloat(void);", "\nExprDef *\nExprCreateBoolean(bool set);", "ExprDef *\nExprCreateKeyName(xkb_atom_t key_name);", "ExprDef *\nExprCreateIdent(xkb_atom_t ident);", "ExprDef *\nExprCreateUnary(enum expr_op_type op, enum expr_value_type type,\n ExprDef *child);", "ExprDef *\nExprCreateBinary(enum expr_op_type op, ExprDef *left, ExprDef *right);", "ExprDef *\nExprCreateFieldRef(xkb_atom_t element, xkb_atom_t field);", "ExprDef *\nExprCreateArrayRef(xkb_atom_t element, xkb_atom_t field, ExprDef *entry);", "ExprDef *\nExprCreateAction(xkb_atom_t name, ExprDef *args);", "ExprDef *\nExprCreateMultiKeysymList(ExprDef *list);", "ExprDef *\nExprCreateKeysymList(xkb_keysym_t sym);", "ExprDef *\nExprAppendMultiKeysymList(ExprDef *list, ExprDef *append);", "ExprDef *\nExprAppendKeysymList(ExprDef *list, xkb_keysym_t sym);", "KeycodeDef *\nKeycodeCreate(xkb_atom_t name, int64_t value);", "KeyAliasDef *\nKeyAliasCreate(xkb_atom_t alias, xkb_atom_t real);", "VModDef *\nVModCreate(xkb_atom_t name, ExprDef *value);", "VarDef *\nVarCreate(ExprDef *name, ExprDef *value);", "VarDef *\nBoolVarCreate(xkb_atom_t ident, bool set);", "InterpDef *\nInterpCreate(xkb_keysym_t sym, ExprDef *match);", "KeyTypeDef *\nKeyTypeCreate(xkb_atom_t name, VarDef *body);", "SymbolsDef *\nSymbolsCreate(xkb_atom_t keyName, VarDef *symbols);", "GroupCompatDef *\nGroupCompatCreate(unsigned group, ExprDef *def);", "ModMapDef *\nModMapCreate(xkb_atom_t modifier, ExprDef *keys);", "LedMapDef *\nLedMapCreate(xkb_atom_t name, VarDef *body);", "LedNameDef *\nLedNameCreate(unsigned ndx, ExprDef *name, bool virtual);", "IncludeStmt *\nIncludeCreate(struct xkb_context *ctx, char *str, enum merge_mode merge);", "XkbFile *\nXkbFileCreate(enum xkb_file_type type, char *name, ParseCommon *defs,\n enum xkb_map_flags flags);", "void\nFreeStmt(ParseCommon *stmt);", "#endif" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [785, 37, 190, 691], "buggy_code_start_loc": [108, 37, 97, 594], "filenames": ["src/xkbcomp/ast-build.c", "src/xkbcomp/ast-build.h", "src/xkbcomp/ast.h", "src/xkbcomp/parser.y"], "fixing_code_end_loc": [794, 41, 198, 691], "fixing_code_start_loc": [109, 38, 98, 594], "message": "Unchecked NULL pointer usage in xkbcommon before 0.8.1 could be used by local attackers to crash (NULL pointer dereference) the xkbcommon parser by supplying a crafted keymap file, because geometry tokens were desupported incorrectly.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xkbcommon_project:xkbcommon:*:*:*:*:*:*:*:*", "matchCriteriaId": "2F9BAF72-405A-41EA-AA6D-509128B3E4AD", "versionEndExcluding": "0.8.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:lts:*:*:*", "matchCriteriaId": "B5A6F2F3-4894-4392-8296-3B8DD2679084", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:16.04:*:*:*:lts:*:*:*", "matchCriteriaId": "F7016A2A-8365-4F1A-89A2-7A19F2BCAE5B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:18.04:*:*:*:lts:*:*:*", "matchCriteriaId": "23A7C53F-B80F-4E6A-AFA9-58EEA84BE11D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Unchecked NULL pointer usage in xkbcommon before 0.8.1 could be used by local attackers to crash (NULL pointer dereference) the xkbcommon parser by supplying a crafted keymap file, because geometry tokens were desupported incorrectly."}, {"lang": "es", "value": "El uso de un puntero NULL no verificado en xkbcommon en versiones anteriores a la 0.8.1 podr\u00eda ser aprovechado por atacantes locales para provocar el cierre inesperado (desreferencia de puntero NULL) del analizador xkbcommon proporcionando un archivo keymap manipulado, debido a que los tokens de geometr\u00eda dejaron de ser soportados incorrectamente."}], "evaluatorComment": null, "id": "CVE-2018-15854", "lastModified": "2019-08-06T17:15:24.947", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 2.1, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-08-25T21:29:01.593", "references": [{"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2019:2079"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/xkbcommon/libxkbcommon/commit/e3cacae7b1bfda0d839c280494f23284a1187adf"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://lists.freedesktop.org/archives/wayland-devel/2018-August/039232.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/201810-05"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3786-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3786-2/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/xkbcommon/libxkbcommon/commit/e3cacae7b1bfda0d839c280494f23284a1187adf"}, "type": "CWE-476"}
321
Determine whether the {function_name} code is vulnerable or not.
[ "/************************************************************\n * Copyright (c) 1994 by Silicon Graphics Computer Systems, Inc.\n *\n * Permission to use, copy, modify, and distribute this\n * software and its documentation for any purpose and without\n * fee is hereby granted, provided that the above copyright\n * notice appear in all copies and that both that copyright\n * notice and this permission notice appear in supporting\n * documentation, and that the name of Silicon Graphics not be\n * used in advertising or publicity pertaining to distribution\n * of the software without specific prior written permission.\n * Silicon Graphics makes no representation about the suitability\n * of this software for any purpose. It is provided \"as is\"\n * without any express or implied warranty.\n *\n * SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS\n * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n * AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON\n * GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\n * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,\n * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE\n * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH\n * THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n ********************************************************/", "/*\n * Copyright © 2012 Ran Benita <ran234@gmail.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */", "#ifndef XKBCOMP_AST_H\n#define XKBCOMP_AST_H", "enum xkb_file_type {\n /* Component files, by order of compilation. */\n FILE_TYPE_KEYCODES = 0,\n FILE_TYPE_TYPES = 1,\n FILE_TYPE_COMPAT = 2,\n FILE_TYPE_SYMBOLS = 3,\n /* Geometry is not compiled any more. */\n FILE_TYPE_GEOMETRY = 4,", " /* A top level file which includes the above files. */\n FILE_TYPE_KEYMAP,", "/* File types which must be found in a keymap file. */\n#define FIRST_KEYMAP_FILE_TYPE FILE_TYPE_KEYCODES\n#define LAST_KEYMAP_FILE_TYPE FILE_TYPE_SYMBOLS", " /* This one doesn't mix with the others, but useful here as well. */\n FILE_TYPE_RULES,", " _FILE_TYPE_NUM_ENTRIES\n};", "enum stmt_type {\n STMT_UNKNOWN = 0,\n STMT_INCLUDE,\n STMT_KEYCODE,\n STMT_ALIAS,\n STMT_EXPR,\n STMT_VAR,\n STMT_TYPE,\n STMT_INTERP,\n STMT_VMOD,\n STMT_SYMBOLS,\n STMT_MODMAP,\n STMT_GROUP_COMPAT,\n STMT_LED_MAP,\n STMT_LED_NAME,", " _STMT_NUM_VALUES\n};", "enum expr_value_type {\n EXPR_TYPE_UNKNOWN = 0,\n EXPR_TYPE_BOOLEAN,\n EXPR_TYPE_INT,", "", " EXPR_TYPE_STRING,\n EXPR_TYPE_ACTION,\n EXPR_TYPE_KEYNAME,\n EXPR_TYPE_SYMBOLS,", " _EXPR_TYPE_NUM_VALUES\n};", "enum expr_op_type {\n EXPR_VALUE,\n EXPR_IDENT,\n EXPR_ACTION_DECL,\n EXPR_FIELD_REF,\n EXPR_ARRAY_REF,\n EXPR_KEYSYM_LIST,\n EXPR_ACTION_LIST,\n EXPR_ADD,\n EXPR_SUBTRACT,\n EXPR_MULTIPLY,\n EXPR_DIVIDE,\n EXPR_ASSIGN,\n EXPR_NOT,\n EXPR_NEGATE,\n EXPR_INVERT,\n EXPR_UNARY_PLUS,", " _EXPR_NUM_VALUES\n};", "enum merge_mode {\n MERGE_DEFAULT,\n MERGE_AUGMENT,\n MERGE_OVERRIDE,\n MERGE_REPLACE,\n};", "const char *\nxkb_file_type_to_string(enum xkb_file_type type);", "const char *\nstmt_type_to_string(enum stmt_type type);", "const char *\nexpr_op_type_to_string(enum expr_op_type type);", "const char *\nexpr_value_type_to_string(enum expr_value_type type);", "typedef struct _ParseCommon {\n struct _ParseCommon *next;\n enum stmt_type type;\n} ParseCommon;", "typedef struct _IncludeStmt {\n ParseCommon common;\n enum merge_mode merge;\n char *stmt;\n char *file;\n char *map;\n char *modifier;\n struct _IncludeStmt *next_incl;\n} IncludeStmt;", "typedef struct {\n ParseCommon common;\n enum expr_op_type op;\n enum expr_value_type value_type;\n} ExprCommon;", "typedef union ExprDef ExprDef;", "typedef struct {\n ExprCommon expr;\n xkb_atom_t ident;\n} ExprIdent;", "typedef struct {\n ExprCommon expr;\n xkb_atom_t str;\n} ExprString;", "typedef struct {\n ExprCommon expr;\n bool set;\n} ExprBoolean;", "typedef struct {\n ExprCommon expr;\n int ival;\n} ExprInteger;", "typedef struct {\n ExprCommon expr;", "", " xkb_atom_t key_name;\n} ExprKeyName;", "typedef struct {\n ExprCommon expr;\n ExprDef *left;\n ExprDef *right;\n} ExprBinary;", "typedef struct {\n ExprCommon expr;\n ExprDef *child;\n} ExprUnary;", "typedef struct {\n ExprCommon expr;\n xkb_atom_t element;\n xkb_atom_t field;\n} ExprFieldRef;", "typedef struct {\n ExprCommon expr;\n xkb_atom_t element;\n xkb_atom_t field;\n ExprDef *entry;\n} ExprArrayRef;", "typedef struct {\n ExprCommon expr;\n xkb_atom_t name;\n ExprDef *args;\n} ExprAction;", "typedef struct {\n ExprCommon expr;\n darray(xkb_keysym_t) syms;\n darray(unsigned int) symsMapIndex;\n darray(unsigned int) symsNumEntries;\n} ExprKeysymList;", "union ExprDef {\n ParseCommon common;\n /* Maybe someday we can use C11 anonymous struct for ExprCommon here. */\n ExprCommon expr;\n ExprIdent ident;\n ExprString string;\n ExprBoolean boolean;\n ExprInteger integer;\n ExprKeyName key_name;\n ExprBinary binary;\n ExprUnary unary;\n ExprFieldRef field_ref;\n ExprArrayRef array_ref;\n ExprAction action;\n ExprKeysymList keysym_list;\n};", "typedef struct {\n ParseCommon common;\n enum merge_mode merge;\n ExprDef *name;\n ExprDef *value;\n} VarDef;", "typedef struct {\n ParseCommon common;\n enum merge_mode merge;\n xkb_atom_t name;\n ExprDef *value;\n} VModDef;", "typedef struct {\n ParseCommon common;\n enum merge_mode merge;\n xkb_atom_t name;\n int64_t value;\n} KeycodeDef;", "typedef struct {\n ParseCommon common;\n enum merge_mode merge;\n xkb_atom_t alias;\n xkb_atom_t real;\n} KeyAliasDef;", "typedef struct {\n ParseCommon common;\n enum merge_mode merge;\n xkb_atom_t name;\n VarDef *body;\n} KeyTypeDef;", "typedef struct {\n ParseCommon common;\n enum merge_mode merge;\n xkb_atom_t keyName;\n VarDef *symbols;\n} SymbolsDef;", "typedef struct {\n ParseCommon common;\n enum merge_mode merge;\n xkb_atom_t modifier;\n ExprDef *keys;\n} ModMapDef;", "typedef struct {\n ParseCommon common;\n enum merge_mode merge;\n unsigned group;\n ExprDef *def;\n} GroupCompatDef;", "typedef struct {\n ParseCommon common;\n enum merge_mode merge;\n xkb_keysym_t sym;\n ExprDef *match;\n VarDef *def;\n} InterpDef;", "typedef struct {\n ParseCommon common;\n enum merge_mode merge;\n unsigned ndx;\n ExprDef *name;\n bool virtual;\n} LedNameDef;", "typedef struct {\n ParseCommon common;\n enum merge_mode merge;\n xkb_atom_t name;\n VarDef *body;\n} LedMapDef;", "enum xkb_map_flags {\n MAP_IS_DEFAULT = (1 << 0),\n MAP_IS_PARTIAL = (1 << 1),\n MAP_IS_HIDDEN = (1 << 2),\n MAP_HAS_ALPHANUMERIC = (1 << 3),\n MAP_HAS_MODIFIER = (1 << 4),\n MAP_HAS_KEYPAD = (1 << 5),\n MAP_HAS_FN = (1 << 6),\n MAP_IS_ALTGR = (1 << 7),\n};", "typedef struct {\n ParseCommon common;\n enum xkb_file_type file_type;\n char *name;\n ParseCommon *defs;\n enum xkb_map_flags flags;\n} XkbFile;", "#endif" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [785, 37, 190, 691], "buggy_code_start_loc": [108, 37, 97, 594], "filenames": ["src/xkbcomp/ast-build.c", "src/xkbcomp/ast-build.h", "src/xkbcomp/ast.h", "src/xkbcomp/parser.y"], "fixing_code_end_loc": [794, 41, 198, 691], "fixing_code_start_loc": [109, 38, 98, 594], "message": "Unchecked NULL pointer usage in xkbcommon before 0.8.1 could be used by local attackers to crash (NULL pointer dereference) the xkbcommon parser by supplying a crafted keymap file, because geometry tokens were desupported incorrectly.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xkbcommon_project:xkbcommon:*:*:*:*:*:*:*:*", "matchCriteriaId": "2F9BAF72-405A-41EA-AA6D-509128B3E4AD", "versionEndExcluding": "0.8.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:lts:*:*:*", "matchCriteriaId": "B5A6F2F3-4894-4392-8296-3B8DD2679084", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:16.04:*:*:*:lts:*:*:*", "matchCriteriaId": "F7016A2A-8365-4F1A-89A2-7A19F2BCAE5B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:18.04:*:*:*:lts:*:*:*", "matchCriteriaId": "23A7C53F-B80F-4E6A-AFA9-58EEA84BE11D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Unchecked NULL pointer usage in xkbcommon before 0.8.1 could be used by local attackers to crash (NULL pointer dereference) the xkbcommon parser by supplying a crafted keymap file, because geometry tokens were desupported incorrectly."}, {"lang": "es", "value": "El uso de un puntero NULL no verificado en xkbcommon en versiones anteriores a la 0.8.1 podr\u00eda ser aprovechado por atacantes locales para provocar el cierre inesperado (desreferencia de puntero NULL) del analizador xkbcommon proporcionando un archivo keymap manipulado, debido a que los tokens de geometr\u00eda dejaron de ser soportados incorrectamente."}], "evaluatorComment": null, "id": "CVE-2018-15854", "lastModified": "2019-08-06T17:15:24.947", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 2.1, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-08-25T21:29:01.593", "references": [{"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2019:2079"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/xkbcommon/libxkbcommon/commit/e3cacae7b1bfda0d839c280494f23284a1187adf"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://lists.freedesktop.org/archives/wayland-devel/2018-August/039232.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/201810-05"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3786-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3786-2/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/xkbcommon/libxkbcommon/commit/e3cacae7b1bfda0d839c280494f23284a1187adf"}, "type": "CWE-476"}
321
Determine whether the {function_name} code is vulnerable or not.
[ "/************************************************************\n * Copyright (c) 1994 by Silicon Graphics Computer Systems, Inc.\n *\n * Permission to use, copy, modify, and distribute this\n * software and its documentation for any purpose and without\n * fee is hereby granted, provided that the above copyright\n * notice appear in all copies and that both that copyright\n * notice and this permission notice appear in supporting\n * documentation, and that the name of Silicon Graphics not be\n * used in advertising or publicity pertaining to distribution\n * of the software without specific prior written permission.\n * Silicon Graphics makes no representation about the suitability\n * of this software for any purpose. It is provided \"as is\"\n * without any express or implied warranty.\n *\n * SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS\n * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n * AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON\n * GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\n * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,\n * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE\n * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH\n * THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n ********************************************************/", "/*\n * Copyright © 2012 Ran Benita <ran234@gmail.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */", "#ifndef XKBCOMP_AST_H\n#define XKBCOMP_AST_H", "enum xkb_file_type {\n /* Component files, by order of compilation. */\n FILE_TYPE_KEYCODES = 0,\n FILE_TYPE_TYPES = 1,\n FILE_TYPE_COMPAT = 2,\n FILE_TYPE_SYMBOLS = 3,\n /* Geometry is not compiled any more. */\n FILE_TYPE_GEOMETRY = 4,", " /* A top level file which includes the above files. */\n FILE_TYPE_KEYMAP,", "/* File types which must be found in a keymap file. */\n#define FIRST_KEYMAP_FILE_TYPE FILE_TYPE_KEYCODES\n#define LAST_KEYMAP_FILE_TYPE FILE_TYPE_SYMBOLS", " /* This one doesn't mix with the others, but useful here as well. */\n FILE_TYPE_RULES,", " _FILE_TYPE_NUM_ENTRIES\n};", "enum stmt_type {\n STMT_UNKNOWN = 0,\n STMT_INCLUDE,\n STMT_KEYCODE,\n STMT_ALIAS,\n STMT_EXPR,\n STMT_VAR,\n STMT_TYPE,\n STMT_INTERP,\n STMT_VMOD,\n STMT_SYMBOLS,\n STMT_MODMAP,\n STMT_GROUP_COMPAT,\n STMT_LED_MAP,\n STMT_LED_NAME,", " _STMT_NUM_VALUES\n};", "enum expr_value_type {\n EXPR_TYPE_UNKNOWN = 0,\n EXPR_TYPE_BOOLEAN,\n EXPR_TYPE_INT,", " EXPR_TYPE_FLOAT,", " EXPR_TYPE_STRING,\n EXPR_TYPE_ACTION,\n EXPR_TYPE_KEYNAME,\n EXPR_TYPE_SYMBOLS,", " _EXPR_TYPE_NUM_VALUES\n};", "enum expr_op_type {\n EXPR_VALUE,\n EXPR_IDENT,\n EXPR_ACTION_DECL,\n EXPR_FIELD_REF,\n EXPR_ARRAY_REF,\n EXPR_KEYSYM_LIST,\n EXPR_ACTION_LIST,\n EXPR_ADD,\n EXPR_SUBTRACT,\n EXPR_MULTIPLY,\n EXPR_DIVIDE,\n EXPR_ASSIGN,\n EXPR_NOT,\n EXPR_NEGATE,\n EXPR_INVERT,\n EXPR_UNARY_PLUS,", " _EXPR_NUM_VALUES\n};", "enum merge_mode {\n MERGE_DEFAULT,\n MERGE_AUGMENT,\n MERGE_OVERRIDE,\n MERGE_REPLACE,\n};", "const char *\nxkb_file_type_to_string(enum xkb_file_type type);", "const char *\nstmt_type_to_string(enum stmt_type type);", "const char *\nexpr_op_type_to_string(enum expr_op_type type);", "const char *\nexpr_value_type_to_string(enum expr_value_type type);", "typedef struct _ParseCommon {\n struct _ParseCommon *next;\n enum stmt_type type;\n} ParseCommon;", "typedef struct _IncludeStmt {\n ParseCommon common;\n enum merge_mode merge;\n char *stmt;\n char *file;\n char *map;\n char *modifier;\n struct _IncludeStmt *next_incl;\n} IncludeStmt;", "typedef struct {\n ParseCommon common;\n enum expr_op_type op;\n enum expr_value_type value_type;\n} ExprCommon;", "typedef union ExprDef ExprDef;", "typedef struct {\n ExprCommon expr;\n xkb_atom_t ident;\n} ExprIdent;", "typedef struct {\n ExprCommon expr;\n xkb_atom_t str;\n} ExprString;", "typedef struct {\n ExprCommon expr;\n bool set;\n} ExprBoolean;", "typedef struct {\n ExprCommon expr;\n int ival;\n} ExprInteger;", "typedef struct {\n ExprCommon expr;", " /* We don't support floats, but we still represnt them in the AST, in\n * order to provide proper error messages. */\n} ExprFloat;", "typedef struct {\n ExprCommon expr;", " xkb_atom_t key_name;\n} ExprKeyName;", "typedef struct {\n ExprCommon expr;\n ExprDef *left;\n ExprDef *right;\n} ExprBinary;", "typedef struct {\n ExprCommon expr;\n ExprDef *child;\n} ExprUnary;", "typedef struct {\n ExprCommon expr;\n xkb_atom_t element;\n xkb_atom_t field;\n} ExprFieldRef;", "typedef struct {\n ExprCommon expr;\n xkb_atom_t element;\n xkb_atom_t field;\n ExprDef *entry;\n} ExprArrayRef;", "typedef struct {\n ExprCommon expr;\n xkb_atom_t name;\n ExprDef *args;\n} ExprAction;", "typedef struct {\n ExprCommon expr;\n darray(xkb_keysym_t) syms;\n darray(unsigned int) symsMapIndex;\n darray(unsigned int) symsNumEntries;\n} ExprKeysymList;", "union ExprDef {\n ParseCommon common;\n /* Maybe someday we can use C11 anonymous struct for ExprCommon here. */\n ExprCommon expr;\n ExprIdent ident;\n ExprString string;\n ExprBoolean boolean;\n ExprInteger integer;\n ExprKeyName key_name;\n ExprBinary binary;\n ExprUnary unary;\n ExprFieldRef field_ref;\n ExprArrayRef array_ref;\n ExprAction action;\n ExprKeysymList keysym_list;\n};", "typedef struct {\n ParseCommon common;\n enum merge_mode merge;\n ExprDef *name;\n ExprDef *value;\n} VarDef;", "typedef struct {\n ParseCommon common;\n enum merge_mode merge;\n xkb_atom_t name;\n ExprDef *value;\n} VModDef;", "typedef struct {\n ParseCommon common;\n enum merge_mode merge;\n xkb_atom_t name;\n int64_t value;\n} KeycodeDef;", "typedef struct {\n ParseCommon common;\n enum merge_mode merge;\n xkb_atom_t alias;\n xkb_atom_t real;\n} KeyAliasDef;", "typedef struct {\n ParseCommon common;\n enum merge_mode merge;\n xkb_atom_t name;\n VarDef *body;\n} KeyTypeDef;", "typedef struct {\n ParseCommon common;\n enum merge_mode merge;\n xkb_atom_t keyName;\n VarDef *symbols;\n} SymbolsDef;", "typedef struct {\n ParseCommon common;\n enum merge_mode merge;\n xkb_atom_t modifier;\n ExprDef *keys;\n} ModMapDef;", "typedef struct {\n ParseCommon common;\n enum merge_mode merge;\n unsigned group;\n ExprDef *def;\n} GroupCompatDef;", "typedef struct {\n ParseCommon common;\n enum merge_mode merge;\n xkb_keysym_t sym;\n ExprDef *match;\n VarDef *def;\n} InterpDef;", "typedef struct {\n ParseCommon common;\n enum merge_mode merge;\n unsigned ndx;\n ExprDef *name;\n bool virtual;\n} LedNameDef;", "typedef struct {\n ParseCommon common;\n enum merge_mode merge;\n xkb_atom_t name;\n VarDef *body;\n} LedMapDef;", "enum xkb_map_flags {\n MAP_IS_DEFAULT = (1 << 0),\n MAP_IS_PARTIAL = (1 << 1),\n MAP_IS_HIDDEN = (1 << 2),\n MAP_HAS_ALPHANUMERIC = (1 << 3),\n MAP_HAS_MODIFIER = (1 << 4),\n MAP_HAS_KEYPAD = (1 << 5),\n MAP_HAS_FN = (1 << 6),\n MAP_IS_ALTGR = (1 << 7),\n};", "typedef struct {\n ParseCommon common;\n enum xkb_file_type file_type;\n char *name;\n ParseCommon *defs;\n enum xkb_map_flags flags;\n} XkbFile;", "#endif" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [785, 37, 190, 691], "buggy_code_start_loc": [108, 37, 97, 594], "filenames": ["src/xkbcomp/ast-build.c", "src/xkbcomp/ast-build.h", "src/xkbcomp/ast.h", "src/xkbcomp/parser.y"], "fixing_code_end_loc": [794, 41, 198, 691], "fixing_code_start_loc": [109, 38, 98, 594], "message": "Unchecked NULL pointer usage in xkbcommon before 0.8.1 could be used by local attackers to crash (NULL pointer dereference) the xkbcommon parser by supplying a crafted keymap file, because geometry tokens were desupported incorrectly.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xkbcommon_project:xkbcommon:*:*:*:*:*:*:*:*", "matchCriteriaId": "2F9BAF72-405A-41EA-AA6D-509128B3E4AD", "versionEndExcluding": "0.8.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:lts:*:*:*", "matchCriteriaId": "B5A6F2F3-4894-4392-8296-3B8DD2679084", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:16.04:*:*:*:lts:*:*:*", "matchCriteriaId": "F7016A2A-8365-4F1A-89A2-7A19F2BCAE5B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:18.04:*:*:*:lts:*:*:*", "matchCriteriaId": "23A7C53F-B80F-4E6A-AFA9-58EEA84BE11D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Unchecked NULL pointer usage in xkbcommon before 0.8.1 could be used by local attackers to crash (NULL pointer dereference) the xkbcommon parser by supplying a crafted keymap file, because geometry tokens were desupported incorrectly."}, {"lang": "es", "value": "El uso de un puntero NULL no verificado en xkbcommon en versiones anteriores a la 0.8.1 podr\u00eda ser aprovechado por atacantes locales para provocar el cierre inesperado (desreferencia de puntero NULL) del analizador xkbcommon proporcionando un archivo keymap manipulado, debido a que los tokens de geometr\u00eda dejaron de ser soportados incorrectamente."}], "evaluatorComment": null, "id": "CVE-2018-15854", "lastModified": "2019-08-06T17:15:24.947", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 2.1, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-08-25T21:29:01.593", "references": [{"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2019:2079"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/xkbcommon/libxkbcommon/commit/e3cacae7b1bfda0d839c280494f23284a1187adf"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://lists.freedesktop.org/archives/wayland-devel/2018-August/039232.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/201810-05"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3786-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3786-2/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/xkbcommon/libxkbcommon/commit/e3cacae7b1bfda0d839c280494f23284a1187adf"}, "type": "CWE-476"}
321
Determine whether the {function_name} code is vulnerable or not.
[ "/************************************************************\n Copyright (c) 1994 by Silicon Graphics Computer Systems, Inc.", " Permission to use, copy, modify, and distribute this\n software and its documentation for any purpose and without\n fee is hereby granted, provided that the above copyright\n notice appear in all copies and that both that copyright\n notice and this permission notice appear in supporting\n documentation, and that the name of Silicon Graphics not be\n used in advertising or publicity pertaining to distribution\n of the software without specific prior written permission.\n Silicon Graphics makes no representation about the suitability\n of this software for any purpose. It is provided \"as is\"\n without any express or implied warranty.", " SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS\n SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON\n GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\n DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,\n DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE\n OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH\n THE USE OR PERFORMANCE OF THIS SOFTWARE.", " ********************************************************/", "/*\n * The parser should work with reasonably recent versions of either\n * bison or byacc. So if you make changes, try to make sure it works\n * in both!\n */", "%{\n#include \"xkbcomp/xkbcomp-priv.h\"\n#include \"xkbcomp/ast-build.h\"\n#include \"xkbcomp/parser-priv.h\"\n#include \"scanner-utils.h\"", "struct parser_param {\n struct xkb_context *ctx;\n struct scanner *scanner;\n XkbFile *rtrn;\n bool more_maps;\n};", "#define parser_err(param, fmt, ...) \\\n scanner_err((param)->scanner, fmt, ##__VA_ARGS__)", "#define parser_warn(param, fmt, ...) \\\n scanner_warn((param)->scanner, fmt, ##__VA_ARGS__)", "static void\n_xkbcommon_error(struct parser_param *param, const char *msg)\n{\n parser_err(param, \"%s\", msg);\n}", "static bool\nresolve_keysym(const char *name, xkb_keysym_t *sym_rtrn)\n{\n xkb_keysym_t sym;", " if (!name || istreq(name, \"any\") || istreq(name, \"nosymbol\")) {\n *sym_rtrn = XKB_KEY_NoSymbol;\n return true;\n }", " if (istreq(name, \"none\") || istreq(name, \"voidsymbol\")) {\n *sym_rtrn = XKB_KEY_VoidSymbol;\n return true;\n }", " sym = xkb_keysym_from_name(name, XKB_KEYSYM_NO_FLAGS);\n if (sym != XKB_KEY_NoSymbol) {\n *sym_rtrn = sym;\n return true;\n }", " return false;\n}", "#define param_scanner param->scanner\n%}", "%pure-parser\n%lex-param { struct scanner *param_scanner }\n%parse-param { struct parser_param *param }", "%token\n END_OF_FILE 0\n ERROR_TOK 255\n XKB_KEYMAP 1\n XKB_KEYCODES 2\n XKB_TYPES 3\n XKB_SYMBOLS 4\n XKB_COMPATMAP 5\n XKB_GEOMETRY 6\n XKB_SEMANTICS 7\n XKB_LAYOUT 8\n INCLUDE 10\n OVERRIDE 11\n AUGMENT 12\n REPLACE 13\n ALTERNATE 14\n VIRTUAL_MODS 20\n TYPE 21\n INTERPRET 22\n ACTION_TOK 23\n KEY 24\n ALIAS 25\n GROUP 26\n MODIFIER_MAP 27\n INDICATOR 28\n SHAPE 29\n KEYS 30\n ROW 31\n SECTION 32\n OVERLAY 33\n TEXT 34\n OUTLINE 35\n SOLID 36\n LOGO 37\n VIRTUAL 38\n EQUALS 40\n PLUS 41\n MINUS 42\n DIVIDE 43\n TIMES 44\n OBRACE 45\n CBRACE 46\n OPAREN 47\n CPAREN 48\n OBRACKET 49\n CBRACKET 50\n DOT 51\n COMMA 52\n SEMI 53\n EXCLAM 54\n INVERT 55\n STRING 60\n INTEGER 61\n FLOAT 62\n IDENT 63\n KEYNAME 64\n PARTIAL 70\n DEFAULT 71\n HIDDEN 72\n ALPHANUMERIC_KEYS 73\n MODIFIER_KEYS 74\n KEYPAD_KEYS 75\n FUNCTION_KEYS 76\n ALTERNATE_GROUP 77", "%right EQUALS\n%left PLUS MINUS\n%left TIMES DIVIDE\n%left EXCLAM INVERT\n%left OPAREN", "%start XkbFile", "%union {\n int ival;\n int64_t num;\n enum xkb_file_type file_type;\n char *str;\n xkb_atom_t atom;\n enum merge_mode merge;\n enum xkb_map_flags mapFlags;\n xkb_keysym_t keysym;\n ParseCommon *any;\n ExprDef *expr;\n VarDef *var;\n VModDef *vmod;\n InterpDef *interp;\n KeyTypeDef *keyType;\n SymbolsDef *syms;\n ModMapDef *modMask;\n GroupCompatDef *groupCompat;\n LedMapDef *ledMap;\n LedNameDef *ledName;\n KeycodeDef *keyCode;\n KeyAliasDef *keyAlias;\n void *geom;\n XkbFile *file;\n}", "%type <num> INTEGER FLOAT\n%type <str> IDENT STRING\n%type <atom> KEYNAME\n%type <num> KeyCode\n%type <ival> Number Integer Float SignedNumber DoodadType\n%type <merge> MergeMode OptMergeMode\n%type <file_type> XkbCompositeType FileType\n%type <mapFlags> Flag Flags OptFlags\n%type <str> MapName OptMapName\n%type <atom> FieldSpec Ident Element String\n%type <keysym> KeySym\n%type <any> DeclList Decl\n%type <expr> OptExprList ExprList Expr Term Lhs Terminal ArrayInit KeySyms\n%type <expr> OptKeySymList KeySymList Action ActionList Coord CoordList\n%type <var> VarDecl VarDeclList SymbolsBody SymbolsVarDecl\n%type <vmod> VModDecl VModDefList VModDef\n%type <interp> InterpretDecl InterpretMatch\n%type <keyType> KeyTypeDecl\n%type <syms> SymbolsDecl\n%type <modMask> ModMapDecl\n%type <groupCompat> GroupCompatDecl\n%type <ledMap> LedMapDecl\n%type <ledName> LedNameDecl\n%type <keyCode> KeyNameDecl\n%type <keyAlias> KeyAliasDecl\n%type <geom> ShapeDecl SectionDecl SectionBody SectionBodyItem RowBody RowBodyItem\n%type <geom> Keys Key OverlayDecl OverlayKeyList OverlayKey OutlineList OutlineInList\n%type <geom> DoodadDecl\n%type <file> XkbFile XkbMapConfigList XkbMapConfig\n%type <file> XkbCompositeMap", "%destructor { FreeStmt((ParseCommon *) $$); }\n <any> <expr> <var> <vmod> <interp> <keyType> <syms> <modMask> <groupCompat>\n <ledMap> <ledName> <keyCode> <keyAlias>\n/* The destructor also runs on the start symbol when the parser *succeeds*.\n * The `if` here catches this case. */\n%destructor { if (!param->rtrn) FreeXkbFile($$); } <file>\n%destructor { free($$); } <str>", "%%", "/*\n * An actual file may contain more than one map. However, if we do things\n * in the normal yacc way, i.e. aggregate all of the maps into a list and\n * let the caller find the map it wants, we end up scanning and parsing a\n * lot of unneeded maps (in the end we always just need one).\n * Instead of doing that, we make yyparse return one map at a time, and\n * then call it repeatedly until we find the map we need. Once we find it,\n * we don't need to parse everything that follows in the file.\n * This does mean that if we e.g. always use the first map, the file may\n * contain complete garbage after that. But it's worth it.\n */", "XkbFile : XkbCompositeMap\n { $$ = param->rtrn = $1; param->more_maps = true; }\n | XkbMapConfig\n { $$ = param->rtrn = $1; param->more_maps = true; YYACCEPT; }\n | END_OF_FILE\n { $$ = param->rtrn = NULL; param->more_maps = false; }\n ;", "XkbCompositeMap : OptFlags XkbCompositeType OptMapName OBRACE\n XkbMapConfigList\n CBRACE SEMI\n { $$ = XkbFileCreate($2, $3, (ParseCommon *) $5, $1); }\n ;", "XkbCompositeType: XKB_KEYMAP { $$ = FILE_TYPE_KEYMAP; }\n | XKB_SEMANTICS { $$ = FILE_TYPE_KEYMAP; }\n | XKB_LAYOUT { $$ = FILE_TYPE_KEYMAP; }\n ;", "XkbMapConfigList : XkbMapConfigList XkbMapConfig\n {\n if (!$2)\n $$ = $1;\n else\n $$ = (XkbFile *) AppendStmt((ParseCommon *) $1,\n (ParseCommon *) $2);\n }\n | XkbMapConfig\n { $$ = $1; }\n ;", "XkbMapConfig : OptFlags FileType OptMapName OBRACE\n DeclList\n CBRACE SEMI\n {\n if ($2 == FILE_TYPE_GEOMETRY) {\n free($3);\n FreeStmt($5);\n $$ = NULL;\n }\n else {\n $$ = XkbFileCreate($2, $3, $5, $1);\n }\n }\n ;", "FileType : XKB_KEYCODES { $$ = FILE_TYPE_KEYCODES; }\n | XKB_TYPES { $$ = FILE_TYPE_TYPES; }\n | XKB_COMPATMAP { $$ = FILE_TYPE_COMPAT; }\n | XKB_SYMBOLS { $$ = FILE_TYPE_SYMBOLS; }\n | XKB_GEOMETRY { $$ = FILE_TYPE_GEOMETRY; }\n ;", "OptFlags : Flags { $$ = $1; }\n | { $$ = 0; }\n ;", "Flags : Flags Flag { $$ = ($1 | $2); }\n | Flag { $$ = $1; }\n ;", "Flag : PARTIAL { $$ = MAP_IS_PARTIAL; }\n | DEFAULT { $$ = MAP_IS_DEFAULT; }\n | HIDDEN { $$ = MAP_IS_HIDDEN; }\n | ALPHANUMERIC_KEYS { $$ = MAP_HAS_ALPHANUMERIC; }\n | MODIFIER_KEYS { $$ = MAP_HAS_MODIFIER; }\n | KEYPAD_KEYS { $$ = MAP_HAS_KEYPAD; }\n | FUNCTION_KEYS { $$ = MAP_HAS_FN; }\n | ALTERNATE_GROUP { $$ = MAP_IS_ALTGR; }\n ;", "DeclList : DeclList Decl\n { $$ = AppendStmt($1, $2); }\n | { $$ = NULL; }\n ;", "Decl : OptMergeMode VarDecl\n {\n $2->merge = $1;\n $$ = (ParseCommon *) $2;\n }\n | OptMergeMode VModDecl\n {\n $2->merge = $1;\n $$ = (ParseCommon *) $2;\n }\n | OptMergeMode InterpretDecl\n {\n $2->merge = $1;\n $$ = (ParseCommon *) $2;\n }\n | OptMergeMode KeyNameDecl\n {\n $2->merge = $1;\n $$ = (ParseCommon *) $2;\n }\n | OptMergeMode KeyAliasDecl\n {\n $2->merge = $1;\n $$ = (ParseCommon *) $2;\n }\n | OptMergeMode KeyTypeDecl\n {\n $2->merge = $1;\n $$ = (ParseCommon *) $2;\n }\n | OptMergeMode SymbolsDecl\n {\n $2->merge = $1;\n $$ = (ParseCommon *) $2;\n }\n | OptMergeMode ModMapDecl\n {\n $2->merge = $1;\n $$ = (ParseCommon *) $2;\n }\n | OptMergeMode GroupCompatDecl\n {\n $2->merge = $1;\n $$ = (ParseCommon *) $2;\n }\n | OptMergeMode LedMapDecl\n {\n $2->merge = $1;\n $$ = (ParseCommon *) $2;\n }\n | OptMergeMode LedNameDecl\n {\n $2->merge = $1;\n $$ = (ParseCommon *) $2;\n }\n | OptMergeMode ShapeDecl { $$ = NULL; }\n | OptMergeMode SectionDecl { $$ = NULL; }\n | OptMergeMode DoodadDecl { $$ = NULL; }\n | MergeMode STRING\n {\n $$ = (ParseCommon *) IncludeCreate(param->ctx, $2, $1);\n free($2);\n }\n ;", "VarDecl : Lhs EQUALS Expr SEMI\n { $$ = VarCreate($1, $3); }\n | Ident SEMI\n { $$ = BoolVarCreate($1, true); }\n | EXCLAM Ident SEMI\n { $$ = BoolVarCreate($2, false); }\n ;", "KeyNameDecl : KEYNAME EQUALS KeyCode SEMI\n { $$ = KeycodeCreate($1, $3); }\n ;", "KeyAliasDecl : ALIAS KEYNAME EQUALS KEYNAME SEMI\n { $$ = KeyAliasCreate($2, $4); }\n ;", "VModDecl : VIRTUAL_MODS VModDefList SEMI\n { $$ = $2; }\n ;", "VModDefList : VModDefList COMMA VModDef\n { $$ = (VModDef *) AppendStmt((ParseCommon *) $1,\n (ParseCommon *) $3); }\n | VModDef\n { $$ = $1; }\n ;", "VModDef : Ident\n { $$ = VModCreate($1, NULL); }\n | Ident EQUALS Expr\n { $$ = VModCreate($1, $3); }\n ;", "InterpretDecl : INTERPRET InterpretMatch OBRACE\n VarDeclList\n CBRACE SEMI\n { $2->def = $4; $$ = $2; }\n ;", "InterpretMatch : KeySym PLUS Expr\n { $$ = InterpCreate($1, $3); }\n | KeySym\n { $$ = InterpCreate($1, NULL); }\n ;", "VarDeclList : VarDeclList VarDecl\n { $$ = (VarDef *) AppendStmt((ParseCommon *) $1,\n (ParseCommon *) $2); }\n | VarDecl\n { $$ = $1; }\n ;", "KeyTypeDecl : TYPE String OBRACE\n VarDeclList\n CBRACE SEMI\n { $$ = KeyTypeCreate($2, $4); }\n ;", "SymbolsDecl : KEY KEYNAME OBRACE\n SymbolsBody\n CBRACE SEMI\n { $$ = SymbolsCreate($2, $4); }\n ;", "SymbolsBody : SymbolsBody COMMA SymbolsVarDecl\n { $$ = (VarDef *) AppendStmt((ParseCommon *) $1,\n (ParseCommon *) $3); }\n | SymbolsVarDecl\n { $$ = $1; }\n | { $$ = NULL; }\n ;", "SymbolsVarDecl : Lhs EQUALS Expr { $$ = VarCreate($1, $3); }\n | Lhs EQUALS ArrayInit { $$ = VarCreate($1, $3); }\n | Ident { $$ = BoolVarCreate($1, true); }\n | EXCLAM Ident { $$ = BoolVarCreate($2, false); }\n | ArrayInit { $$ = VarCreate(NULL, $1); }\n ;", "ArrayInit : OBRACKET OptKeySymList CBRACKET\n { $$ = $2; }\n | OBRACKET ActionList CBRACKET\n { $$ = ExprCreateUnary(EXPR_ACTION_LIST, EXPR_TYPE_ACTION, $2); }\n ;", "GroupCompatDecl : GROUP Integer EQUALS Expr SEMI\n { $$ = GroupCompatCreate($2, $4); }\n ;", "ModMapDecl : MODIFIER_MAP Ident OBRACE ExprList CBRACE SEMI\n { $$ = ModMapCreate($2, $4); }\n ;", "LedMapDecl: INDICATOR String OBRACE VarDeclList CBRACE SEMI\n { $$ = LedMapCreate($2, $4); }\n ;", "LedNameDecl: INDICATOR Integer EQUALS Expr SEMI\n { $$ = LedNameCreate($2, $4, false); }\n | VIRTUAL INDICATOR Integer EQUALS Expr SEMI\n { $$ = LedNameCreate($3, $5, true); }\n ;", "ShapeDecl : SHAPE String OBRACE OutlineList CBRACE SEMI\n { $$ = NULL; }\n | SHAPE String OBRACE CoordList CBRACE SEMI\n { (void) $4; $$ = NULL; }\n ;", "SectionDecl : SECTION String OBRACE SectionBody CBRACE SEMI\n { $$ = NULL; }\n ;", "SectionBody : SectionBody SectionBodyItem { $$ = NULL;}\n | SectionBodyItem { $$ = NULL; }\n ;", "SectionBodyItem : ROW OBRACE RowBody CBRACE SEMI\n { $$ = NULL; }\n | VarDecl\n { FreeStmt((ParseCommon *) $1); $$ = NULL; }\n | DoodadDecl\n { $$ = NULL; }\n | LedMapDecl\n { FreeStmt((ParseCommon *) $1); $$ = NULL; }\n | OverlayDecl\n { $$ = NULL; }\n ;", "RowBody : RowBody RowBodyItem { $$ = NULL;}\n | RowBodyItem { $$ = NULL; }\n ;", "RowBodyItem : KEYS OBRACE Keys CBRACE SEMI { $$ = NULL; }\n | VarDecl\n { FreeStmt((ParseCommon *) $1); $$ = NULL; }\n ;", "Keys : Keys COMMA Key { $$ = NULL; }\n | Key { $$ = NULL; }\n ;", "Key : KEYNAME\n { $$ = NULL; }\n | OBRACE ExprList CBRACE\n { FreeStmt((ParseCommon *) $2); $$ = NULL; }\n ;", "OverlayDecl : OVERLAY String OBRACE OverlayKeyList CBRACE SEMI\n { $$ = NULL; }\n ;", "OverlayKeyList : OverlayKeyList COMMA OverlayKey { $$ = NULL; }\n | OverlayKey { $$ = NULL; }\n ;", "OverlayKey : KEYNAME EQUALS KEYNAME { $$ = NULL; }\n ;", "OutlineList : OutlineList COMMA OutlineInList\n { $$ = NULL;}\n | OutlineInList\n { $$ = NULL; }\n ;", "OutlineInList : OBRACE CoordList CBRACE\n { (void) $2; $$ = NULL; }\n | Ident EQUALS OBRACE CoordList CBRACE\n { (void) $4; $$ = NULL; }\n | Ident EQUALS Expr\n { FreeStmt((ParseCommon *) $3); $$ = NULL; }\n ;", "CoordList : CoordList COMMA Coord\n { (void) $1; (void) $3; $$ = NULL; }\n | Coord\n { (void) $1; $$ = NULL; }\n ;", "Coord : OBRACKET SignedNumber COMMA SignedNumber CBRACKET\n { $$ = NULL; }\n ;", "DoodadDecl : DoodadType String OBRACE VarDeclList CBRACE SEMI\n { FreeStmt((ParseCommon *) $4); $$ = NULL; }\n ;", "DoodadType : TEXT { $$ = 0; }\n | OUTLINE { $$ = 0; }\n | SOLID { $$ = 0; }\n | LOGO { $$ = 0; }\n ;", "FieldSpec : Ident { $$ = $1; }\n | Element { $$ = $1; }\n ;", "Element : ACTION_TOK\n { $$ = xkb_atom_intern_literal(param->ctx, \"action\"); }\n | INTERPRET\n { $$ = xkb_atom_intern_literal(param->ctx, \"interpret\"); }\n | TYPE\n { $$ = xkb_atom_intern_literal(param->ctx, \"type\"); }\n | KEY\n { $$ = xkb_atom_intern_literal(param->ctx, \"key\"); }\n | GROUP\n { $$ = xkb_atom_intern_literal(param->ctx, \"group\"); }\n | MODIFIER_MAP\n {$$ = xkb_atom_intern_literal(param->ctx, \"modifier_map\");}\n | INDICATOR\n { $$ = xkb_atom_intern_literal(param->ctx, \"indicator\"); }\n | SHAPE", " { $$ = XKB_ATOM_NONE; }", " | ROW", " { $$ = XKB_ATOM_NONE; }", " | SECTION", " { $$ = XKB_ATOM_NONE; }", " | TEXT", " { $$ = XKB_ATOM_NONE; }", " ;", "OptMergeMode : MergeMode { $$ = $1; }\n | { $$ = MERGE_DEFAULT; }\n ;", "MergeMode : INCLUDE { $$ = MERGE_DEFAULT; }\n | AUGMENT { $$ = MERGE_AUGMENT; }\n | OVERRIDE { $$ = MERGE_OVERRIDE; }\n | REPLACE { $$ = MERGE_REPLACE; }\n | ALTERNATE\n {\n /*\n * This used to be MERGE_ALT_FORM. This functionality was\n * unused and has been removed.\n */\n $$ = MERGE_DEFAULT;\n }\n ;", "OptExprList : ExprList { $$ = $1; }\n | { $$ = NULL; }\n ;", "ExprList : ExprList COMMA Expr\n { $$ = (ExprDef *) AppendStmt((ParseCommon *) $1,\n (ParseCommon *) $3); }\n | Expr\n { $$ = $1; }\n ;", "Expr : Expr DIVIDE Expr\n { $$ = ExprCreateBinary(EXPR_DIVIDE, $1, $3); }\n | Expr PLUS Expr\n { $$ = ExprCreateBinary(EXPR_ADD, $1, $3); }\n | Expr MINUS Expr\n { $$ = ExprCreateBinary(EXPR_SUBTRACT, $1, $3); }\n | Expr TIMES Expr\n { $$ = ExprCreateBinary(EXPR_MULTIPLY, $1, $3); }\n | Lhs EQUALS Expr\n { $$ = ExprCreateBinary(EXPR_ASSIGN, $1, $3); }\n | Term\n { $$ = $1; }\n ;", "Term : MINUS Term\n { $$ = ExprCreateUnary(EXPR_NEGATE, $2->expr.value_type, $2); }\n | PLUS Term\n { $$ = ExprCreateUnary(EXPR_UNARY_PLUS, $2->expr.value_type, $2); }\n | EXCLAM Term\n { $$ = ExprCreateUnary(EXPR_NOT, EXPR_TYPE_BOOLEAN, $2); }\n | INVERT Term\n { $$ = ExprCreateUnary(EXPR_INVERT, $2->expr.value_type, $2); }\n | Lhs\n { $$ = $1; }\n | FieldSpec OPAREN OptExprList CPAREN %prec OPAREN\n { $$ = ExprCreateAction($1, $3); }\n | Terminal\n { $$ = $1; }\n | OPAREN Expr CPAREN\n { $$ = $2; }\n ;", "ActionList : ActionList COMMA Action\n { $$ = (ExprDef *) AppendStmt((ParseCommon *) $1,\n (ParseCommon *) $3); }\n | Action\n { $$ = $1; }\n ;", "Action : FieldSpec OPAREN OptExprList CPAREN\n { $$ = ExprCreateAction($1, $3); }\n ;", "Lhs : FieldSpec\n { $$ = ExprCreateIdent($1); }\n | FieldSpec DOT FieldSpec\n { $$ = ExprCreateFieldRef($1, $3); }\n | FieldSpec OBRACKET Expr CBRACKET\n { $$ = ExprCreateArrayRef(XKB_ATOM_NONE, $1, $3); }\n | FieldSpec DOT FieldSpec OBRACKET Expr CBRACKET\n { $$ = ExprCreateArrayRef($1, $3, $5); }\n ;", "Terminal : String\n { $$ = ExprCreateString($1); }\n | Integer\n { $$ = ExprCreateInteger($1); }\n | Float", " { $$ = NULL; }", " | KEYNAME\n { $$ = ExprCreateKeyName($1); }\n ;", "OptKeySymList : KeySymList { $$ = $1; }\n | { $$ = NULL; }\n ;", "KeySymList : KeySymList COMMA KeySym\n { $$ = ExprAppendKeysymList($1, $3); }\n | KeySymList COMMA KeySyms\n { $$ = ExprAppendMultiKeysymList($1, $3); }\n | KeySym\n { $$ = ExprCreateKeysymList($1); }\n | KeySyms\n { $$ = ExprCreateMultiKeysymList($1); }\n ;", "KeySyms : OBRACE KeySymList CBRACE\n { $$ = $2; }\n ;", "KeySym : IDENT\n {\n if (!resolve_keysym($1, &$$))\n parser_warn(param, \"unrecognized keysym \\\"%s\\\"\", $1);\n free($1);\n }\n | SECTION { $$ = XKB_KEY_section; }\n | Integer\n {\n if ($1 < 0) {\n parser_warn(param, \"unrecognized keysym \\\"%d\\\"\", $1);\n $$ = XKB_KEY_NoSymbol;\n }\n else if ($1 < 10) { /* XKB_KEY_0 .. XKB_KEY_9 */\n $$ = XKB_KEY_0 + (xkb_keysym_t) $1;\n }\n else {\n char buf[17];\n snprintf(buf, sizeof(buf), \"0x%x\", $1);\n if (!resolve_keysym(buf, &$$)) {\n parser_warn(param, \"unrecognized keysym \\\"%s\\\"\", buf);\n $$ = XKB_KEY_NoSymbol;\n }\n }\n }\n ;", "SignedNumber : MINUS Number { $$ = -$2; }\n | Number { $$ = $1; }\n ;", "Number : FLOAT { $$ = $1; }\n | INTEGER { $$ = $1; }\n ;", "Float : FLOAT { $$ = 0; }\n ;", "Integer : INTEGER { $$ = $1; }\n ;", "KeyCode : INTEGER { $$ = $1; }\n ;", "Ident : IDENT { $$ = xkb_atom_steal(param->ctx, $1); }\n | DEFAULT { $$ = xkb_atom_intern_literal(param->ctx, \"default\"); }\n ;", "String : STRING { $$ = xkb_atom_steal(param->ctx, $1); }\n ;", "OptMapName : MapName { $$ = $1; }\n | { $$ = NULL; }\n ;", "MapName : STRING { $$ = $1; }\n ;", "%%", "XkbFile *\nparse(struct xkb_context *ctx, struct scanner *scanner, const char *map)\n{\n int ret;\n XkbFile *first = NULL;\n struct parser_param param = {\n .scanner = scanner,\n .ctx = ctx,\n .rtrn = NULL,\n };", " /*\n * If we got a specific map, we look for it exclusively and return\n * immediately upon finding it. Otherwise, we need to get the\n * default map. If we find a map marked as default, we return it\n * immediately. If there are no maps marked as default, we return\n * the first map in the file.\n */", " while ((ret = yyparse(&param)) == 0 && param.more_maps) {\n if (map) {\n if (streq_not_null(map, param.rtrn->name))\n return param.rtrn;\n else\n FreeXkbFile(param.rtrn);\n }\n else {\n if (param.rtrn->flags & MAP_IS_DEFAULT) {\n FreeXkbFile(first);\n return param.rtrn;\n }\n else if (!first) {\n first = param.rtrn;\n }\n else {\n FreeXkbFile(param.rtrn);\n }\n }\n param.rtrn = NULL;\n }", " if (ret != 0) {\n FreeXkbFile(first);\n return NULL;\n }", " if (first)\n log_vrb(ctx, 5,\n \"No map in include statement, but \\\"%s\\\" contains several; \"\n \"Using first defined map, \\\"%s\\\"\\n\",\n scanner->file_name, first->name);", " return first;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [785, 37, 190, 691], "buggy_code_start_loc": [108, 37, 97, 594], "filenames": ["src/xkbcomp/ast-build.c", "src/xkbcomp/ast-build.h", "src/xkbcomp/ast.h", "src/xkbcomp/parser.y"], "fixing_code_end_loc": [794, 41, 198, 691], "fixing_code_start_loc": [109, 38, 98, 594], "message": "Unchecked NULL pointer usage in xkbcommon before 0.8.1 could be used by local attackers to crash (NULL pointer dereference) the xkbcommon parser by supplying a crafted keymap file, because geometry tokens were desupported incorrectly.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xkbcommon_project:xkbcommon:*:*:*:*:*:*:*:*", "matchCriteriaId": "2F9BAF72-405A-41EA-AA6D-509128B3E4AD", "versionEndExcluding": "0.8.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:lts:*:*:*", "matchCriteriaId": "B5A6F2F3-4894-4392-8296-3B8DD2679084", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:16.04:*:*:*:lts:*:*:*", "matchCriteriaId": "F7016A2A-8365-4F1A-89A2-7A19F2BCAE5B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:18.04:*:*:*:lts:*:*:*", "matchCriteriaId": "23A7C53F-B80F-4E6A-AFA9-58EEA84BE11D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Unchecked NULL pointer usage in xkbcommon before 0.8.1 could be used by local attackers to crash (NULL pointer dereference) the xkbcommon parser by supplying a crafted keymap file, because geometry tokens were desupported incorrectly."}, {"lang": "es", "value": "El uso de un puntero NULL no verificado en xkbcommon en versiones anteriores a la 0.8.1 podr\u00eda ser aprovechado por atacantes locales para provocar el cierre inesperado (desreferencia de puntero NULL) del analizador xkbcommon proporcionando un archivo keymap manipulado, debido a que los tokens de geometr\u00eda dejaron de ser soportados incorrectamente."}], "evaluatorComment": null, "id": "CVE-2018-15854", "lastModified": "2019-08-06T17:15:24.947", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 2.1, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-08-25T21:29:01.593", "references": [{"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2019:2079"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/xkbcommon/libxkbcommon/commit/e3cacae7b1bfda0d839c280494f23284a1187adf"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://lists.freedesktop.org/archives/wayland-devel/2018-August/039232.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/201810-05"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3786-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3786-2/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/xkbcommon/libxkbcommon/commit/e3cacae7b1bfda0d839c280494f23284a1187adf"}, "type": "CWE-476"}
321
Determine whether the {function_name} code is vulnerable or not.
[ "/************************************************************\n Copyright (c) 1994 by Silicon Graphics Computer Systems, Inc.", " Permission to use, copy, modify, and distribute this\n software and its documentation for any purpose and without\n fee is hereby granted, provided that the above copyright\n notice appear in all copies and that both that copyright\n notice and this permission notice appear in supporting\n documentation, and that the name of Silicon Graphics not be\n used in advertising or publicity pertaining to distribution\n of the software without specific prior written permission.\n Silicon Graphics makes no representation about the suitability\n of this software for any purpose. It is provided \"as is\"\n without any express or implied warranty.", " SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS\n SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON\n GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\n DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,\n DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE\n OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH\n THE USE OR PERFORMANCE OF THIS SOFTWARE.", " ********************************************************/", "/*\n * The parser should work with reasonably recent versions of either\n * bison or byacc. So if you make changes, try to make sure it works\n * in both!\n */", "%{\n#include \"xkbcomp/xkbcomp-priv.h\"\n#include \"xkbcomp/ast-build.h\"\n#include \"xkbcomp/parser-priv.h\"\n#include \"scanner-utils.h\"", "struct parser_param {\n struct xkb_context *ctx;\n struct scanner *scanner;\n XkbFile *rtrn;\n bool more_maps;\n};", "#define parser_err(param, fmt, ...) \\\n scanner_err((param)->scanner, fmt, ##__VA_ARGS__)", "#define parser_warn(param, fmt, ...) \\\n scanner_warn((param)->scanner, fmt, ##__VA_ARGS__)", "static void\n_xkbcommon_error(struct parser_param *param, const char *msg)\n{\n parser_err(param, \"%s\", msg);\n}", "static bool\nresolve_keysym(const char *name, xkb_keysym_t *sym_rtrn)\n{\n xkb_keysym_t sym;", " if (!name || istreq(name, \"any\") || istreq(name, \"nosymbol\")) {\n *sym_rtrn = XKB_KEY_NoSymbol;\n return true;\n }", " if (istreq(name, \"none\") || istreq(name, \"voidsymbol\")) {\n *sym_rtrn = XKB_KEY_VoidSymbol;\n return true;\n }", " sym = xkb_keysym_from_name(name, XKB_KEYSYM_NO_FLAGS);\n if (sym != XKB_KEY_NoSymbol) {\n *sym_rtrn = sym;\n return true;\n }", " return false;\n}", "#define param_scanner param->scanner\n%}", "%pure-parser\n%lex-param { struct scanner *param_scanner }\n%parse-param { struct parser_param *param }", "%token\n END_OF_FILE 0\n ERROR_TOK 255\n XKB_KEYMAP 1\n XKB_KEYCODES 2\n XKB_TYPES 3\n XKB_SYMBOLS 4\n XKB_COMPATMAP 5\n XKB_GEOMETRY 6\n XKB_SEMANTICS 7\n XKB_LAYOUT 8\n INCLUDE 10\n OVERRIDE 11\n AUGMENT 12\n REPLACE 13\n ALTERNATE 14\n VIRTUAL_MODS 20\n TYPE 21\n INTERPRET 22\n ACTION_TOK 23\n KEY 24\n ALIAS 25\n GROUP 26\n MODIFIER_MAP 27\n INDICATOR 28\n SHAPE 29\n KEYS 30\n ROW 31\n SECTION 32\n OVERLAY 33\n TEXT 34\n OUTLINE 35\n SOLID 36\n LOGO 37\n VIRTUAL 38\n EQUALS 40\n PLUS 41\n MINUS 42\n DIVIDE 43\n TIMES 44\n OBRACE 45\n CBRACE 46\n OPAREN 47\n CPAREN 48\n OBRACKET 49\n CBRACKET 50\n DOT 51\n COMMA 52\n SEMI 53\n EXCLAM 54\n INVERT 55\n STRING 60\n INTEGER 61\n FLOAT 62\n IDENT 63\n KEYNAME 64\n PARTIAL 70\n DEFAULT 71\n HIDDEN 72\n ALPHANUMERIC_KEYS 73\n MODIFIER_KEYS 74\n KEYPAD_KEYS 75\n FUNCTION_KEYS 76\n ALTERNATE_GROUP 77", "%right EQUALS\n%left PLUS MINUS\n%left TIMES DIVIDE\n%left EXCLAM INVERT\n%left OPAREN", "%start XkbFile", "%union {\n int ival;\n int64_t num;\n enum xkb_file_type file_type;\n char *str;\n xkb_atom_t atom;\n enum merge_mode merge;\n enum xkb_map_flags mapFlags;\n xkb_keysym_t keysym;\n ParseCommon *any;\n ExprDef *expr;\n VarDef *var;\n VModDef *vmod;\n InterpDef *interp;\n KeyTypeDef *keyType;\n SymbolsDef *syms;\n ModMapDef *modMask;\n GroupCompatDef *groupCompat;\n LedMapDef *ledMap;\n LedNameDef *ledName;\n KeycodeDef *keyCode;\n KeyAliasDef *keyAlias;\n void *geom;\n XkbFile *file;\n}", "%type <num> INTEGER FLOAT\n%type <str> IDENT STRING\n%type <atom> KEYNAME\n%type <num> KeyCode\n%type <ival> Number Integer Float SignedNumber DoodadType\n%type <merge> MergeMode OptMergeMode\n%type <file_type> XkbCompositeType FileType\n%type <mapFlags> Flag Flags OptFlags\n%type <str> MapName OptMapName\n%type <atom> FieldSpec Ident Element String\n%type <keysym> KeySym\n%type <any> DeclList Decl\n%type <expr> OptExprList ExprList Expr Term Lhs Terminal ArrayInit KeySyms\n%type <expr> OptKeySymList KeySymList Action ActionList Coord CoordList\n%type <var> VarDecl VarDeclList SymbolsBody SymbolsVarDecl\n%type <vmod> VModDecl VModDefList VModDef\n%type <interp> InterpretDecl InterpretMatch\n%type <keyType> KeyTypeDecl\n%type <syms> SymbolsDecl\n%type <modMask> ModMapDecl\n%type <groupCompat> GroupCompatDecl\n%type <ledMap> LedMapDecl\n%type <ledName> LedNameDecl\n%type <keyCode> KeyNameDecl\n%type <keyAlias> KeyAliasDecl\n%type <geom> ShapeDecl SectionDecl SectionBody SectionBodyItem RowBody RowBodyItem\n%type <geom> Keys Key OverlayDecl OverlayKeyList OverlayKey OutlineList OutlineInList\n%type <geom> DoodadDecl\n%type <file> XkbFile XkbMapConfigList XkbMapConfig\n%type <file> XkbCompositeMap", "%destructor { FreeStmt((ParseCommon *) $$); }\n <any> <expr> <var> <vmod> <interp> <keyType> <syms> <modMask> <groupCompat>\n <ledMap> <ledName> <keyCode> <keyAlias>\n/* The destructor also runs on the start symbol when the parser *succeeds*.\n * The `if` here catches this case. */\n%destructor { if (!param->rtrn) FreeXkbFile($$); } <file>\n%destructor { free($$); } <str>", "%%", "/*\n * An actual file may contain more than one map. However, if we do things\n * in the normal yacc way, i.e. aggregate all of the maps into a list and\n * let the caller find the map it wants, we end up scanning and parsing a\n * lot of unneeded maps (in the end we always just need one).\n * Instead of doing that, we make yyparse return one map at a time, and\n * then call it repeatedly until we find the map we need. Once we find it,\n * we don't need to parse everything that follows in the file.\n * This does mean that if we e.g. always use the first map, the file may\n * contain complete garbage after that. But it's worth it.\n */", "XkbFile : XkbCompositeMap\n { $$ = param->rtrn = $1; param->more_maps = true; }\n | XkbMapConfig\n { $$ = param->rtrn = $1; param->more_maps = true; YYACCEPT; }\n | END_OF_FILE\n { $$ = param->rtrn = NULL; param->more_maps = false; }\n ;", "XkbCompositeMap : OptFlags XkbCompositeType OptMapName OBRACE\n XkbMapConfigList\n CBRACE SEMI\n { $$ = XkbFileCreate($2, $3, (ParseCommon *) $5, $1); }\n ;", "XkbCompositeType: XKB_KEYMAP { $$ = FILE_TYPE_KEYMAP; }\n | XKB_SEMANTICS { $$ = FILE_TYPE_KEYMAP; }\n | XKB_LAYOUT { $$ = FILE_TYPE_KEYMAP; }\n ;", "XkbMapConfigList : XkbMapConfigList XkbMapConfig\n {\n if (!$2)\n $$ = $1;\n else\n $$ = (XkbFile *) AppendStmt((ParseCommon *) $1,\n (ParseCommon *) $2);\n }\n | XkbMapConfig\n { $$ = $1; }\n ;", "XkbMapConfig : OptFlags FileType OptMapName OBRACE\n DeclList\n CBRACE SEMI\n {\n if ($2 == FILE_TYPE_GEOMETRY) {\n free($3);\n FreeStmt($5);\n $$ = NULL;\n }\n else {\n $$ = XkbFileCreate($2, $3, $5, $1);\n }\n }\n ;", "FileType : XKB_KEYCODES { $$ = FILE_TYPE_KEYCODES; }\n | XKB_TYPES { $$ = FILE_TYPE_TYPES; }\n | XKB_COMPATMAP { $$ = FILE_TYPE_COMPAT; }\n | XKB_SYMBOLS { $$ = FILE_TYPE_SYMBOLS; }\n | XKB_GEOMETRY { $$ = FILE_TYPE_GEOMETRY; }\n ;", "OptFlags : Flags { $$ = $1; }\n | { $$ = 0; }\n ;", "Flags : Flags Flag { $$ = ($1 | $2); }\n | Flag { $$ = $1; }\n ;", "Flag : PARTIAL { $$ = MAP_IS_PARTIAL; }\n | DEFAULT { $$ = MAP_IS_DEFAULT; }\n | HIDDEN { $$ = MAP_IS_HIDDEN; }\n | ALPHANUMERIC_KEYS { $$ = MAP_HAS_ALPHANUMERIC; }\n | MODIFIER_KEYS { $$ = MAP_HAS_MODIFIER; }\n | KEYPAD_KEYS { $$ = MAP_HAS_KEYPAD; }\n | FUNCTION_KEYS { $$ = MAP_HAS_FN; }\n | ALTERNATE_GROUP { $$ = MAP_IS_ALTGR; }\n ;", "DeclList : DeclList Decl\n { $$ = AppendStmt($1, $2); }\n | { $$ = NULL; }\n ;", "Decl : OptMergeMode VarDecl\n {\n $2->merge = $1;\n $$ = (ParseCommon *) $2;\n }\n | OptMergeMode VModDecl\n {\n $2->merge = $1;\n $$ = (ParseCommon *) $2;\n }\n | OptMergeMode InterpretDecl\n {\n $2->merge = $1;\n $$ = (ParseCommon *) $2;\n }\n | OptMergeMode KeyNameDecl\n {\n $2->merge = $1;\n $$ = (ParseCommon *) $2;\n }\n | OptMergeMode KeyAliasDecl\n {\n $2->merge = $1;\n $$ = (ParseCommon *) $2;\n }\n | OptMergeMode KeyTypeDecl\n {\n $2->merge = $1;\n $$ = (ParseCommon *) $2;\n }\n | OptMergeMode SymbolsDecl\n {\n $2->merge = $1;\n $$ = (ParseCommon *) $2;\n }\n | OptMergeMode ModMapDecl\n {\n $2->merge = $1;\n $$ = (ParseCommon *) $2;\n }\n | OptMergeMode GroupCompatDecl\n {\n $2->merge = $1;\n $$ = (ParseCommon *) $2;\n }\n | OptMergeMode LedMapDecl\n {\n $2->merge = $1;\n $$ = (ParseCommon *) $2;\n }\n | OptMergeMode LedNameDecl\n {\n $2->merge = $1;\n $$ = (ParseCommon *) $2;\n }\n | OptMergeMode ShapeDecl { $$ = NULL; }\n | OptMergeMode SectionDecl { $$ = NULL; }\n | OptMergeMode DoodadDecl { $$ = NULL; }\n | MergeMode STRING\n {\n $$ = (ParseCommon *) IncludeCreate(param->ctx, $2, $1);\n free($2);\n }\n ;", "VarDecl : Lhs EQUALS Expr SEMI\n { $$ = VarCreate($1, $3); }\n | Ident SEMI\n { $$ = BoolVarCreate($1, true); }\n | EXCLAM Ident SEMI\n { $$ = BoolVarCreate($2, false); }\n ;", "KeyNameDecl : KEYNAME EQUALS KeyCode SEMI\n { $$ = KeycodeCreate($1, $3); }\n ;", "KeyAliasDecl : ALIAS KEYNAME EQUALS KEYNAME SEMI\n { $$ = KeyAliasCreate($2, $4); }\n ;", "VModDecl : VIRTUAL_MODS VModDefList SEMI\n { $$ = $2; }\n ;", "VModDefList : VModDefList COMMA VModDef\n { $$ = (VModDef *) AppendStmt((ParseCommon *) $1,\n (ParseCommon *) $3); }\n | VModDef\n { $$ = $1; }\n ;", "VModDef : Ident\n { $$ = VModCreate($1, NULL); }\n | Ident EQUALS Expr\n { $$ = VModCreate($1, $3); }\n ;", "InterpretDecl : INTERPRET InterpretMatch OBRACE\n VarDeclList\n CBRACE SEMI\n { $2->def = $4; $$ = $2; }\n ;", "InterpretMatch : KeySym PLUS Expr\n { $$ = InterpCreate($1, $3); }\n | KeySym\n { $$ = InterpCreate($1, NULL); }\n ;", "VarDeclList : VarDeclList VarDecl\n { $$ = (VarDef *) AppendStmt((ParseCommon *) $1,\n (ParseCommon *) $2); }\n | VarDecl\n { $$ = $1; }\n ;", "KeyTypeDecl : TYPE String OBRACE\n VarDeclList\n CBRACE SEMI\n { $$ = KeyTypeCreate($2, $4); }\n ;", "SymbolsDecl : KEY KEYNAME OBRACE\n SymbolsBody\n CBRACE SEMI\n { $$ = SymbolsCreate($2, $4); }\n ;", "SymbolsBody : SymbolsBody COMMA SymbolsVarDecl\n { $$ = (VarDef *) AppendStmt((ParseCommon *) $1,\n (ParseCommon *) $3); }\n | SymbolsVarDecl\n { $$ = $1; }\n | { $$ = NULL; }\n ;", "SymbolsVarDecl : Lhs EQUALS Expr { $$ = VarCreate($1, $3); }\n | Lhs EQUALS ArrayInit { $$ = VarCreate($1, $3); }\n | Ident { $$ = BoolVarCreate($1, true); }\n | EXCLAM Ident { $$ = BoolVarCreate($2, false); }\n | ArrayInit { $$ = VarCreate(NULL, $1); }\n ;", "ArrayInit : OBRACKET OptKeySymList CBRACKET\n { $$ = $2; }\n | OBRACKET ActionList CBRACKET\n { $$ = ExprCreateUnary(EXPR_ACTION_LIST, EXPR_TYPE_ACTION, $2); }\n ;", "GroupCompatDecl : GROUP Integer EQUALS Expr SEMI\n { $$ = GroupCompatCreate($2, $4); }\n ;", "ModMapDecl : MODIFIER_MAP Ident OBRACE ExprList CBRACE SEMI\n { $$ = ModMapCreate($2, $4); }\n ;", "LedMapDecl: INDICATOR String OBRACE VarDeclList CBRACE SEMI\n { $$ = LedMapCreate($2, $4); }\n ;", "LedNameDecl: INDICATOR Integer EQUALS Expr SEMI\n { $$ = LedNameCreate($2, $4, false); }\n | VIRTUAL INDICATOR Integer EQUALS Expr SEMI\n { $$ = LedNameCreate($3, $5, true); }\n ;", "ShapeDecl : SHAPE String OBRACE OutlineList CBRACE SEMI\n { $$ = NULL; }\n | SHAPE String OBRACE CoordList CBRACE SEMI\n { (void) $4; $$ = NULL; }\n ;", "SectionDecl : SECTION String OBRACE SectionBody CBRACE SEMI\n { $$ = NULL; }\n ;", "SectionBody : SectionBody SectionBodyItem { $$ = NULL;}\n | SectionBodyItem { $$ = NULL; }\n ;", "SectionBodyItem : ROW OBRACE RowBody CBRACE SEMI\n { $$ = NULL; }\n | VarDecl\n { FreeStmt((ParseCommon *) $1); $$ = NULL; }\n | DoodadDecl\n { $$ = NULL; }\n | LedMapDecl\n { FreeStmt((ParseCommon *) $1); $$ = NULL; }\n | OverlayDecl\n { $$ = NULL; }\n ;", "RowBody : RowBody RowBodyItem { $$ = NULL;}\n | RowBodyItem { $$ = NULL; }\n ;", "RowBodyItem : KEYS OBRACE Keys CBRACE SEMI { $$ = NULL; }\n | VarDecl\n { FreeStmt((ParseCommon *) $1); $$ = NULL; }\n ;", "Keys : Keys COMMA Key { $$ = NULL; }\n | Key { $$ = NULL; }\n ;", "Key : KEYNAME\n { $$ = NULL; }\n | OBRACE ExprList CBRACE\n { FreeStmt((ParseCommon *) $2); $$ = NULL; }\n ;", "OverlayDecl : OVERLAY String OBRACE OverlayKeyList CBRACE SEMI\n { $$ = NULL; }\n ;", "OverlayKeyList : OverlayKeyList COMMA OverlayKey { $$ = NULL; }\n | OverlayKey { $$ = NULL; }\n ;", "OverlayKey : KEYNAME EQUALS KEYNAME { $$ = NULL; }\n ;", "OutlineList : OutlineList COMMA OutlineInList\n { $$ = NULL;}\n | OutlineInList\n { $$ = NULL; }\n ;", "OutlineInList : OBRACE CoordList CBRACE\n { (void) $2; $$ = NULL; }\n | Ident EQUALS OBRACE CoordList CBRACE\n { (void) $4; $$ = NULL; }\n | Ident EQUALS Expr\n { FreeStmt((ParseCommon *) $3); $$ = NULL; }\n ;", "CoordList : CoordList COMMA Coord\n { (void) $1; (void) $3; $$ = NULL; }\n | Coord\n { (void) $1; $$ = NULL; }\n ;", "Coord : OBRACKET SignedNumber COMMA SignedNumber CBRACKET\n { $$ = NULL; }\n ;", "DoodadDecl : DoodadType String OBRACE VarDeclList CBRACE SEMI\n { FreeStmt((ParseCommon *) $4); $$ = NULL; }\n ;", "DoodadType : TEXT { $$ = 0; }\n | OUTLINE { $$ = 0; }\n | SOLID { $$ = 0; }\n | LOGO { $$ = 0; }\n ;", "FieldSpec : Ident { $$ = $1; }\n | Element { $$ = $1; }\n ;", "Element : ACTION_TOK\n { $$ = xkb_atom_intern_literal(param->ctx, \"action\"); }\n | INTERPRET\n { $$ = xkb_atom_intern_literal(param->ctx, \"interpret\"); }\n | TYPE\n { $$ = xkb_atom_intern_literal(param->ctx, \"type\"); }\n | KEY\n { $$ = xkb_atom_intern_literal(param->ctx, \"key\"); }\n | GROUP\n { $$ = xkb_atom_intern_literal(param->ctx, \"group\"); }\n | MODIFIER_MAP\n {$$ = xkb_atom_intern_literal(param->ctx, \"modifier_map\");}\n | INDICATOR\n { $$ = xkb_atom_intern_literal(param->ctx, \"indicator\"); }\n | SHAPE", " { $$ = xkb_atom_intern_literal(param->ctx, \"shape\"); }", " | ROW", " { $$ = xkb_atom_intern_literal(param->ctx, \"row\"); }", " | SECTION", " { $$ = xkb_atom_intern_literal(param->ctx, \"section\"); }", " | TEXT", " { $$ = xkb_atom_intern_literal(param->ctx, \"text\"); }", " ;", "OptMergeMode : MergeMode { $$ = $1; }\n | { $$ = MERGE_DEFAULT; }\n ;", "MergeMode : INCLUDE { $$ = MERGE_DEFAULT; }\n | AUGMENT { $$ = MERGE_AUGMENT; }\n | OVERRIDE { $$ = MERGE_OVERRIDE; }\n | REPLACE { $$ = MERGE_REPLACE; }\n | ALTERNATE\n {\n /*\n * This used to be MERGE_ALT_FORM. This functionality was\n * unused and has been removed.\n */\n $$ = MERGE_DEFAULT;\n }\n ;", "OptExprList : ExprList { $$ = $1; }\n | { $$ = NULL; }\n ;", "ExprList : ExprList COMMA Expr\n { $$ = (ExprDef *) AppendStmt((ParseCommon *) $1,\n (ParseCommon *) $3); }\n | Expr\n { $$ = $1; }\n ;", "Expr : Expr DIVIDE Expr\n { $$ = ExprCreateBinary(EXPR_DIVIDE, $1, $3); }\n | Expr PLUS Expr\n { $$ = ExprCreateBinary(EXPR_ADD, $1, $3); }\n | Expr MINUS Expr\n { $$ = ExprCreateBinary(EXPR_SUBTRACT, $1, $3); }\n | Expr TIMES Expr\n { $$ = ExprCreateBinary(EXPR_MULTIPLY, $1, $3); }\n | Lhs EQUALS Expr\n { $$ = ExprCreateBinary(EXPR_ASSIGN, $1, $3); }\n | Term\n { $$ = $1; }\n ;", "Term : MINUS Term\n { $$ = ExprCreateUnary(EXPR_NEGATE, $2->expr.value_type, $2); }\n | PLUS Term\n { $$ = ExprCreateUnary(EXPR_UNARY_PLUS, $2->expr.value_type, $2); }\n | EXCLAM Term\n { $$ = ExprCreateUnary(EXPR_NOT, EXPR_TYPE_BOOLEAN, $2); }\n | INVERT Term\n { $$ = ExprCreateUnary(EXPR_INVERT, $2->expr.value_type, $2); }\n | Lhs\n { $$ = $1; }\n | FieldSpec OPAREN OptExprList CPAREN %prec OPAREN\n { $$ = ExprCreateAction($1, $3); }\n | Terminal\n { $$ = $1; }\n | OPAREN Expr CPAREN\n { $$ = $2; }\n ;", "ActionList : ActionList COMMA Action\n { $$ = (ExprDef *) AppendStmt((ParseCommon *) $1,\n (ParseCommon *) $3); }\n | Action\n { $$ = $1; }\n ;", "Action : FieldSpec OPAREN OptExprList CPAREN\n { $$ = ExprCreateAction($1, $3); }\n ;", "Lhs : FieldSpec\n { $$ = ExprCreateIdent($1); }\n | FieldSpec DOT FieldSpec\n { $$ = ExprCreateFieldRef($1, $3); }\n | FieldSpec OBRACKET Expr CBRACKET\n { $$ = ExprCreateArrayRef(XKB_ATOM_NONE, $1, $3); }\n | FieldSpec DOT FieldSpec OBRACKET Expr CBRACKET\n { $$ = ExprCreateArrayRef($1, $3, $5); }\n ;", "Terminal : String\n { $$ = ExprCreateString($1); }\n | Integer\n { $$ = ExprCreateInteger($1); }\n | Float", " { $$ = ExprCreateFloat(/* Discard $1 */); }", " | KEYNAME\n { $$ = ExprCreateKeyName($1); }\n ;", "OptKeySymList : KeySymList { $$ = $1; }\n | { $$ = NULL; }\n ;", "KeySymList : KeySymList COMMA KeySym\n { $$ = ExprAppendKeysymList($1, $3); }\n | KeySymList COMMA KeySyms\n { $$ = ExprAppendMultiKeysymList($1, $3); }\n | KeySym\n { $$ = ExprCreateKeysymList($1); }\n | KeySyms\n { $$ = ExprCreateMultiKeysymList($1); }\n ;", "KeySyms : OBRACE KeySymList CBRACE\n { $$ = $2; }\n ;", "KeySym : IDENT\n {\n if (!resolve_keysym($1, &$$))\n parser_warn(param, \"unrecognized keysym \\\"%s\\\"\", $1);\n free($1);\n }\n | SECTION { $$ = XKB_KEY_section; }\n | Integer\n {\n if ($1 < 0) {\n parser_warn(param, \"unrecognized keysym \\\"%d\\\"\", $1);\n $$ = XKB_KEY_NoSymbol;\n }\n else if ($1 < 10) { /* XKB_KEY_0 .. XKB_KEY_9 */\n $$ = XKB_KEY_0 + (xkb_keysym_t) $1;\n }\n else {\n char buf[17];\n snprintf(buf, sizeof(buf), \"0x%x\", $1);\n if (!resolve_keysym(buf, &$$)) {\n parser_warn(param, \"unrecognized keysym \\\"%s\\\"\", buf);\n $$ = XKB_KEY_NoSymbol;\n }\n }\n }\n ;", "SignedNumber : MINUS Number { $$ = -$2; }\n | Number { $$ = $1; }\n ;", "Number : FLOAT { $$ = $1; }\n | INTEGER { $$ = $1; }\n ;", "Float : FLOAT { $$ = 0; }\n ;", "Integer : INTEGER { $$ = $1; }\n ;", "KeyCode : INTEGER { $$ = $1; }\n ;", "Ident : IDENT { $$ = xkb_atom_steal(param->ctx, $1); }\n | DEFAULT { $$ = xkb_atom_intern_literal(param->ctx, \"default\"); }\n ;", "String : STRING { $$ = xkb_atom_steal(param->ctx, $1); }\n ;", "OptMapName : MapName { $$ = $1; }\n | { $$ = NULL; }\n ;", "MapName : STRING { $$ = $1; }\n ;", "%%", "XkbFile *\nparse(struct xkb_context *ctx, struct scanner *scanner, const char *map)\n{\n int ret;\n XkbFile *first = NULL;\n struct parser_param param = {\n .scanner = scanner,\n .ctx = ctx,\n .rtrn = NULL,\n };", " /*\n * If we got a specific map, we look for it exclusively and return\n * immediately upon finding it. Otherwise, we need to get the\n * default map. If we find a map marked as default, we return it\n * immediately. If there are no maps marked as default, we return\n * the first map in the file.\n */", " while ((ret = yyparse(&param)) == 0 && param.more_maps) {\n if (map) {\n if (streq_not_null(map, param.rtrn->name))\n return param.rtrn;\n else\n FreeXkbFile(param.rtrn);\n }\n else {\n if (param.rtrn->flags & MAP_IS_DEFAULT) {\n FreeXkbFile(first);\n return param.rtrn;\n }\n else if (!first) {\n first = param.rtrn;\n }\n else {\n FreeXkbFile(param.rtrn);\n }\n }\n param.rtrn = NULL;\n }", " if (ret != 0) {\n FreeXkbFile(first);\n return NULL;\n }", " if (first)\n log_vrb(ctx, 5,\n \"No map in include statement, but \\\"%s\\\" contains several; \"\n \"Using first defined map, \\\"%s\\\"\\n\",\n scanner->file_name, first->name);", " return first;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [785, 37, 190, 691], "buggy_code_start_loc": [108, 37, 97, 594], "filenames": ["src/xkbcomp/ast-build.c", "src/xkbcomp/ast-build.h", "src/xkbcomp/ast.h", "src/xkbcomp/parser.y"], "fixing_code_end_loc": [794, 41, 198, 691], "fixing_code_start_loc": [109, 38, 98, 594], "message": "Unchecked NULL pointer usage in xkbcommon before 0.8.1 could be used by local attackers to crash (NULL pointer dereference) the xkbcommon parser by supplying a crafted keymap file, because geometry tokens were desupported incorrectly.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xkbcommon_project:xkbcommon:*:*:*:*:*:*:*:*", "matchCriteriaId": "2F9BAF72-405A-41EA-AA6D-509128B3E4AD", "versionEndExcluding": "0.8.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:lts:*:*:*", "matchCriteriaId": "B5A6F2F3-4894-4392-8296-3B8DD2679084", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:16.04:*:*:*:lts:*:*:*", "matchCriteriaId": "F7016A2A-8365-4F1A-89A2-7A19F2BCAE5B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:18.04:*:*:*:lts:*:*:*", "matchCriteriaId": "23A7C53F-B80F-4E6A-AFA9-58EEA84BE11D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Unchecked NULL pointer usage in xkbcommon before 0.8.1 could be used by local attackers to crash (NULL pointer dereference) the xkbcommon parser by supplying a crafted keymap file, because geometry tokens were desupported incorrectly."}, {"lang": "es", "value": "El uso de un puntero NULL no verificado en xkbcommon en versiones anteriores a la 0.8.1 podr\u00eda ser aprovechado por atacantes locales para provocar el cierre inesperado (desreferencia de puntero NULL) del analizador xkbcommon proporcionando un archivo keymap manipulado, debido a que los tokens de geometr\u00eda dejaron de ser soportados incorrectamente."}], "evaluatorComment": null, "id": "CVE-2018-15854", "lastModified": "2019-08-06T17:15:24.947", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 2.1, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-08-25T21:29:01.593", "references": [{"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2019:2079"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/xkbcommon/libxkbcommon/commit/e3cacae7b1bfda0d839c280494f23284a1187adf"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://lists.freedesktop.org/archives/wayland-devel/2018-August/039232.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.gentoo.org/glsa/201810-05"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3786-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3786-2/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/xkbcommon/libxkbcommon/commit/e3cacae7b1bfda0d839c280494f23284a1187adf"}, "type": "CWE-476"}
321
Determine whether the {function_name} code is vulnerable or not.
[ "/*\t$OpenBSD: ca.c,v 1.64 2020/07/15 14:45:15 tobhe Exp $\t*/", "\n/*\n * Copyright (c) 2010-2013 Reyk Floeter <reyk@openbsd.org>\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */", "#include <sys/queue.h>\n#include <sys/socket.h>\n#include <sys/wait.h>\n#include <sys/uio.h>", "#include <stdlib.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <string.h>\n#include <signal.h>\n#include <syslog.h>\n#include <errno.h>\n#include <err.h>\n#include <pwd.h>\n#include <event.h>", "#include <openssl/bio.h>\n#include <openssl/err.h>\n#include <openssl/engine.h>\n#include <openssl/ssl.h>\n#include <openssl/x509.h>\n#include <openssl/x509v3.h>\n#include <openssl/pem.h>\n#include <openssl/evp.h>\n#include <openssl/sha.h>\n#include <openssl/rsa.h>", "#include \"iked.h\"\n#include \"ikev2.h\"", "void\t ca_run(struct privsep *, struct privsep_proc *, void *);\nvoid\t ca_shutdown(struct privsep_proc *);\nvoid\t ca_reset(struct privsep *);\nint\t ca_reload(struct iked *);", "int\t ca_getreq(struct iked *, struct imsg *);\nint\t ca_getcert(struct iked *, struct imsg *);\nint\t ca_getauth(struct iked *, struct imsg *);\nX509\t*ca_by_subjectpubkey(X509_STORE *, uint8_t *, size_t);\nX509\t*ca_by_issuer(X509_STORE *, X509_NAME *, struct iked_static_id *);\nX509\t*ca_by_subjectaltname(X509_STORE *, struct iked_static_id *);\nvoid\t ca_store_certs_info(const char *, X509_STORE *);\nint\t ca_subjectpubkey_digest(X509 *, uint8_t *, unsigned int *);\nint\t ca_x509_subject_cmp(X509 *, struct iked_static_id *);\nint\t ca_validate_pubkey(struct iked *, struct iked_static_id *,\n\t void *, size_t, struct iked_id *);\nint\t ca_validate_cert(struct iked *, struct iked_static_id *,\n\t void *, size_t);\nint\t ca_privkey_to_method(struct iked_id *);\nstruct ibuf *\n\t ca_x509_serialize(X509 *);\nint\t ca_x509_subjectaltname_do(X509 *, int, const char *,\n\t struct iked_static_id *, struct iked_id *);\nint\t ca_x509_subjectaltname_cmp(X509 *, struct iked_static_id *);\nint\t ca_x509_subjectaltname_log(X509 *, const char *);\nint\t ca_x509_subjectaltname_get(X509 *cert, struct iked_id *);\nint\t ca_dispatch_parent(int, struct privsep_proc *, struct imsg *);\nint\t ca_dispatch_ikev2(int, struct privsep_proc *, struct imsg *);", "static struct privsep_proc procs[] = {\n\t{ \"parent\",\tPROC_PARENT,\tca_dispatch_parent },\n\t{ \"ikev2\",\tPROC_IKEV2,\tca_dispatch_ikev2 }\n};", "struct ca_store {\n\tX509_STORE\t*ca_cas;\n\tX509_LOOKUP\t*ca_calookup;", "\tX509_STORE\t*ca_certs;\n\tX509_LOOKUP\t*ca_certlookup;", "\tstruct iked_id\t ca_privkey;\n\tstruct iked_id\t ca_pubkey;", "\tuint8_t\t\t ca_privkey_method;\n};", "pid_t\ncaproc(struct privsep *ps, struct privsep_proc *p)\n{\n\treturn (proc_run(ps, p, procs, nitems(procs), ca_run, NULL));\n}", "void\nca_run(struct privsep *ps, struct privsep_proc *p, void *arg)\n{\n\tstruct iked\t*env = ps->ps_env;\n\tstruct ca_store\t*store;", "\t/*\n\t * pledge in the ca process:\n\t * stdio - for malloc and basic I/O including events.\n\t * rpath - for certificate files.\n\t * recvfd - for ocsp sockets.\n\t */\n\tif (pledge(\"stdio rpath recvfd\", NULL) == -1)\n\t\tfatal(\"pledge\");", "\tif ((store = calloc(1, sizeof(*store))) == NULL)\n\t\tfatal(\"%s: failed to allocate cert store\", __func__);", "\tenv->sc_priv = store;\n\tp->p_shutdown = ca_shutdown;\n}", "void\nca_shutdown(struct privsep_proc *p)\n{\n\tstruct iked *env = p->p_env;\n\tstruct ca_store\t\t*store;", "\tif (env == NULL)\n\t\treturn;\n\tibuf_release(env->sc_certreq);\n\tif ((store = env->sc_priv) == NULL)\n\t\treturn;\n\tibuf_release(store->ca_pubkey.id_buf);\n\tibuf_release(store->ca_privkey.id_buf);\n\tfree(store);\n}", "void\nca_getkey(struct privsep *ps, struct iked_id *key, enum imsg_type type)\n{\n\tstruct iked\t*env = ps->ps_env;\n\tstruct ca_store\t*store = env->sc_priv;\n\tstruct iked_id\t*id;\n\tconst char\t*name;", "\tif (store == NULL)\n\t\tfatalx(\"%s: invalid store\", __func__);", "\tif (type == IMSG_PRIVKEY) {\n\t\tname = \"private\";\n\t\tid = &store->ca_privkey;", "\t\tstore->ca_privkey_method = ca_privkey_to_method(key);\n\t\tif (store->ca_privkey_method == IKEV2_AUTH_NONE)\n\t\t\tfatalx(\"ca: failed to get auth method for privkey\");\n\t} else if (type == IMSG_PUBKEY) {\n\t\tname = \"public\";\n\t\tid = &store->ca_pubkey;\n\t} else\n\t\tfatalx(\"%s: invalid type %d\", __func__, type);", "\tlog_debug(\"%s: received %s key type %s length %zd\", __func__,\n\t name, print_map(key->id_type, ikev2_cert_map),\n\t ibuf_length(key->id_buf));", "\t/* clear old key and copy new one */\n\tibuf_release(id->id_buf);\n\tmemcpy(id, key, sizeof(*id));\n}", "void\nca_reset(struct privsep *ps)\n{\n\tstruct iked\t*env = ps->ps_env;\n\tstruct ca_store\t*store = env->sc_priv;", "\tif (store->ca_privkey.id_type == IKEV2_ID_NONE ||\n\t store->ca_pubkey.id_type == IKEV2_ID_NONE)\n\t\tfatalx(\"ca_reset: keys not loaded\");", "\tif (store->ca_cas != NULL)\n\t\tX509_STORE_free(store->ca_cas);\n\tif (store->ca_certs != NULL)\n\t\tX509_STORE_free(store->ca_certs);", "\tif ((store->ca_cas = X509_STORE_new()) == NULL)\n\t\tfatalx(\"ca_reset: failed to get ca store\");\n\tif ((store->ca_calookup = X509_STORE_add_lookup(store->ca_cas,\n\t X509_LOOKUP_file())) == NULL)\n\t\tfatalx(\"ca_reset: failed to add ca lookup\");", "\tif ((store->ca_certs = X509_STORE_new()) == NULL)\n\t\tfatalx(\"ca_reset: failed to get cert store\");\n\tif ((store->ca_certlookup = X509_STORE_add_lookup(store->ca_certs,\n\t X509_LOOKUP_file())) == NULL)\n\t\tfatalx(\"ca_reset: failed to add cert lookup\");", "\tif (ca_reload(env) != 0)\n\t\tfatal(\"ca_reset: reload\");\n}", "int\nca_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)\n{\n\tstruct iked\t\t*env = p->p_env;\n\tunsigned int\t\t mode;", "\tswitch (imsg->hdr.type) {\n\tcase IMSG_CTL_RESET:\n\t\tIMSG_SIZE_CHECK(imsg, &mode);\n\t\tmemcpy(&mode, imsg->data, sizeof(mode));\n\t\tif (mode == RESET_ALL || mode == RESET_CA) {\n\t\t\tlog_debug(\"%s: config reset\", __func__);\n\t\t\tca_reset(&env->sc_ps);\n\t\t}\n\t\tbreak;\n\tcase IMSG_OCSP_FD:\n\t\tocsp_receive_fd(env, imsg);\n\t\tbreak;\n\tcase IMSG_OCSP_URL:\n\t\tconfig_getocsp(env, imsg);\n\t\tbreak;\n\tcase IMSG_PRIVKEY:\n\tcase IMSG_PUBKEY:\n\t\tconfig_getkey(env, imsg);\n\t\tbreak;\n\tdefault:\n\t\treturn (-1);\n\t}", "\treturn (0);\n}", "int\nca_dispatch_ikev2(int fd, struct privsep_proc *p, struct imsg *imsg)\n{\n\tstruct iked\t*env = p->p_env;", "\tswitch (imsg->hdr.type) {\n\tcase IMSG_CERTREQ:\n\t\tca_getreq(env, imsg);\n\t\tbreak;\n\tcase IMSG_CERT:\n\t\tca_getcert(env, imsg);\n\t\tbreak;\n\tcase IMSG_AUTH:\n\t\tca_getauth(env, imsg);\n\t\tbreak;\n\tdefault:\n\t\treturn (-1);\n\t}", "\treturn (0);\n}", "int\nca_setcert(struct iked *env, struct iked_sahdr *sh, struct iked_id *id,\n uint8_t type, uint8_t *data, size_t len, enum privsep_procid procid)\n{\n\tstruct iovec\t\tiov[4];\n\tint\t\t\tiovcnt = 0;\n\tstruct iked_static_id\tidb;", "\t/* Must send the cert and a valid Id to the ca process */\n\tif (procid == PROC_CERT) {\n\t\tif (id == NULL || id->id_type == IKEV2_ID_NONE ||\n\t\t ibuf_length(id->id_buf) > IKED_ID_SIZE)\n\t\t\treturn (-1);\n\t\tbzero(&idb, sizeof(idb));", "\t\t/* Convert to a static Id */\n\t\tidb.id_type = id->id_type;\n\t\tidb.id_offset = id->id_offset;\n\t\tidb.id_length = ibuf_length(id->id_buf);\n\t\tmemcpy(&idb.id_data, ibuf_data(id->id_buf),\n\t\t ibuf_length(id->id_buf));", "\t\tiov[iovcnt].iov_base = &idb;\n\t\tiov[iovcnt].iov_len = sizeof(idb);\n\t\tiovcnt++;\n\t}", "\tiov[iovcnt].iov_base = sh;\n\tiov[iovcnt].iov_len = sizeof(*sh);\n\tiovcnt++;\n\tiov[iovcnt].iov_base = &type;\n\tiov[iovcnt].iov_len = sizeof(type);\n\tiovcnt++;\n\tif (data != NULL) {\n\t\tiov[iovcnt].iov_base = data;\n\t\tiov[iovcnt].iov_len = len;\n\t\tiovcnt++;\n\t}", "\tif (proc_composev(&env->sc_ps, procid, IMSG_CERT, iov, iovcnt) == -1)\n\t\treturn (-1);\n\treturn (0);\n}", "int\nca_setreq(struct iked *env, struct iked_sa *sa,\n struct iked_static_id *localid, uint8_t type, uint8_t more, uint8_t *data,\n size_t len, enum privsep_procid procid)\n{\n\tstruct iovec\t\tiov[5];\n\tint\t\t\tiovcnt = 0;\n\tstruct iked_static_id\tidb;\n\tstruct iked_id\t\tid;\n\tint\t\t\tret = -1;", "\t/* Convert to a static Id */\n\tbzero(&id, sizeof(id));\n\tif (ikev2_policy2id(localid, &id, 1) != 0)\n\t\treturn (-1);", "\tbzero(&idb, sizeof(idb));\n\tidb.id_type = id.id_type;\n\tidb.id_offset = id.id_offset;\n\tidb.id_length = ibuf_length(id.id_buf);\n\tmemcpy(&idb.id_data, ibuf_data(id.id_buf),\n\t ibuf_length(id.id_buf));\n\tiov[iovcnt].iov_base = &idb;\n\tiov[iovcnt].iov_len = sizeof(idb);\n\tiovcnt++;", "\tiov[iovcnt].iov_base = &sa->sa_hdr;\n\tiov[iovcnt].iov_len = sizeof(sa->sa_hdr);\n\tiovcnt++;\n\tiov[iovcnt].iov_base = &type;\n\tiov[iovcnt].iov_len = sizeof(type);\n\tiovcnt++;\n\tiov[iovcnt].iov_base = &more;\n\tiov[iovcnt].iov_len = sizeof(more);\n\tiovcnt++;\n\tif (data != NULL) {\n\t\tiov[iovcnt].iov_base = data;\n\t\tiov[iovcnt].iov_len = len;\n\t\tiovcnt++;\n\t}", "\tif (proc_composev(&env->sc_ps, procid, IMSG_CERTREQ, iov, iovcnt) == -1)\n\t\tgoto done;", "\tsa_stateflags(sa, IKED_REQ_CERTREQ);", "\tret = 0;\n done:\n\tibuf_release(id.id_buf);\n\treturn (ret);\n}", "static int\nauth_sig_compatible(uint8_t type)\n{\n\tswitch (type) {\n\tcase IKEV2_AUTH_RSA_SIG:\n\tcase IKEV2_AUTH_ECDSA_256:\n\tcase IKEV2_AUTH_ECDSA_384:\n\tcase IKEV2_AUTH_ECDSA_521:\n\tcase IKEV2_AUTH_SIG_ANY:\n\t\treturn (1);\n\t}\n\treturn (0);\n}", "int\nca_setauth(struct iked *env, struct iked_sa *sa,\n struct ibuf *authmsg, enum privsep_procid id)\n{\n\tstruct iovec\t\t iov[3];\n\tint\t\t\t iovcnt = 3;\n\tstruct iked_policy\t*policy = sa->sa_policy;\n\tuint8_t\t\t\t type = policy->pol_auth.auth_method;", "\tif (id == PROC_CERT) {\n\t\t/* switch encoding to IKEV2_AUTH_SIG if SHA2 is supported */\n\t\tif (sa->sa_sigsha2 && auth_sig_compatible(type)) {\n\t\t\tlog_debug(\"%s: switching %s to SIG\", __func__,\n\t\t\t print_map(type, ikev2_auth_map));\n\t\t\ttype = IKEV2_AUTH_SIG;\n\t\t} else if (!sa->sa_sigsha2 && type == IKEV2_AUTH_SIG_ANY) {\n\t\t\tlog_debug(\"%s: switching SIG to RSA_SIG(*)\", __func__);\n\t\t\t/* XXX ca might auto-switch to ECDSA */\n\t\t\ttype = IKEV2_AUTH_RSA_SIG;\n\t\t} else if (type == IKEV2_AUTH_SIG) {\n\t\t\tlog_debug(\"%s: using SIG (RFC7427)\", __func__);\n\t\t}\n\t}", "\tif (type == IKEV2_AUTH_SHARED_KEY_MIC) {\n\t\tsa->sa_stateflags |= IKED_REQ_AUTH;\n\t\treturn (ikev2_msg_authsign(env, sa,\n\t\t &policy->pol_auth, authmsg));\n\t}", "\tiov[0].iov_base = &sa->sa_hdr;\n\tiov[0].iov_len = sizeof(sa->sa_hdr);\n\tiov[1].iov_base = &type;\n\tiov[1].iov_len = sizeof(type);\n\tif (type == IKEV2_AUTH_NONE)\n\t\tiovcnt--;\n\telse {\n\t\tiov[2].iov_base = ibuf_data(authmsg);\n\t\tiov[2].iov_len = ibuf_size(authmsg);\n\t\tlog_debug(\"%s: auth length %zu\", __func__, ibuf_size(authmsg));\n\t}", "\tif (proc_composev(&env->sc_ps, id, IMSG_AUTH, iov, iovcnt) == -1)\n\t\treturn (-1);\n\treturn (0);\n}", "int\nca_getcert(struct iked *env, struct imsg *imsg)\n{\n\tstruct iked_sahdr\t sh;\n\tuint8_t\t\t\t type;\n\tuint8_t\t\t\t*ptr;\n\tsize_t\t\t\t len;\n\tstruct iked_static_id\t id;\n\tunsigned int\t\t i;\n\tstruct iovec\t\t iov[3];\n\tint\t\t\t iovcnt = 3, cmd, ret = 0;\n\tstruct iked_id\t\t key;", "\tptr = (uint8_t *)imsg->data;\n\tlen = IMSG_DATA_SIZE(imsg);\n\ti = sizeof(id) + sizeof(sh) + sizeof(type);\n\tif (len < i)\n\t\treturn (-1);", "\tmemcpy(&id, ptr, sizeof(id));\n\tif (id.id_type == IKEV2_ID_NONE)\n\t\treturn (-1);\n\tmemcpy(&sh, ptr + sizeof(id), sizeof(sh));\n\tmemcpy(&type, ptr + sizeof(id) + sizeof(sh), sizeof(uint8_t));", "\tptr += i;\n\tlen -= i;", "\tbzero(&key, sizeof(key));", "\tswitch (type) {\n\tcase IKEV2_CERT_X509_CERT:\n\t\tret = ca_validate_cert(env, &id, ptr, len);\n\t\tif (ret == 0 && env->sc_ocsp_url) {\n\t\t\tret = ocsp_validate_cert(env, &id, ptr, len, sh, type);\n\t\t\tif (ret == 0)\n\t\t\t\treturn (0);\n\t\t}\n\t\tbreak;\n\tcase IKEV2_CERT_RSA_KEY:\n\tcase IKEV2_CERT_ECDSA:\n\t\tret = ca_validate_pubkey(env, &id, ptr, len, NULL);\n\t\tbreak;\n\tcase IKEV2_CERT_NONE:\n\t\t/* Fallback to public key */\n\t\tret = ca_validate_pubkey(env, &id, NULL, 0, &key);\n\t\tif (ret == 0) {\n\t\t\tptr = ibuf_data(key.id_buf);\n\t\t\tlen = ibuf_length(key.id_buf);\n\t\t\ttype = key.id_type;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tlog_debug(\"%s: unsupported cert type %d\", __func__, type);\n\t\tret = -1;\n\t\tbreak;\n\t}", "\tif (ret == 0)\n\t\tcmd = IMSG_CERTVALID;\n\telse\n\t\tcmd = IMSG_CERTINVALID;", "\tiov[0].iov_base = &sh;\n\tiov[0].iov_len = sizeof(sh);\n\tiov[1].iov_base = &type;\n\tiov[1].iov_len = sizeof(type);\n\tiov[2].iov_base = ptr;\n\tiov[2].iov_len = len;", "\tif (proc_composev(&env->sc_ps, PROC_IKEV2, cmd, iov, iovcnt) == -1)\n\t\treturn (-1);\n\treturn (0);\n}", "int\nca_getreq(struct iked *env, struct imsg *imsg)\n{\n\tstruct ca_store\t\t*store = env->sc_priv;\n\tstruct iked_sahdr\t sh;\n\tuint8_t\t\t\t type, more;\n\tuint8_t\t\t\t*ptr;\n\tsize_t\t\t\t len;\n\tunsigned int\t\t i;\n\tX509\t\t\t*ca = NULL, *cert = NULL;\n\tstruct ibuf\t\t*buf;\n\tstruct iked_static_id\t id;\n\tchar\t\t\t idstr[IKED_ID_SIZE];", "\tptr = (uint8_t *)imsg->data;\n\tlen = IMSG_DATA_SIZE(imsg);\n\ti = sizeof(id) + sizeof(type) + sizeof(sh) + sizeof(more);\n\tif (len < i)\n\t\treturn (-1);", "\tmemcpy(&id, ptr, sizeof(id));\n\tif (id.id_type == IKEV2_ID_NONE)\n\t\treturn (-1);\n\tmemcpy(&sh, ptr + sizeof(id), sizeof(sh));\n\tmemcpy(&type, ptr + sizeof(id) + sizeof(sh), sizeof(type));\n\tmemcpy(&more, ptr + sizeof(id) + sizeof(sh) + sizeof(type), sizeof(more));", "\tptr += i;\n\tlen -= i;", "\tswitch (type) {\n\tcase IKEV2_CERT_RSA_KEY:\n\tcase IKEV2_CERT_ECDSA:\n\t\t/*\n\t\t * Find a local raw public key that matches the type\n\t\t * received in the CERTREQ payoad\n\t\t */\n\t\tif (store->ca_pubkey.id_type != type ||\n\t\t store->ca_pubkey.id_buf == NULL)\n\t\t\tgoto fallback;", "\t\tbuf = ibuf_dup(store->ca_pubkey.id_buf);\n\t\tlog_debug(\"%s: using local public key of type %s\", __func__,\n\t\t print_map(type, ikev2_cert_map));\n\t\tbreak;\n\tcase IKEV2_CERT_X509_CERT:\n\t\tif (len == 0 || len % SHA_DIGEST_LENGTH) {\n\t\t\tlog_info(\"%s: invalid CERTREQ data.\",\n\t\t\t SPI_SH(&sh, __func__));\n\t\t\treturn (-1);\n\t\t}", "\t\t/*\n\t\t * Find a local certificate signed by any of the CAs\n\t\t * received in the CERTREQ payload\n\t\t */\n\t\tfor (i = 0; i < len; i += SHA_DIGEST_LENGTH) {\n\t\t\tif ((ca = ca_by_subjectpubkey(store->ca_cas, ptr + i,\n\t\t\t SHA_DIGEST_LENGTH)) == NULL)\n\t\t\t\tcontinue;", "\t\t\tlog_debug(\"%s: found CA %s\", __func__, ca->name);", "\t\t\tif ((cert = ca_by_issuer(store->ca_certs,\n\t\t\t X509_get_subject_name(ca), &id)) != NULL) {\n\t\t\t\t/* XXX\n\t\t\t\t * should we re-validate our own cert here?\n\t\t\t\t */\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t/* Fallthrough */\n\tcase IKEV2_CERT_NONE:\n fallback:\n\t\t/*\n\t\t * If no certificate or key matching any of the trust-anchors\n\t\t * was found and this was the last CERTREQ, try to find one with\n\t\t * subjectAltName matching the ID\n\t\t */\n\t\tif (more)\n\t\t\treturn (0);", "\t\tif (cert == NULL)\n\t\t\tcert = ca_by_subjectaltname(store->ca_certs, &id);", "\t\t/* If there is no matching certificate use local raw pubkey */\n\t\tif (cert == NULL) {\n\t\t\tif (ikev2_print_static_id(&id, idstr, sizeof(idstr)) == -1)\n\t\t\t\treturn (-1);\n\t\t\tlog_info(\"%s: no valid local certificate found for %s\",\n\t\t\t SPI_SH(&sh, __func__), idstr);\n\t\t\tca_store_certs_info(SPI_SH(&sh, __func__),\n\t\t\t store->ca_certs);\n\t\t\tif (store->ca_pubkey.id_buf == NULL)\n\t\t\t\treturn (-1);\n\t\t\tbuf = ibuf_dup(store->ca_pubkey.id_buf);\n\t\t\ttype = store->ca_pubkey.id_type;\n\t\t\tlog_info(\"%s: using local public key of type %s\",\n\t\t\t SPI_SH(&sh, __func__),\n\t\t\t print_map(type, ikev2_cert_map));\n\t\t\tbreak;\n\t\t}", "\t\tlog_debug(\"%s: found local certificate %s\", __func__,\n\t\t cert->name);", "\t\tif ((buf = ca_x509_serialize(cert)) == NULL)\n\t\t\treturn (-1);\n\t\tbreak;\n\tdefault:\n\t\tlog_warnx(\"%s: unknown cert type requested\",\n\t\t SPI_SH(&sh, __func__));\n\t\treturn (-1);\n\t}", "\tca_setcert(env, &sh, NULL, type,\n\t ibuf_data(buf), ibuf_size(buf), PROC_IKEV2);\n\tibuf_release(buf);", "\treturn (0);\n}", "int\nca_getauth(struct iked *env, struct imsg *imsg)\n{\n\tstruct ca_store\t\t*store = env->sc_priv;\n\tstruct iked_sahdr\t sh;\n\tuint8_t\t\t\t method;\n\tuint8_t\t\t\t*ptr;\n\tsize_t\t\t\t len;\n\tunsigned int\t\t i;\n\tint\t\t\t ret = -1;\n\tstruct iked_sa\t\t sa;\n\tstruct iked_policy\t policy;\n\tstruct iked_id\t\t*id;\n\tstruct ibuf\t\t*authmsg;", "\tptr = (uint8_t *)imsg->data;\n\tlen = IMSG_DATA_SIZE(imsg);\n\ti = sizeof(method) + sizeof(sh);\n\tif (len <= i)\n\t\treturn (-1);", "\tmemcpy(&sh, ptr, sizeof(sh));\n\tmemcpy(&method, ptr + sizeof(sh), sizeof(uint8_t));\n\tif (method == IKEV2_AUTH_SHARED_KEY_MIC)\n\t\treturn (-1);", "\tptr += i;\n\tlen -= i;", "\tif ((authmsg = ibuf_new(ptr, len)) == NULL)\n\t\treturn (-1);", "\t/*\n\t * Create fake SA and policy\n\t */\n\tbzero(&sa, sizeof(sa));\n\tbzero(&policy, sizeof(policy));\n\tmemcpy(&sa.sa_hdr, &sh, sizeof(sh));\n\tsa.sa_policy = &policy;\n\tif (sh.sh_initiator)\n\t\tid = &sa.sa_icert;\n\telse\n\t\tid = &sa.sa_rcert;\n\tmemcpy(id, &store->ca_privkey, sizeof(*id));\n\tpolicy.pol_auth.auth_method = method == IKEV2_AUTH_SIG ?\n\t method : store->ca_privkey_method;", "\tif (ikev2_msg_authsign(env, &sa, &policy.pol_auth, authmsg) != 0) {\n\t\tlog_debug(\"%s: AUTH sign failed\", __func__);\n\t\tpolicy.pol_auth.auth_method = IKEV2_AUTH_NONE;\n\t}", "\tret = ca_setauth(env, &sa, sa.sa_localauth.id_buf, PROC_IKEV2);", "\tibuf_release(sa.sa_localauth.id_buf);\n\tsa.sa_localauth.id_buf = NULL;\n\tibuf_release(authmsg);", "\treturn (ret);\n}", "int\nca_reload(struct iked *env)\n{\n\tstruct ca_store\t\t*store = env->sc_priv;\n\tuint8_t\t\t\t md[EVP_MAX_MD_SIZE];\n\tchar\t\t\t file[PATH_MAX];\n\tstruct iovec\t\t iov[2];\n\tstruct dirent\t\t*entry;\n\tSTACK_OF(X509_OBJECT)\t*h;\n\tX509_OBJECT\t\t*xo;\n\tX509\t\t\t*x509;\n\tDIR\t\t\t*dir;\n\tint\t\t\t i, len, iovcnt = 0;", "\t/*\n\t * Load CAs\n\t */\n\tif ((dir = opendir(IKED_CA_DIR)) == NULL)\n\t\treturn (-1);", "\twhile ((entry = readdir(dir)) != NULL) {\n\t\tif ((entry->d_type != DT_REG) &&\n\t\t (entry->d_type != DT_LNK))\n\t\t\tcontinue;", "\t\tif (snprintf(file, sizeof(file), \"%s%s\",\n\t\t IKED_CA_DIR, entry->d_name) < 0)\n\t\t\tcontinue;", "\t\tif (!X509_load_cert_file(store->ca_calookup, file,\n\t\t X509_FILETYPE_PEM)) {\n\t\t\tlog_warn(\"%s: failed to load ca file %s\", __func__,\n\t\t\t entry->d_name);\n\t\t\tca_sslerror(__func__);\n\t\t\tcontinue;\n\t\t}\n\t\tlog_debug(\"%s: loaded ca file %s\", __func__, entry->d_name);\n\t}\n\tclosedir(dir);", "\t/*\n\t * Load CRLs for the CAs\n\t */\n\tif ((dir = opendir(IKED_CRL_DIR)) == NULL)\n\t\treturn (-1);", "\twhile ((entry = readdir(dir)) != NULL) {\n\t\tif ((entry->d_type != DT_REG) &&\n\t\t (entry->d_type != DT_LNK))\n\t\t\tcontinue;", "\t\tif (snprintf(file, sizeof(file), \"%s%s\",\n\t\t IKED_CRL_DIR, entry->d_name) < 0)\n\t\t\tcontinue;", "\t\tif (!X509_load_crl_file(store->ca_calookup, file,\n\t\t X509_FILETYPE_PEM)) {\n\t\t\tlog_warn(\"%s: failed to load crl file %s\", __func__,\n\t\t\t entry->d_name);\n\t\t\tca_sslerror(__func__);\n\t\t\tcontinue;\n\t\t}", "\t\t/* Only enable CRL checks if we actually loaded a CRL */\n\t\tX509_STORE_set_flags(store->ca_cas, X509_V_FLAG_CRL_CHECK);", "\t\tlog_debug(\"%s: loaded crl file %s\", __func__, entry->d_name);\n\t}\n\tclosedir(dir);", "\t/*\n\t * Save CAs signatures for the IKEv2 CERTREQ\n\t */\n\tibuf_release(env->sc_certreq);\n\tif ((env->sc_certreq = ibuf_new(NULL, 0)) == NULL)\n\t\treturn (-1);", "\th = store->ca_cas->objs;\n\tfor (i = 0; i < sk_X509_OBJECT_num(h); i++) {\n\t\txo = sk_X509_OBJECT_value(h, i);\n\t\tif (xo->type != X509_LU_X509)\n\t\t\tcontinue;", "\t\tx509 = xo->data.x509;\n\t\tlen = sizeof(md);\n\t\tca_subjectpubkey_digest(x509, md, &len);\n\t\tlog_debug(\"%s: %s\", __func__, x509->name);", "\t\tif (ibuf_add(env->sc_certreq, md, len) != 0) {\n\t\t\tibuf_release(env->sc_certreq);\n\t\t\tenv->sc_certreq = NULL;\n\t\t\treturn (-1);\n\t\t}\n\t}", "\tif (ibuf_length(env->sc_certreq)) {\n\t\tenv->sc_certreqtype = IKEV2_CERT_X509_CERT;\n\t\tiov[0].iov_base = &env->sc_certreqtype;\n\t\tiov[0].iov_len = sizeof(env->sc_certreqtype);\n\t\tiovcnt++;\n\t\tiov[1].iov_base = ibuf_data(env->sc_certreq);\n\t\tiov[1].iov_len = ibuf_length(env->sc_certreq);\n\t\tiovcnt++;", "\t\tlog_debug(\"%s: loaded %zu ca certificate%s\", __func__,\n\t\t ibuf_length(env->sc_certreq) / SHA_DIGEST_LENGTH,\n\t\t ibuf_length(env->sc_certreq) == SHA_DIGEST_LENGTH ?\n\t\t \"\" : \"s\");", "\t\t(void)proc_composev(&env->sc_ps, PROC_IKEV2, IMSG_CERTREQ,\n\t\t iov, iovcnt);\n\t}", "\t/*\n\t * Load certificates\n\t */\n\tif ((dir = opendir(IKED_CERT_DIR)) == NULL)\n\t\treturn (-1);", "\twhile ((entry = readdir(dir)) != NULL) {\n\t\tif ((entry->d_type != DT_REG) &&\n\t\t (entry->d_type != DT_LNK))\n\t\t\tcontinue;", "\t\tif (snprintf(file, sizeof(file), \"%s%s\",\n\t\t IKED_CERT_DIR, entry->d_name) < 0)\n\t\t\tcontinue;", "\t\tif (!X509_load_cert_file(store->ca_certlookup, file,\n\t\t X509_FILETYPE_PEM)) {\n\t\t\tlog_warn(\"%s: failed to load cert file %s\", __func__,\n\t\t\t entry->d_name);\n\t\t\tca_sslerror(__func__);\n\t\t\tcontinue;\n\t\t}\n\t\tlog_debug(\"%s: loaded cert file %s\", __func__, entry->d_name);\n\t}\n\tclosedir(dir);", "\th = store->ca_certs->objs;\n\tfor (i = 0; i < sk_X509_OBJECT_num(h); i++) {\n\t\txo = sk_X509_OBJECT_value(h, i);\n\t\tif (xo->type != X509_LU_X509)\n\t\t\tcontinue;", "\t\tx509 = xo->data.x509;", "\t\t(void)ca_validate_cert(env, NULL, x509, 0);\n\t}", "\tif (!env->sc_certreqtype)\n\t\tenv->sc_certreqtype = store->ca_pubkey.id_type;", "\tlog_debug(\"%s: local cert type %s\", __func__,\n\t print_map(env->sc_certreqtype, ikev2_cert_map));", "\tiov[0].iov_base = &env->sc_certreqtype;\n\tiov[0].iov_len = sizeof(env->sc_certreqtype);\n\tif (iovcnt == 0)\n\t\tiovcnt++;\n\t(void)proc_composev(&env->sc_ps, PROC_IKEV2, IMSG_CERTREQ, iov, iovcnt);", "\treturn (0);\n}", "X509 *\nca_by_subjectpubkey(X509_STORE *ctx, uint8_t *sig, size_t siglen)\n{\n\tSTACK_OF(X509_OBJECT)\t*h;\n\tX509_OBJECT\t\t*xo;\n\tX509\t\t\t*ca;\n\tint\t\t\t i;\n\tunsigned int\t\t len;\n\tuint8_t\t\t\t md[EVP_MAX_MD_SIZE];", "\th = ctx->objs;", "\tfor (i = 0; i < sk_X509_OBJECT_num(h); i++) {\n\t\txo = sk_X509_OBJECT_value(h, i);\n\t\tif (xo->type != X509_LU_X509)\n\t\t\tcontinue;", "\t\tca = xo->data.x509;\n\t\tlen = sizeof(md);\n\t\tca_subjectpubkey_digest(ca, md, &len);", "\t\tif (len == siglen && memcmp(md, sig, len) == 0)\n\t\t\treturn (ca);\n\t}", "\treturn (NULL);\n}", "X509 *\nca_by_issuer(X509_STORE *ctx, X509_NAME *subject, struct iked_static_id *id)\n{\n\tSTACK_OF(X509_OBJECT)\t*h;\n\tX509_OBJECT\t\t*xo;\n\tX509\t\t\t*cert;\n\tint\t\t\t i;\n\tX509_NAME\t\t*issuer;", "\tif (subject == NULL)\n\t\treturn (NULL);", "\th = ctx->objs;\n\tfor (i = 0; i < sk_X509_OBJECT_num(h); i++) {\n\t\txo = sk_X509_OBJECT_value(h, i);\n\t\tif (xo->type != X509_LU_X509)\n\t\t\tcontinue;", "\t\tcert = xo->data.x509;\n\t\tif ((issuer = X509_get_issuer_name(cert)) == NULL)\n\t\t\tcontinue;\n\t\telse if (X509_NAME_cmp(subject, issuer) == 0) {\n\t\t\tswitch (id->id_type) {\n\t\t\tcase IKEV2_ID_ASN1_DN:\n\t\t\t\tif (ca_x509_subject_cmp(cert, id) == 0)\n\t\t\t\t\treturn (cert);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (ca_x509_subjectaltname_cmp(cert, id) == 0)\n\t\t\t\t\treturn (cert);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}", "\treturn (NULL);\n}", "X509 *\nca_by_subjectaltname(X509_STORE *ctx, struct iked_static_id *id)\n{\n\tSTACK_OF(X509_OBJECT)\t*h;\n\tX509_OBJECT\t\t*xo;\n\tX509\t\t\t*cert;\n\tint\t\t\t i;", "\th = ctx->objs;\n\tfor (i = 0; i < sk_X509_OBJECT_num(h); i++) {\n\t\txo = sk_X509_OBJECT_value(h, i);\n\t\tif (xo->type != X509_LU_X509)\n\t\t\tcontinue;", "\t\tcert = xo->data.x509;\n\t\tswitch (id->id_type) {\n\t\tcase IKEV2_ID_ASN1_DN:\n\t\t\tif (ca_x509_subject_cmp(cert, id) == 0)\n\t\t\t\treturn (cert);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (ca_x509_subjectaltname_cmp(cert, id) == 0)\n\t\t\t\treturn (cert);\n\t\t\tbreak;\n\t\t}\n\t}", "\treturn (NULL);\n}", "void\nca_store_certs_info(const char *msg, X509_STORE *ctx)\n{\n\tSTACK_OF(X509_OBJECT)\t*h;\n\tX509_OBJECT\t\t*xo;\n\tX509\t\t\t*cert;\n\tint\t\t\t i;", "\th = ctx->objs;\n\tfor (i = 0; i < sk_X509_OBJECT_num(h); i++) {\n\t\txo = sk_X509_OBJECT_value(h, i);\n\t\tif (xo->type != X509_LU_X509)\n\t\t\tcontinue;\n\t\tcert = xo->data.x509;\n\t\tca_cert_info(msg, cert);\n\t}\n}", "void\nca_cert_info(const char *msg, X509 *cert)\n{\n\tASN1_INTEGER\t*asn1_serial;\n\tBUF_MEM\t\t*memptr;\n\tBIO\t\t*rawserial = NULL;\n\tchar\t\t buf[BUFSIZ];", "\tif ((asn1_serial = X509_get_serialNumber(cert)) == NULL ||\n\t (rawserial = BIO_new(BIO_s_mem())) == NULL ||\n\t i2a_ASN1_INTEGER(rawserial, asn1_serial) <= 0)\n\t\tgoto out;\n\tif (X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf)))\n\t\tlog_info(\"%s: issuer: %s\", msg, buf);\n\tBIO_get_mem_ptr(rawserial, &memptr);\n\tif (memptr->data != NULL && memptr->length < INT32_MAX)\n\t\tlog_info(\"%s: serial: %.*s\", msg, (int)memptr->length,\n\t\t memptr->data);\n\tif (X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf)))\n\t\tlog_info(\"%s: subject: %s\", msg, buf);\n\tca_x509_subjectaltname_log(cert, msg);\nout:\n\tif (rawserial)\n\t\tBIO_free(rawserial);\n}", "int\nca_subjectpubkey_digest(X509 *x509, uint8_t *md, unsigned int *size)\n{\n\tEVP_PKEY\t*pkey;\n\tuint8_t\t\t*buf = NULL;\n\tint\t\t buflen;", "\tif (*size < SHA_DIGEST_LENGTH)\n\t\treturn (-1);", "\t/*\n\t * Generate a SHA-1 digest of the Subject Public Key Info\n\t * element in the X.509 certificate, an ASN.1 sequence\n\t * that includes the public key type (eg. RSA) and the\n\t * public key value (see 3.7 of RFC7296).\n\t */\n\tif ((pkey = X509_get_pubkey(x509)) == NULL)\n\t\treturn (-1);\n\tbuflen = i2d_PUBKEY(pkey, &buf);\n\tEVP_PKEY_free(pkey);\n\tif (buflen == 0)\n\t\treturn (-1);\n\tif (!EVP_Digest(buf, buflen, md, size, EVP_sha1(), NULL)) {\n\t\tfree(buf);\n\t\treturn (-1);\n\t}\n\tfree(buf);", "\treturn (0);\n}", "struct ibuf *\nca_x509_serialize(X509 *x509)\n{\n\tlong\t\t len;\n\tstruct ibuf\t*buf;\n\tuint8_t\t\t*d = NULL;\n\tBIO\t\t*out;", "\tif ((out = BIO_new(BIO_s_mem())) == NULL)\n\t\treturn (NULL);\n\tif (!i2d_X509_bio(out, x509)) {\n\t\tBIO_free(out);\n\t\treturn (NULL);\n\t}", "\tlen = BIO_get_mem_data(out, &d);\n\tbuf = ibuf_new(d, len);\n\tBIO_free(out);", "\treturn (buf);\n}", "int\nca_pubkey_serialize(EVP_PKEY *key, struct iked_id *id)\n{\n\tRSA\t\t*rsa = NULL;\n\tEC_KEY\t\t*ec = NULL;\n\tuint8_t\t\t*d;\n\tint\t\t len = 0;\n\tint\t\t ret = -1;", "\tswitch (key->type) {\n\tcase EVP_PKEY_RSA:\n\t\tid->id_type = 0;\n\t\tid->id_offset = 0;\n\t\tibuf_release(id->id_buf);\n\t\tid->id_buf = NULL;", "\t\tif ((rsa = EVP_PKEY_get1_RSA(key)) == NULL)\n\t\t\tgoto done;\n\t\tif ((len = i2d_RSAPublicKey(rsa, NULL)) <= 0)\n\t\t\tgoto done;\n\t\tif ((id->id_buf = ibuf_new(NULL, len)) == NULL)\n\t\t\tgoto done;", "\t\td = ibuf_data(id->id_buf);\n\t\tif (i2d_RSAPublicKey(rsa, &d) != len) {\n\t\t\tibuf_release(id->id_buf);\n\t\t\tid->id_buf = NULL;\n\t\t\tgoto done;\n\t\t}", "\t\tid->id_type = IKEV2_CERT_RSA_KEY;\n\t\tbreak;\n\tcase EVP_PKEY_EC:\n\t\tid->id_type = 0;\n\t\tid->id_offset = 0;\n\t\tibuf_release(id->id_buf);\n\t\tid->id_buf = NULL;", "\t\tif ((ec = EVP_PKEY_get1_EC_KEY(key)) == NULL)\n\t\t\tgoto done;\n\t\tif ((len = i2d_EC_PUBKEY(ec, NULL)) <= 0)\n\t\t\tgoto done;\n\t\tif ((id->id_buf = ibuf_new(NULL, len)) == NULL)\n\t\t\tgoto done;", "\t\td = ibuf_data(id->id_buf);\n\t\tif (i2d_EC_PUBKEY(ec, &d) != len) {\n\t\t\tibuf_release(id->id_buf);\n\t\t\tid->id_buf = NULL;\n\t\t\tgoto done;\n\t\t}", "\t\tid->id_type = IKEV2_CERT_ECDSA;\n\t\tbreak;\n\tdefault:\n\t\tlog_debug(\"%s: unsupported key type %d\", __func__, key->type);\n\t\treturn (-1);\n\t}", "\tlog_debug(\"%s: type %s length %d\", __func__,\n\t print_map(id->id_type, ikev2_cert_map), len);", "\tret = 0;\n done:\n\tif (rsa != NULL)\n\t\tRSA_free(rsa);\n\tif (ec != NULL)\n\t\tEC_KEY_free(ec);\n\treturn (ret);\n}", "int\nca_privkey_serialize(EVP_PKEY *key, struct iked_id *id)\n{\n\tRSA\t\t*rsa = NULL;\n\tEC_KEY\t\t*ec = NULL;\n\tuint8_t\t\t*d;\n\tint\t\t len = 0;\n\tint\t\t ret = -1;", "\tswitch (key->type) {\n\tcase EVP_PKEY_RSA:\n\t\tid->id_type = 0;\n\t\tid->id_offset = 0;\n\t\tibuf_release(id->id_buf);\n\t\tid->id_buf = NULL;", "\t\tif ((rsa = EVP_PKEY_get1_RSA(key)) == NULL)\n\t\t\tgoto done;\n\t\tif ((len = i2d_RSAPrivateKey(rsa, NULL)) <= 0)\n\t\t\tgoto done;\n\t\tif ((id->id_buf = ibuf_new(NULL, len)) == NULL)\n\t\t\tgoto done;", "\t\td = ibuf_data(id->id_buf);\n\t\tif (i2d_RSAPrivateKey(rsa, &d) != len) {\n\t\t\tibuf_release(id->id_buf);\n\t\t\tid->id_buf = NULL;\n\t\t\tgoto done;\n\t\t}", "\t\tid->id_type = IKEV2_CERT_RSA_KEY;\n\t\tbreak;\n\tcase EVP_PKEY_EC:\n\t\tid->id_type = 0;\n\t\tid->id_offset = 0;\n\t\tibuf_release(id->id_buf);\n\t\tid->id_buf = NULL;", "\t\tif ((ec = EVP_PKEY_get1_EC_KEY(key)) == NULL)\n\t\t\tgoto done;\n\t\tif ((len = i2d_ECPrivateKey(ec, NULL)) <= 0)\n\t\t\tgoto done;\n\t\tif ((id->id_buf = ibuf_new(NULL, len)) == NULL)\n\t\t\tgoto done;", "\t\td = ibuf_data(id->id_buf);\n\t\tif (i2d_ECPrivateKey(ec, &d) != len) {\n\t\t\tibuf_release(id->id_buf);\n\t\t\tid->id_buf = NULL;\n\t\t\tgoto done;\n\t\t}", "\t\tid->id_type = IKEV2_CERT_ECDSA;\n\t\tbreak;\n\tdefault:\n\t\tlog_debug(\"%s: unsupported key type %d\", __func__, key->type);\n\t\treturn (-1);\n\t}", "\tlog_debug(\"%s: type %s length %d\", __func__,\n\t print_map(id->id_type, ikev2_cert_map), len);", "\tret = 0;\n done:\n\tif (rsa != NULL)\n\t\tRSA_free(rsa);\n\tif (ec != NULL)\n\t\tEC_KEY_free(ec);\n\treturn (ret);\n}", "int\nca_privkey_to_method(struct iked_id *privkey)\n{\n\tBIO\t\t*rawcert = NULL;\n\tEC_KEY\t\t*ec = NULL;\n\tconst EC_GROUP\t*group = NULL;\n\tuint8_t\t method = IKEV2_AUTH_NONE;", "\tswitch (privkey->id_type) {\n\tcase IKEV2_CERT_RSA_KEY:\n\t\tmethod = IKEV2_AUTH_RSA_SIG;\n\t\tbreak;\n\tcase IKEV2_CERT_ECDSA:\n\t\tif ((rawcert = BIO_new_mem_buf(ibuf_data(privkey->id_buf),\n\t\t ibuf_length(privkey->id_buf))) == NULL)\n\t\t\tgoto out;\n\t\tif ((ec = d2i_ECPrivateKey_bio(rawcert, NULL)) == NULL)\n\t\t\tgoto out;\n\t\tif ((group = EC_KEY_get0_group(ec)) == NULL)\n\t\t\tgoto out;\n\t\tswitch (EC_GROUP_get_degree(group)) {\n\t\tcase 256:\n\t\t\tmethod = IKEV2_AUTH_ECDSA_256;\n\t\t\tbreak;\n\t\tcase 384:\n\t\t\tmethod = IKEV2_AUTH_ECDSA_384;\n\t\t\tbreak;\n\t\tcase 521:\n\t\t\tmethod = IKEV2_AUTH_ECDSA_521;\n\t\t\tbreak;\n\t\t}\n\t}", "\tlog_debug(\"%s: type %s method %s\", __func__,\n\t print_map(privkey->id_type, ikev2_cert_map),\n\t print_map(method, ikev2_auth_map));", " out:\n\tif (ec != NULL)\n\t\tEC_KEY_free(ec);\n\tif (rawcert != NULL)\n\t\tBIO_free(rawcert);", "\treturn (method);\n}", "char *\nca_asn1_name(uint8_t *asn1, size_t len)\n{\n\tX509_NAME\t*name = NULL;\n\tchar\t\t*str = NULL;\n\tconst uint8_t\t*p;", "\tp = asn1;\n\tif ((name = d2i_X509_NAME(NULL, &p, len)) == NULL)\n\t\treturn (NULL);\n\tstr = X509_NAME_oneline(name, NULL, 0);\n\tX509_NAME_free(name);", "\treturn (str);\n}", "/*\n * Copy 'src' to 'dst' until 'marker' is found while unescaping '\\'\n * characters. The return value tells the caller where to continue\n * parsing (might be the end of the string) or NULL on error.\n */\nstatic char *\nca_x509_name_unescape(char *src, char *dst, char marker)\n{\n\twhile (*src) {\n\t\tif (*src == marker) {\n\t\t\tsrc++;\n\t\t\tbreak;\n\t\t}\n\t\tif (*src == '\\\\') {\n\t\t\tsrc++;\n\t\t\tif (!*src) {\n\t\t\t\tlog_warnx(\"%s: '\\\\' at end of string\",\n\t\t\t\t __func__);\n\t\t\t\t*dst = '\\0';\n\t\t\t\treturn (NULL);\n\t\t\t}\n\t\t}\n\t\t*dst++ = *src++;\n\t}\n\t*dst = '\\0';\n\treturn (src);\n}\n/*\n * Parse an X509 subject name where 'subject' is in the format\n * /type0=value0/type1=value1/type2=...\n * where characters may be escaped by '\\'.\n * See lib/libssl/src/apps/apps.c:parse_name()\n */\nvoid *\nca_x509_name_parse(char *subject)\n{\n\tchar\t\t*cp, *value = NULL, *type = NULL;\n\tsize_t\t\t maxlen;\n\tX509_NAME\t*name = NULL;", "\tif (*subject != '/') {\n\t\tlog_warnx(\"%s: leading '/' missing in '%s'\", __func__, subject);\n\t\tgoto err;\n\t}", "\t/* length of subject is upper bound for unescaped type/value */\n\tmaxlen = strlen(subject) + 1;", "\tif ((type = calloc(1, maxlen)) == NULL ||\n\t (value = calloc(1, maxlen)) == NULL ||\n\t (name = X509_NAME_new()) == NULL)\n\t\tgoto err;", "\tcp = subject + 1;\n\twhile (*cp) {\n\t\t/* unescape type, terminated by '=' */\n\t\tcp = ca_x509_name_unescape(cp, type, '=');\n\t\tif (cp == NULL) {\n\t\t\tlog_warnx(\"%s: could not parse type\", __func__);\n\t\t\tgoto err;\n\t\t}\n\t\tif (!*cp) {\n\t\t\tlog_warnx(\"%s: missing value\", __func__);\n\t\t\tgoto err;\n\t\t}\n\t\t/* unescape value, terminated by '/' */\n\t\tcp = ca_x509_name_unescape(cp, value, '/');\n\t\tif (cp == NULL) {\n\t\t\tlog_warnx(\"%s: could not parse value\", __func__);\n\t\t\tgoto err;\n\t\t}\n\t\tif (!*type || !*value) {\n\t\t\tlog_warnx(\"%s: empty type or value\", __func__);\n\t\t\tgoto err;\n\t\t}\n\t\tlog_debug(\"%s: setting '%s' to '%s'\", __func__, type, value);\n\t\tif (!X509_NAME_add_entry_by_txt(name, type, MBSTRING_ASC,\n\t\t value, -1, -1, 0)) {\n\t\t\tlog_warnx(\"%s: setting '%s' to '%s' failed\", __func__,\n\t\t\t type, value);\n\t\t\tca_sslerror(__func__);\n\t\t\tgoto err;\n\t\t}\n\t}\n\tfree(type);\n\tfree(value);\n\treturn (name);", "err:\n\tX509_NAME_free(name);\n\tfree(type);\n\tfree(value);\n\treturn (NULL);\n}", "int\nca_validate_pubkey(struct iked *env, struct iked_static_id *id,\n void *data, size_t len, struct iked_id *out)\n{\n\tBIO\t\t*rawcert = NULL;\n\tRSA\t\t*peerrsa = NULL, *localrsa = NULL;\n\tEC_KEY\t\t*peerec = NULL;\n\tEVP_PKEY\t*peerkey = NULL, *localkey = NULL;\n\tint\t\t ret = -1;\n\tFILE\t\t*fp = NULL;\n\tchar\t\t idstr[IKED_ID_SIZE];\n\tchar\t\t file[PATH_MAX];\n\tstruct iked_id\t idp;", "\tswitch (id->id_type) {\n\tcase IKEV2_ID_IPV4:\n\tcase IKEV2_ID_FQDN:\n\tcase IKEV2_ID_UFQDN:\n\tcase IKEV2_ID_IPV6:\n\t\tbreak;\n\tdefault:\n\t\t/* Some types like ASN1_DN will not be mapped to file names */\n\t\tlog_debug(\"%s: unsupported public key type %s\",\n\t\t __func__, print_map(id->id_type, ikev2_id_map));\n\t\treturn (-1);\n\t}", "\tbzero(&idp, sizeof(idp));\n\tif ((idp.id_buf = ibuf_new(id->id_data, id->id_length)) == NULL)\n\t\tgoto done;", "\tidp.id_type = id->id_type;\n\tidp.id_offset = id->id_offset;\n\tif (ikev2_print_id(&idp, idstr, sizeof(idstr)) == -1)\n\t\tgoto done;", "\tif (len == 0 && data) {\n\t\t/* Data is already an public key */\n\t\tpeerkey = (EVP_PKEY *)data;\n\t}\n\tif (len > 0) {\n\t\tif ((rawcert = BIO_new_mem_buf(data, len)) == NULL)\n\t\t\tgoto done;", "\t\tif ((peerkey = EVP_PKEY_new()) == NULL)\n\t\t\tgoto sslerr;\n\t\tif ((peerrsa = d2i_RSAPublicKey_bio(rawcert, NULL))) {\n\t\t\tif (!EVP_PKEY_set1_RSA(peerkey, peerrsa)) {\n\t\t\t\tgoto sslerr;\n\t\t\t}\n\t\t} else if (BIO_reset(rawcert) == 1 &&\n\t\t (peerec = d2i_EC_PUBKEY_bio(rawcert, NULL))) {\n\t\t\tif (!EVP_PKEY_set1_EC_KEY(peerkey, peerec)) {\n\t\t\t\tgoto sslerr;\n\t\t\t}\n\t\t} else {\n\t\t\tlog_debug(\"%s: unknown key type received\", __func__);\n\t\t\tgoto sslerr;\n\t\t}\n\t}", "\tlc_idtype(idstr);\n\tif (strlcpy(file, IKED_PUBKEY_DIR, sizeof(file)) >= sizeof(file) ||\n\t strlcat(file, idstr, sizeof(file)) >= sizeof(file)) {\n\t\tlog_debug(\"%s: public key id too long %s\", __func__, idstr);\n\t\tgoto done;\n\t}", "\tif ((fp = fopen(file, \"r\")) == NULL) {\n\t\t/* Log to debug when called from ca_validate_cert */\n\t\tlogit(len == 0 ? LOG_DEBUG : LOG_INFO,\n\t\t \"%s: could not open public key %s\", __func__, file);\n\t\tgoto done;\n\t}\n\tlocalkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL);\n\tif (localkey == NULL) {\n\t\t/* reading PKCS #8 failed, try PEM RSA */\n\t\trewind(fp);\n\t\tlocalrsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL);\n\t\tfclose(fp);\n\t\tif (localrsa == NULL)\n\t\t\tgoto sslerr;\n\t\tif ((localkey = EVP_PKEY_new()) == NULL)\n\t\t\tgoto sslerr;\n\t\tif (!EVP_PKEY_set1_RSA(localkey, localrsa))\n\t\t\tgoto sslerr;\n\t} else {\n\t\tfclose(fp);\n\t}\n\tif (localkey == NULL)\n\t\tgoto sslerr;\n", "\tif (peerkey && !EVP_PKEY_cmp(peerkey, localkey)) {", "\t\tlog_debug(\"%s: public key does not match %s\", __func__, file);\n\t\tgoto done;\n\t}", "\tlog_debug(\"%s: valid public key in file %s\", __func__, file);", "\tif (out && ca_pubkey_serialize(localkey, out))\n\t\tgoto done;", "\tret = 0;\n sslerr:\n\tif (ret != 0)\n\t\tca_sslerror(__func__);\n done:\n\tibuf_release(idp.id_buf);\n\tif (localkey != NULL)\n\t\tEVP_PKEY_free(localkey);\n\tif (peerrsa != NULL)\n\t\tRSA_free(peerrsa);\n\tif (peerec != NULL)\n\t\tEC_KEY_free(peerec);\n\tif (localrsa != NULL)\n\t\tRSA_free(localrsa);\n\tif (rawcert != NULL) {\n\t\tBIO_free(rawcert);\n\t\tif (peerkey != NULL)\n\t\t\tEVP_PKEY_free(peerkey);\n\t}", "\treturn (ret);\n}", "int\nca_validate_cert(struct iked *env, struct iked_static_id *id,\n void *data, size_t len)\n{\n\tstruct ca_store\t*store = env->sc_priv;\n\tX509_STORE_CTX\t csc;\n\tBIO\t\t*rawcert = NULL;\n\tX509\t\t*cert = NULL;\n\tEVP_PKEY\t*pkey;\n\tint\t\t ret = -1, result, error;\n\tX509_NAME\t*subject;\n\tconst char\t*errstr = \"failed\";", "\tif (len == 0) {\n\t\t/* Data is already an X509 certificate */\n\t\tcert = (X509 *)data;\n\t} else {\n\t\t/* Convert data to X509 certificate */\n\t\tif ((rawcert = BIO_new_mem_buf(data, len)) == NULL)\n\t\t\tgoto done;\n\t\tif ((cert = d2i_X509_bio(rawcert, NULL)) == NULL)\n\t\t\tgoto done;\n\t}", "\t/* Certificate needs a valid subjectName */\n\tif ((subject = X509_get_subject_name(cert)) == NULL) {\n\t\terrstr = \"invalid subject\";\n\t\tgoto done;\n\t}", "\tif (id != NULL) {\n\t\tif ((pkey = X509_get_pubkey(cert)) == NULL) {\n\t\t\terrstr = \"no public key in cert\";\n\t\t\tgoto done;\n\t\t}\n\t\tret = ca_validate_pubkey(env, id, pkey, 0, NULL);\n\t\tEVP_PKEY_free(pkey);\n\t\tif (ret == 0) {\n\t\t\terrstr = \"in public key file, ok\";\n\t\t\tgoto done;\n\t\t}", "\t\tswitch (id->id_type) {\n\t\tcase IKEV2_ID_ASN1_DN:\n\t\t\tif (ca_x509_subject_cmp(cert, id) < 0) {\n\t\t\t\terrstr = \"ASN1_DN identifier mismatch\";\n\t\t\t\tgoto done;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (ca_x509_subjectaltname_cmp(cert, id) != 0) {\n\t\t\t\terrstr = \"invalid subjectAltName extension\";\n\t\t\t\tgoto done;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}", "\tbzero(&csc, sizeof(csc));\n\tX509_STORE_CTX_init(&csc, store->ca_cas, cert, NULL);\n\tif (store->ca_cas->param->flags & X509_V_FLAG_CRL_CHECK) {\n\t\tX509_STORE_CTX_set_flags(&csc, X509_V_FLAG_CRL_CHECK);\n\t\tX509_STORE_CTX_set_flags(&csc, X509_V_FLAG_CRL_CHECK_ALL);\n\t}", "\tresult = X509_verify_cert(&csc);\n\terror = csc.error;\n\tX509_STORE_CTX_cleanup(&csc);\n\tif (error != 0) {\n\t\terrstr = X509_verify_cert_error_string(error);\n\t\tgoto done;\n\t}", "\tif (!result) {\n\t\t/* XXX should we accept self-signed certificates? */\n\t\terrstr = \"rejecting self-signed certificate\";\n\t\tgoto done;\n\t}", "\t/* Success */\n\tret = 0;\n\terrstr = \"ok\";", " done:\n\tif (cert != NULL)\n\t\tlog_debug(\"%s: %s %.100s\", __func__, cert->name, errstr);", "\tif (rawcert != NULL) {\n\t\tBIO_free(rawcert);\n\t\tif (cert != NULL)\n\t\t\tX509_free(cert);\n\t}", "\treturn (ret);\n}", "/* check if subject from cert matches the id */\nint\nca_x509_subject_cmp(X509 *cert, struct iked_static_id *id)\n{\n\tX509_NAME\t*subject, *idname = NULL;\n\tconst uint8_t\t*idptr;\n\tsize_t\t\t idlen;\n\tint\t\t ret = -1;", "\tif (id->id_type != IKEV2_ID_ASN1_DN)\n\t\treturn (-1);\n\tif ((subject = X509_get_subject_name(cert)) == NULL)\n\t\treturn (-1);\n\tif (id->id_length <= id->id_offset)\n\t\treturn (-1);\n\tidlen = id->id_length - id->id_offset;\n\tidptr = id->id_data + id->id_offset;\n\tif ((idname = d2i_X509_NAME(NULL, &idptr, idlen)) == NULL)\n\t\treturn (-1);\n\tif (X509_NAME_cmp(subject, idname) == 0)\n\t\tret = 0;\n\tX509_NAME_free(idname);\n\treturn (ret);\n}", "#define MODE_ALT_LOG\t1\n#define MODE_ALT_GET\t2\n#define MODE_ALT_CMP\t3\nint\nca_x509_subjectaltname_do(X509 *cert, int mode, const char *logmsg,\n struct iked_static_id *id, struct iked_id *retid)\n{\n\tSTACK_OF(GENERAL_NAME) *stack = NULL;\n\tGENERAL_NAME *entry;\n\tASN1_STRING *cstr;\n\tchar idstr[IKED_ID_SIZE];\n\tint idx, ret, i, type, len;\n\tuint8_t *data;", "\tret = -1;\n\tidx = -1;\n\twhile ((stack = X509_get_ext_d2i(cert, NID_subject_alt_name,\n\t NULL, &idx)) != NULL) {\n\t\tfor (i = 0; i < sk_GENERAL_NAME_num(stack); i++) {\n\t\t\tentry = sk_GENERAL_NAME_value(stack, i);\n\t\t\tswitch (entry->type) {\n\t\t\tcase GEN_DNS:\n\t\t\t\tcstr = entry->d.dNSName;\n\t\t\t\tif (ASN1_STRING_type(cstr) != V_ASN1_IA5STRING)\n\t\t\t\t\tcontinue;\n\t\t\t\ttype = IKEV2_ID_FQDN;\n\t\t\t\tbreak;\n\t\t\tcase GEN_EMAIL:\n\t\t\t\tcstr = entry->d.rfc822Name;\n\t\t\t\tif (ASN1_STRING_type(cstr) != V_ASN1_IA5STRING)\n\t\t\t\t\tcontinue;\n\t\t\t\ttype = IKEV2_ID_UFQDN;\n\t\t\t\tbreak;\n\t\t\tcase GEN_IPADD:\n\t\t\t\tcstr = entry->d.iPAddress;\n\t\t\t\tswitch (ASN1_STRING_length(cstr)) {\n\t\t\t\tcase 4:\n\t\t\t\t\ttype = IKEV2_ID_IPV4;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 16:\n\t\t\t\t\ttype = IKEV2_ID_IPV6;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlog_debug(\"%s: invalid subjectAltName\"\n\t\t\t\t\t \" IP address\", __func__);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlen = ASN1_STRING_length(cstr);\n\t\t\tdata = ASN1_STRING_data(cstr);\n\t\t\tif (mode == MODE_ALT_LOG) {\n\t\t\t\tstruct iked_id sanid;", "\t\t\t\tbzero(&sanid, sizeof(sanid));\n\t\t\t\tsanid.id_offset = 0;\n\t\t\t\tsanid.id_type = type;\n\t\t\t\tif ((sanid.id_buf = ibuf_new(data, len))\n\t\t\t\t == NULL) {\n\t\t\t\t\tlog_debug(\"%s: failed to get id buffer\",\n\t\t\t\t\t __func__);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tikev2_print_id(&sanid, idstr, sizeof(idstr));\n\t\t\t\tlog_info(\"%s: altname: %s\", logmsg, idstr);\n\t\t\t\tibuf_release(sanid.id_buf);\n\t\t\t\tsanid.id_buf = NULL;\n\t\t\t}\n\t\t\t/* Compare length and data */\n\t\t\tif (mode == MODE_ALT_CMP) {\n\t\t\t\tif (type == id->id_type &&\n\t\t\t\t (len == (id->id_length - id->id_offset)) &&\n\t\t\t\t (memcmp(id->id_data + id->id_offset,\n\t\t\t\t data, len)) == 0) {\n\t\t\t\t\tret = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t/* Get first ID */\n\t\t\tif (mode == MODE_ALT_GET) {\n\t\t\t\tibuf_release(retid->id_buf);\n\t\t\t\tif ((retid->id_buf = ibuf_new(data, len)) == NULL) {\n\t\t\t\t\tlog_debug(\"%s: failed to get id buffer\",\n\t\t\t\t\t __func__);\n\t\t\t\t\tret = -2;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tretid->id_offset = 0;\n\t\t\t\tikev2_print_id(retid, idstr, sizeof(idstr));\n\t\t\t\tlog_debug(\"%s: %s\", __func__, idstr);\n\t\t\t\tret = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tsk_GENERAL_NAME_pop_free(stack, GENERAL_NAME_free);\n\t\tif (ret != -1)\n\t\t\tbreak;\n\t}\n\tif (idx == -1)\n\t\tlog_debug(\"%s: did not find subjectAltName in certificate\",\n\t\t __func__);\n\treturn ret;\n}", "int\nca_x509_subjectaltname_log(X509 *cert, const char *logmsg)\n{\n\treturn ca_x509_subjectaltname_do(cert, MODE_ALT_LOG, logmsg, NULL, NULL);\n}", "int\nca_x509_subjectaltname_cmp(X509 *cert, struct iked_static_id *id)\n{\n\treturn ca_x509_subjectaltname_do(cert, MODE_ALT_CMP, NULL, id, NULL);\n}", "int\nca_x509_subjectaltname_get(X509 *cert, struct iked_id *retid)\n{\n\treturn ca_x509_subjectaltname_do(cert, MODE_ALT_GET, NULL, NULL, retid);\n}", "void\nca_sslinit(void)\n{\n\tOpenSSL_add_all_algorithms();\n\tERR_load_crypto_strings();", "\t/* Init hardware crypto engines. */\n\tENGINE_load_builtin_engines();\n\tENGINE_register_all_complete();\n}", "void\nca_sslerror(const char *caller)\n{\n\tunsigned long\t error;", "\twhile ((error = ERR_get_error()) != 0)\n\t\tlog_warnx(\"%s: %s: %.100s\", __func__, caller,\n\t\t ERR_error_string(error, NULL));\n}" ]
[ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1424], "buggy_code_start_loc": [1], "filenames": ["sbin/iked/ca.c"], "fixing_code_end_loc": [1424], "fixing_code_start_loc": [1], "message": "iked in OpenIKED, as used in OpenBSD through 6.7, allows authentication bypass because ca.c has the wrong logic for checking whether a public key matches.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:openbsd:openbsd:*:*:*:*:*:*:*:*", "matchCriteriaId": "9A2FECEE-1724-4D96-8165-3AA952EDD4DC", "versionEndExcluding": null, "versionEndIncluding": "6.7", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "iked in OpenIKED, as used in OpenBSD through 6.7, allows authentication bypass because ca.c has the wrong logic for checking whether a public key matches."}, {"lang": "es", "value": "iked en OpenIKED, como es usado en OpenBSD versiones hasta 6.7, permite omitir una autenticaci\u00f3n porque el archivo ca.c presenta una l\u00f3gica equivocada para comprobar si una clave p\u00fablica coincide"}], "evaluatorComment": null, "id": "CVE-2020-16088", "lastModified": "2022-01-04T16:32:52.703", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-07-28T12:15:12.067", "references": [{"source": "cve@mitre.org", "tags": ["Exploit", "Vendor Advisory"], "url": "https://ftp.openbsd.org/pub/OpenBSD/patches/6.7/common/014_iked.patch.sig"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/openbsd/src/commit/7afb2d41c6d373cf965285840b85c45011357115"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/xcllnt/openiked/commits/master"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://www.openiked.org/security.html"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-287"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/openbsd/src/commit/7afb2d41c6d373cf965285840b85c45011357115"}, "type": "CWE-287"}
322
Determine whether the {function_name} code is vulnerable or not.
[ "/*\t$OpenBSD: ca.c,v 1.65 2020/07/27 14:22:53 tobhe Exp $\t*/", "\n/*\n * Copyright (c) 2010-2013 Reyk Floeter <reyk@openbsd.org>\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */", "#include <sys/queue.h>\n#include <sys/socket.h>\n#include <sys/wait.h>\n#include <sys/uio.h>", "#include <stdlib.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <dirent.h>\n#include <string.h>\n#include <signal.h>\n#include <syslog.h>\n#include <errno.h>\n#include <err.h>\n#include <pwd.h>\n#include <event.h>", "#include <openssl/bio.h>\n#include <openssl/err.h>\n#include <openssl/engine.h>\n#include <openssl/ssl.h>\n#include <openssl/x509.h>\n#include <openssl/x509v3.h>\n#include <openssl/pem.h>\n#include <openssl/evp.h>\n#include <openssl/sha.h>\n#include <openssl/rsa.h>", "#include \"iked.h\"\n#include \"ikev2.h\"", "void\t ca_run(struct privsep *, struct privsep_proc *, void *);\nvoid\t ca_shutdown(struct privsep_proc *);\nvoid\t ca_reset(struct privsep *);\nint\t ca_reload(struct iked *);", "int\t ca_getreq(struct iked *, struct imsg *);\nint\t ca_getcert(struct iked *, struct imsg *);\nint\t ca_getauth(struct iked *, struct imsg *);\nX509\t*ca_by_subjectpubkey(X509_STORE *, uint8_t *, size_t);\nX509\t*ca_by_issuer(X509_STORE *, X509_NAME *, struct iked_static_id *);\nX509\t*ca_by_subjectaltname(X509_STORE *, struct iked_static_id *);\nvoid\t ca_store_certs_info(const char *, X509_STORE *);\nint\t ca_subjectpubkey_digest(X509 *, uint8_t *, unsigned int *);\nint\t ca_x509_subject_cmp(X509 *, struct iked_static_id *);\nint\t ca_validate_pubkey(struct iked *, struct iked_static_id *,\n\t void *, size_t, struct iked_id *);\nint\t ca_validate_cert(struct iked *, struct iked_static_id *,\n\t void *, size_t);\nint\t ca_privkey_to_method(struct iked_id *);\nstruct ibuf *\n\t ca_x509_serialize(X509 *);\nint\t ca_x509_subjectaltname_do(X509 *, int, const char *,\n\t struct iked_static_id *, struct iked_id *);\nint\t ca_x509_subjectaltname_cmp(X509 *, struct iked_static_id *);\nint\t ca_x509_subjectaltname_log(X509 *, const char *);\nint\t ca_x509_subjectaltname_get(X509 *cert, struct iked_id *);\nint\t ca_dispatch_parent(int, struct privsep_proc *, struct imsg *);\nint\t ca_dispatch_ikev2(int, struct privsep_proc *, struct imsg *);", "static struct privsep_proc procs[] = {\n\t{ \"parent\",\tPROC_PARENT,\tca_dispatch_parent },\n\t{ \"ikev2\",\tPROC_IKEV2,\tca_dispatch_ikev2 }\n};", "struct ca_store {\n\tX509_STORE\t*ca_cas;\n\tX509_LOOKUP\t*ca_calookup;", "\tX509_STORE\t*ca_certs;\n\tX509_LOOKUP\t*ca_certlookup;", "\tstruct iked_id\t ca_privkey;\n\tstruct iked_id\t ca_pubkey;", "\tuint8_t\t\t ca_privkey_method;\n};", "pid_t\ncaproc(struct privsep *ps, struct privsep_proc *p)\n{\n\treturn (proc_run(ps, p, procs, nitems(procs), ca_run, NULL));\n}", "void\nca_run(struct privsep *ps, struct privsep_proc *p, void *arg)\n{\n\tstruct iked\t*env = ps->ps_env;\n\tstruct ca_store\t*store;", "\t/*\n\t * pledge in the ca process:\n\t * stdio - for malloc and basic I/O including events.\n\t * rpath - for certificate files.\n\t * recvfd - for ocsp sockets.\n\t */\n\tif (pledge(\"stdio rpath recvfd\", NULL) == -1)\n\t\tfatal(\"pledge\");", "\tif ((store = calloc(1, sizeof(*store))) == NULL)\n\t\tfatal(\"%s: failed to allocate cert store\", __func__);", "\tenv->sc_priv = store;\n\tp->p_shutdown = ca_shutdown;\n}", "void\nca_shutdown(struct privsep_proc *p)\n{\n\tstruct iked *env = p->p_env;\n\tstruct ca_store\t\t*store;", "\tif (env == NULL)\n\t\treturn;\n\tibuf_release(env->sc_certreq);\n\tif ((store = env->sc_priv) == NULL)\n\t\treturn;\n\tibuf_release(store->ca_pubkey.id_buf);\n\tibuf_release(store->ca_privkey.id_buf);\n\tfree(store);\n}", "void\nca_getkey(struct privsep *ps, struct iked_id *key, enum imsg_type type)\n{\n\tstruct iked\t*env = ps->ps_env;\n\tstruct ca_store\t*store = env->sc_priv;\n\tstruct iked_id\t*id;\n\tconst char\t*name;", "\tif (store == NULL)\n\t\tfatalx(\"%s: invalid store\", __func__);", "\tif (type == IMSG_PRIVKEY) {\n\t\tname = \"private\";\n\t\tid = &store->ca_privkey;", "\t\tstore->ca_privkey_method = ca_privkey_to_method(key);\n\t\tif (store->ca_privkey_method == IKEV2_AUTH_NONE)\n\t\t\tfatalx(\"ca: failed to get auth method for privkey\");\n\t} else if (type == IMSG_PUBKEY) {\n\t\tname = \"public\";\n\t\tid = &store->ca_pubkey;\n\t} else\n\t\tfatalx(\"%s: invalid type %d\", __func__, type);", "\tlog_debug(\"%s: received %s key type %s length %zd\", __func__,\n\t name, print_map(key->id_type, ikev2_cert_map),\n\t ibuf_length(key->id_buf));", "\t/* clear old key and copy new one */\n\tibuf_release(id->id_buf);\n\tmemcpy(id, key, sizeof(*id));\n}", "void\nca_reset(struct privsep *ps)\n{\n\tstruct iked\t*env = ps->ps_env;\n\tstruct ca_store\t*store = env->sc_priv;", "\tif (store->ca_privkey.id_type == IKEV2_ID_NONE ||\n\t store->ca_pubkey.id_type == IKEV2_ID_NONE)\n\t\tfatalx(\"ca_reset: keys not loaded\");", "\tif (store->ca_cas != NULL)\n\t\tX509_STORE_free(store->ca_cas);\n\tif (store->ca_certs != NULL)\n\t\tX509_STORE_free(store->ca_certs);", "\tif ((store->ca_cas = X509_STORE_new()) == NULL)\n\t\tfatalx(\"ca_reset: failed to get ca store\");\n\tif ((store->ca_calookup = X509_STORE_add_lookup(store->ca_cas,\n\t X509_LOOKUP_file())) == NULL)\n\t\tfatalx(\"ca_reset: failed to add ca lookup\");", "\tif ((store->ca_certs = X509_STORE_new()) == NULL)\n\t\tfatalx(\"ca_reset: failed to get cert store\");\n\tif ((store->ca_certlookup = X509_STORE_add_lookup(store->ca_certs,\n\t X509_LOOKUP_file())) == NULL)\n\t\tfatalx(\"ca_reset: failed to add cert lookup\");", "\tif (ca_reload(env) != 0)\n\t\tfatal(\"ca_reset: reload\");\n}", "int\nca_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg)\n{\n\tstruct iked\t\t*env = p->p_env;\n\tunsigned int\t\t mode;", "\tswitch (imsg->hdr.type) {\n\tcase IMSG_CTL_RESET:\n\t\tIMSG_SIZE_CHECK(imsg, &mode);\n\t\tmemcpy(&mode, imsg->data, sizeof(mode));\n\t\tif (mode == RESET_ALL || mode == RESET_CA) {\n\t\t\tlog_debug(\"%s: config reset\", __func__);\n\t\t\tca_reset(&env->sc_ps);\n\t\t}\n\t\tbreak;\n\tcase IMSG_OCSP_FD:\n\t\tocsp_receive_fd(env, imsg);\n\t\tbreak;\n\tcase IMSG_OCSP_URL:\n\t\tconfig_getocsp(env, imsg);\n\t\tbreak;\n\tcase IMSG_PRIVKEY:\n\tcase IMSG_PUBKEY:\n\t\tconfig_getkey(env, imsg);\n\t\tbreak;\n\tdefault:\n\t\treturn (-1);\n\t}", "\treturn (0);\n}", "int\nca_dispatch_ikev2(int fd, struct privsep_proc *p, struct imsg *imsg)\n{\n\tstruct iked\t*env = p->p_env;", "\tswitch (imsg->hdr.type) {\n\tcase IMSG_CERTREQ:\n\t\tca_getreq(env, imsg);\n\t\tbreak;\n\tcase IMSG_CERT:\n\t\tca_getcert(env, imsg);\n\t\tbreak;\n\tcase IMSG_AUTH:\n\t\tca_getauth(env, imsg);\n\t\tbreak;\n\tdefault:\n\t\treturn (-1);\n\t}", "\treturn (0);\n}", "int\nca_setcert(struct iked *env, struct iked_sahdr *sh, struct iked_id *id,\n uint8_t type, uint8_t *data, size_t len, enum privsep_procid procid)\n{\n\tstruct iovec\t\tiov[4];\n\tint\t\t\tiovcnt = 0;\n\tstruct iked_static_id\tidb;", "\t/* Must send the cert and a valid Id to the ca process */\n\tif (procid == PROC_CERT) {\n\t\tif (id == NULL || id->id_type == IKEV2_ID_NONE ||\n\t\t ibuf_length(id->id_buf) > IKED_ID_SIZE)\n\t\t\treturn (-1);\n\t\tbzero(&idb, sizeof(idb));", "\t\t/* Convert to a static Id */\n\t\tidb.id_type = id->id_type;\n\t\tidb.id_offset = id->id_offset;\n\t\tidb.id_length = ibuf_length(id->id_buf);\n\t\tmemcpy(&idb.id_data, ibuf_data(id->id_buf),\n\t\t ibuf_length(id->id_buf));", "\t\tiov[iovcnt].iov_base = &idb;\n\t\tiov[iovcnt].iov_len = sizeof(idb);\n\t\tiovcnt++;\n\t}", "\tiov[iovcnt].iov_base = sh;\n\tiov[iovcnt].iov_len = sizeof(*sh);\n\tiovcnt++;\n\tiov[iovcnt].iov_base = &type;\n\tiov[iovcnt].iov_len = sizeof(type);\n\tiovcnt++;\n\tif (data != NULL) {\n\t\tiov[iovcnt].iov_base = data;\n\t\tiov[iovcnt].iov_len = len;\n\t\tiovcnt++;\n\t}", "\tif (proc_composev(&env->sc_ps, procid, IMSG_CERT, iov, iovcnt) == -1)\n\t\treturn (-1);\n\treturn (0);\n}", "int\nca_setreq(struct iked *env, struct iked_sa *sa,\n struct iked_static_id *localid, uint8_t type, uint8_t more, uint8_t *data,\n size_t len, enum privsep_procid procid)\n{\n\tstruct iovec\t\tiov[5];\n\tint\t\t\tiovcnt = 0;\n\tstruct iked_static_id\tidb;\n\tstruct iked_id\t\tid;\n\tint\t\t\tret = -1;", "\t/* Convert to a static Id */\n\tbzero(&id, sizeof(id));\n\tif (ikev2_policy2id(localid, &id, 1) != 0)\n\t\treturn (-1);", "\tbzero(&idb, sizeof(idb));\n\tidb.id_type = id.id_type;\n\tidb.id_offset = id.id_offset;\n\tidb.id_length = ibuf_length(id.id_buf);\n\tmemcpy(&idb.id_data, ibuf_data(id.id_buf),\n\t ibuf_length(id.id_buf));\n\tiov[iovcnt].iov_base = &idb;\n\tiov[iovcnt].iov_len = sizeof(idb);\n\tiovcnt++;", "\tiov[iovcnt].iov_base = &sa->sa_hdr;\n\tiov[iovcnt].iov_len = sizeof(sa->sa_hdr);\n\tiovcnt++;\n\tiov[iovcnt].iov_base = &type;\n\tiov[iovcnt].iov_len = sizeof(type);\n\tiovcnt++;\n\tiov[iovcnt].iov_base = &more;\n\tiov[iovcnt].iov_len = sizeof(more);\n\tiovcnt++;\n\tif (data != NULL) {\n\t\tiov[iovcnt].iov_base = data;\n\t\tiov[iovcnt].iov_len = len;\n\t\tiovcnt++;\n\t}", "\tif (proc_composev(&env->sc_ps, procid, IMSG_CERTREQ, iov, iovcnt) == -1)\n\t\tgoto done;", "\tsa_stateflags(sa, IKED_REQ_CERTREQ);", "\tret = 0;\n done:\n\tibuf_release(id.id_buf);\n\treturn (ret);\n}", "static int\nauth_sig_compatible(uint8_t type)\n{\n\tswitch (type) {\n\tcase IKEV2_AUTH_RSA_SIG:\n\tcase IKEV2_AUTH_ECDSA_256:\n\tcase IKEV2_AUTH_ECDSA_384:\n\tcase IKEV2_AUTH_ECDSA_521:\n\tcase IKEV2_AUTH_SIG_ANY:\n\t\treturn (1);\n\t}\n\treturn (0);\n}", "int\nca_setauth(struct iked *env, struct iked_sa *sa,\n struct ibuf *authmsg, enum privsep_procid id)\n{\n\tstruct iovec\t\t iov[3];\n\tint\t\t\t iovcnt = 3;\n\tstruct iked_policy\t*policy = sa->sa_policy;\n\tuint8_t\t\t\t type = policy->pol_auth.auth_method;", "\tif (id == PROC_CERT) {\n\t\t/* switch encoding to IKEV2_AUTH_SIG if SHA2 is supported */\n\t\tif (sa->sa_sigsha2 && auth_sig_compatible(type)) {\n\t\t\tlog_debug(\"%s: switching %s to SIG\", __func__,\n\t\t\t print_map(type, ikev2_auth_map));\n\t\t\ttype = IKEV2_AUTH_SIG;\n\t\t} else if (!sa->sa_sigsha2 && type == IKEV2_AUTH_SIG_ANY) {\n\t\t\tlog_debug(\"%s: switching SIG to RSA_SIG(*)\", __func__);\n\t\t\t/* XXX ca might auto-switch to ECDSA */\n\t\t\ttype = IKEV2_AUTH_RSA_SIG;\n\t\t} else if (type == IKEV2_AUTH_SIG) {\n\t\t\tlog_debug(\"%s: using SIG (RFC7427)\", __func__);\n\t\t}\n\t}", "\tif (type == IKEV2_AUTH_SHARED_KEY_MIC) {\n\t\tsa->sa_stateflags |= IKED_REQ_AUTH;\n\t\treturn (ikev2_msg_authsign(env, sa,\n\t\t &policy->pol_auth, authmsg));\n\t}", "\tiov[0].iov_base = &sa->sa_hdr;\n\tiov[0].iov_len = sizeof(sa->sa_hdr);\n\tiov[1].iov_base = &type;\n\tiov[1].iov_len = sizeof(type);\n\tif (type == IKEV2_AUTH_NONE)\n\t\tiovcnt--;\n\telse {\n\t\tiov[2].iov_base = ibuf_data(authmsg);\n\t\tiov[2].iov_len = ibuf_size(authmsg);\n\t\tlog_debug(\"%s: auth length %zu\", __func__, ibuf_size(authmsg));\n\t}", "\tif (proc_composev(&env->sc_ps, id, IMSG_AUTH, iov, iovcnt) == -1)\n\t\treturn (-1);\n\treturn (0);\n}", "int\nca_getcert(struct iked *env, struct imsg *imsg)\n{\n\tstruct iked_sahdr\t sh;\n\tuint8_t\t\t\t type;\n\tuint8_t\t\t\t*ptr;\n\tsize_t\t\t\t len;\n\tstruct iked_static_id\t id;\n\tunsigned int\t\t i;\n\tstruct iovec\t\t iov[3];\n\tint\t\t\t iovcnt = 3, cmd, ret = 0;\n\tstruct iked_id\t\t key;", "\tptr = (uint8_t *)imsg->data;\n\tlen = IMSG_DATA_SIZE(imsg);\n\ti = sizeof(id) + sizeof(sh) + sizeof(type);\n\tif (len < i)\n\t\treturn (-1);", "\tmemcpy(&id, ptr, sizeof(id));\n\tif (id.id_type == IKEV2_ID_NONE)\n\t\treturn (-1);\n\tmemcpy(&sh, ptr + sizeof(id), sizeof(sh));\n\tmemcpy(&type, ptr + sizeof(id) + sizeof(sh), sizeof(uint8_t));", "\tptr += i;\n\tlen -= i;", "\tbzero(&key, sizeof(key));", "\tswitch (type) {\n\tcase IKEV2_CERT_X509_CERT:\n\t\tret = ca_validate_cert(env, &id, ptr, len);\n\t\tif (ret == 0 && env->sc_ocsp_url) {\n\t\t\tret = ocsp_validate_cert(env, &id, ptr, len, sh, type);\n\t\t\tif (ret == 0)\n\t\t\t\treturn (0);\n\t\t}\n\t\tbreak;\n\tcase IKEV2_CERT_RSA_KEY:\n\tcase IKEV2_CERT_ECDSA:\n\t\tret = ca_validate_pubkey(env, &id, ptr, len, NULL);\n\t\tbreak;\n\tcase IKEV2_CERT_NONE:\n\t\t/* Fallback to public key */\n\t\tret = ca_validate_pubkey(env, &id, NULL, 0, &key);\n\t\tif (ret == 0) {\n\t\t\tptr = ibuf_data(key.id_buf);\n\t\t\tlen = ibuf_length(key.id_buf);\n\t\t\ttype = key.id_type;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tlog_debug(\"%s: unsupported cert type %d\", __func__, type);\n\t\tret = -1;\n\t\tbreak;\n\t}", "\tif (ret == 0)\n\t\tcmd = IMSG_CERTVALID;\n\telse\n\t\tcmd = IMSG_CERTINVALID;", "\tiov[0].iov_base = &sh;\n\tiov[0].iov_len = sizeof(sh);\n\tiov[1].iov_base = &type;\n\tiov[1].iov_len = sizeof(type);\n\tiov[2].iov_base = ptr;\n\tiov[2].iov_len = len;", "\tif (proc_composev(&env->sc_ps, PROC_IKEV2, cmd, iov, iovcnt) == -1)\n\t\treturn (-1);\n\treturn (0);\n}", "int\nca_getreq(struct iked *env, struct imsg *imsg)\n{\n\tstruct ca_store\t\t*store = env->sc_priv;\n\tstruct iked_sahdr\t sh;\n\tuint8_t\t\t\t type, more;\n\tuint8_t\t\t\t*ptr;\n\tsize_t\t\t\t len;\n\tunsigned int\t\t i;\n\tX509\t\t\t*ca = NULL, *cert = NULL;\n\tstruct ibuf\t\t*buf;\n\tstruct iked_static_id\t id;\n\tchar\t\t\t idstr[IKED_ID_SIZE];", "\tptr = (uint8_t *)imsg->data;\n\tlen = IMSG_DATA_SIZE(imsg);\n\ti = sizeof(id) + sizeof(type) + sizeof(sh) + sizeof(more);\n\tif (len < i)\n\t\treturn (-1);", "\tmemcpy(&id, ptr, sizeof(id));\n\tif (id.id_type == IKEV2_ID_NONE)\n\t\treturn (-1);\n\tmemcpy(&sh, ptr + sizeof(id), sizeof(sh));\n\tmemcpy(&type, ptr + sizeof(id) + sizeof(sh), sizeof(type));\n\tmemcpy(&more, ptr + sizeof(id) + sizeof(sh) + sizeof(type), sizeof(more));", "\tptr += i;\n\tlen -= i;", "\tswitch (type) {\n\tcase IKEV2_CERT_RSA_KEY:\n\tcase IKEV2_CERT_ECDSA:\n\t\t/*\n\t\t * Find a local raw public key that matches the type\n\t\t * received in the CERTREQ payoad\n\t\t */\n\t\tif (store->ca_pubkey.id_type != type ||\n\t\t store->ca_pubkey.id_buf == NULL)\n\t\t\tgoto fallback;", "\t\tbuf = ibuf_dup(store->ca_pubkey.id_buf);\n\t\tlog_debug(\"%s: using local public key of type %s\", __func__,\n\t\t print_map(type, ikev2_cert_map));\n\t\tbreak;\n\tcase IKEV2_CERT_X509_CERT:\n\t\tif (len == 0 || len % SHA_DIGEST_LENGTH) {\n\t\t\tlog_info(\"%s: invalid CERTREQ data.\",\n\t\t\t SPI_SH(&sh, __func__));\n\t\t\treturn (-1);\n\t\t}", "\t\t/*\n\t\t * Find a local certificate signed by any of the CAs\n\t\t * received in the CERTREQ payload\n\t\t */\n\t\tfor (i = 0; i < len; i += SHA_DIGEST_LENGTH) {\n\t\t\tif ((ca = ca_by_subjectpubkey(store->ca_cas, ptr + i,\n\t\t\t SHA_DIGEST_LENGTH)) == NULL)\n\t\t\t\tcontinue;", "\t\t\tlog_debug(\"%s: found CA %s\", __func__, ca->name);", "\t\t\tif ((cert = ca_by_issuer(store->ca_certs,\n\t\t\t X509_get_subject_name(ca), &id)) != NULL) {\n\t\t\t\t/* XXX\n\t\t\t\t * should we re-validate our own cert here?\n\t\t\t\t */\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t/* Fallthrough */\n\tcase IKEV2_CERT_NONE:\n fallback:\n\t\t/*\n\t\t * If no certificate or key matching any of the trust-anchors\n\t\t * was found and this was the last CERTREQ, try to find one with\n\t\t * subjectAltName matching the ID\n\t\t */\n\t\tif (more)\n\t\t\treturn (0);", "\t\tif (cert == NULL)\n\t\t\tcert = ca_by_subjectaltname(store->ca_certs, &id);", "\t\t/* If there is no matching certificate use local raw pubkey */\n\t\tif (cert == NULL) {\n\t\t\tif (ikev2_print_static_id(&id, idstr, sizeof(idstr)) == -1)\n\t\t\t\treturn (-1);\n\t\t\tlog_info(\"%s: no valid local certificate found for %s\",\n\t\t\t SPI_SH(&sh, __func__), idstr);\n\t\t\tca_store_certs_info(SPI_SH(&sh, __func__),\n\t\t\t store->ca_certs);\n\t\t\tif (store->ca_pubkey.id_buf == NULL)\n\t\t\t\treturn (-1);\n\t\t\tbuf = ibuf_dup(store->ca_pubkey.id_buf);\n\t\t\ttype = store->ca_pubkey.id_type;\n\t\t\tlog_info(\"%s: using local public key of type %s\",\n\t\t\t SPI_SH(&sh, __func__),\n\t\t\t print_map(type, ikev2_cert_map));\n\t\t\tbreak;\n\t\t}", "\t\tlog_debug(\"%s: found local certificate %s\", __func__,\n\t\t cert->name);", "\t\tif ((buf = ca_x509_serialize(cert)) == NULL)\n\t\t\treturn (-1);\n\t\tbreak;\n\tdefault:\n\t\tlog_warnx(\"%s: unknown cert type requested\",\n\t\t SPI_SH(&sh, __func__));\n\t\treturn (-1);\n\t}", "\tca_setcert(env, &sh, NULL, type,\n\t ibuf_data(buf), ibuf_size(buf), PROC_IKEV2);\n\tibuf_release(buf);", "\treturn (0);\n}", "int\nca_getauth(struct iked *env, struct imsg *imsg)\n{\n\tstruct ca_store\t\t*store = env->sc_priv;\n\tstruct iked_sahdr\t sh;\n\tuint8_t\t\t\t method;\n\tuint8_t\t\t\t*ptr;\n\tsize_t\t\t\t len;\n\tunsigned int\t\t i;\n\tint\t\t\t ret = -1;\n\tstruct iked_sa\t\t sa;\n\tstruct iked_policy\t policy;\n\tstruct iked_id\t\t*id;\n\tstruct ibuf\t\t*authmsg;", "\tptr = (uint8_t *)imsg->data;\n\tlen = IMSG_DATA_SIZE(imsg);\n\ti = sizeof(method) + sizeof(sh);\n\tif (len <= i)\n\t\treturn (-1);", "\tmemcpy(&sh, ptr, sizeof(sh));\n\tmemcpy(&method, ptr + sizeof(sh), sizeof(uint8_t));\n\tif (method == IKEV2_AUTH_SHARED_KEY_MIC)\n\t\treturn (-1);", "\tptr += i;\n\tlen -= i;", "\tif ((authmsg = ibuf_new(ptr, len)) == NULL)\n\t\treturn (-1);", "\t/*\n\t * Create fake SA and policy\n\t */\n\tbzero(&sa, sizeof(sa));\n\tbzero(&policy, sizeof(policy));\n\tmemcpy(&sa.sa_hdr, &sh, sizeof(sh));\n\tsa.sa_policy = &policy;\n\tif (sh.sh_initiator)\n\t\tid = &sa.sa_icert;\n\telse\n\t\tid = &sa.sa_rcert;\n\tmemcpy(id, &store->ca_privkey, sizeof(*id));\n\tpolicy.pol_auth.auth_method = method == IKEV2_AUTH_SIG ?\n\t method : store->ca_privkey_method;", "\tif (ikev2_msg_authsign(env, &sa, &policy.pol_auth, authmsg) != 0) {\n\t\tlog_debug(\"%s: AUTH sign failed\", __func__);\n\t\tpolicy.pol_auth.auth_method = IKEV2_AUTH_NONE;\n\t}", "\tret = ca_setauth(env, &sa, sa.sa_localauth.id_buf, PROC_IKEV2);", "\tibuf_release(sa.sa_localauth.id_buf);\n\tsa.sa_localauth.id_buf = NULL;\n\tibuf_release(authmsg);", "\treturn (ret);\n}", "int\nca_reload(struct iked *env)\n{\n\tstruct ca_store\t\t*store = env->sc_priv;\n\tuint8_t\t\t\t md[EVP_MAX_MD_SIZE];\n\tchar\t\t\t file[PATH_MAX];\n\tstruct iovec\t\t iov[2];\n\tstruct dirent\t\t*entry;\n\tSTACK_OF(X509_OBJECT)\t*h;\n\tX509_OBJECT\t\t*xo;\n\tX509\t\t\t*x509;\n\tDIR\t\t\t*dir;\n\tint\t\t\t i, len, iovcnt = 0;", "\t/*\n\t * Load CAs\n\t */\n\tif ((dir = opendir(IKED_CA_DIR)) == NULL)\n\t\treturn (-1);", "\twhile ((entry = readdir(dir)) != NULL) {\n\t\tif ((entry->d_type != DT_REG) &&\n\t\t (entry->d_type != DT_LNK))\n\t\t\tcontinue;", "\t\tif (snprintf(file, sizeof(file), \"%s%s\",\n\t\t IKED_CA_DIR, entry->d_name) < 0)\n\t\t\tcontinue;", "\t\tif (!X509_load_cert_file(store->ca_calookup, file,\n\t\t X509_FILETYPE_PEM)) {\n\t\t\tlog_warn(\"%s: failed to load ca file %s\", __func__,\n\t\t\t entry->d_name);\n\t\t\tca_sslerror(__func__);\n\t\t\tcontinue;\n\t\t}\n\t\tlog_debug(\"%s: loaded ca file %s\", __func__, entry->d_name);\n\t}\n\tclosedir(dir);", "\t/*\n\t * Load CRLs for the CAs\n\t */\n\tif ((dir = opendir(IKED_CRL_DIR)) == NULL)\n\t\treturn (-1);", "\twhile ((entry = readdir(dir)) != NULL) {\n\t\tif ((entry->d_type != DT_REG) &&\n\t\t (entry->d_type != DT_LNK))\n\t\t\tcontinue;", "\t\tif (snprintf(file, sizeof(file), \"%s%s\",\n\t\t IKED_CRL_DIR, entry->d_name) < 0)\n\t\t\tcontinue;", "\t\tif (!X509_load_crl_file(store->ca_calookup, file,\n\t\t X509_FILETYPE_PEM)) {\n\t\t\tlog_warn(\"%s: failed to load crl file %s\", __func__,\n\t\t\t entry->d_name);\n\t\t\tca_sslerror(__func__);\n\t\t\tcontinue;\n\t\t}", "\t\t/* Only enable CRL checks if we actually loaded a CRL */\n\t\tX509_STORE_set_flags(store->ca_cas, X509_V_FLAG_CRL_CHECK);", "\t\tlog_debug(\"%s: loaded crl file %s\", __func__, entry->d_name);\n\t}\n\tclosedir(dir);", "\t/*\n\t * Save CAs signatures for the IKEv2 CERTREQ\n\t */\n\tibuf_release(env->sc_certreq);\n\tif ((env->sc_certreq = ibuf_new(NULL, 0)) == NULL)\n\t\treturn (-1);", "\th = store->ca_cas->objs;\n\tfor (i = 0; i < sk_X509_OBJECT_num(h); i++) {\n\t\txo = sk_X509_OBJECT_value(h, i);\n\t\tif (xo->type != X509_LU_X509)\n\t\t\tcontinue;", "\t\tx509 = xo->data.x509;\n\t\tlen = sizeof(md);\n\t\tca_subjectpubkey_digest(x509, md, &len);\n\t\tlog_debug(\"%s: %s\", __func__, x509->name);", "\t\tif (ibuf_add(env->sc_certreq, md, len) != 0) {\n\t\t\tibuf_release(env->sc_certreq);\n\t\t\tenv->sc_certreq = NULL;\n\t\t\treturn (-1);\n\t\t}\n\t}", "\tif (ibuf_length(env->sc_certreq)) {\n\t\tenv->sc_certreqtype = IKEV2_CERT_X509_CERT;\n\t\tiov[0].iov_base = &env->sc_certreqtype;\n\t\tiov[0].iov_len = sizeof(env->sc_certreqtype);\n\t\tiovcnt++;\n\t\tiov[1].iov_base = ibuf_data(env->sc_certreq);\n\t\tiov[1].iov_len = ibuf_length(env->sc_certreq);\n\t\tiovcnt++;", "\t\tlog_debug(\"%s: loaded %zu ca certificate%s\", __func__,\n\t\t ibuf_length(env->sc_certreq) / SHA_DIGEST_LENGTH,\n\t\t ibuf_length(env->sc_certreq) == SHA_DIGEST_LENGTH ?\n\t\t \"\" : \"s\");", "\t\t(void)proc_composev(&env->sc_ps, PROC_IKEV2, IMSG_CERTREQ,\n\t\t iov, iovcnt);\n\t}", "\t/*\n\t * Load certificates\n\t */\n\tif ((dir = opendir(IKED_CERT_DIR)) == NULL)\n\t\treturn (-1);", "\twhile ((entry = readdir(dir)) != NULL) {\n\t\tif ((entry->d_type != DT_REG) &&\n\t\t (entry->d_type != DT_LNK))\n\t\t\tcontinue;", "\t\tif (snprintf(file, sizeof(file), \"%s%s\",\n\t\t IKED_CERT_DIR, entry->d_name) < 0)\n\t\t\tcontinue;", "\t\tif (!X509_load_cert_file(store->ca_certlookup, file,\n\t\t X509_FILETYPE_PEM)) {\n\t\t\tlog_warn(\"%s: failed to load cert file %s\", __func__,\n\t\t\t entry->d_name);\n\t\t\tca_sslerror(__func__);\n\t\t\tcontinue;\n\t\t}\n\t\tlog_debug(\"%s: loaded cert file %s\", __func__, entry->d_name);\n\t}\n\tclosedir(dir);", "\th = store->ca_certs->objs;\n\tfor (i = 0; i < sk_X509_OBJECT_num(h); i++) {\n\t\txo = sk_X509_OBJECT_value(h, i);\n\t\tif (xo->type != X509_LU_X509)\n\t\t\tcontinue;", "\t\tx509 = xo->data.x509;", "\t\t(void)ca_validate_cert(env, NULL, x509, 0);\n\t}", "\tif (!env->sc_certreqtype)\n\t\tenv->sc_certreqtype = store->ca_pubkey.id_type;", "\tlog_debug(\"%s: local cert type %s\", __func__,\n\t print_map(env->sc_certreqtype, ikev2_cert_map));", "\tiov[0].iov_base = &env->sc_certreqtype;\n\tiov[0].iov_len = sizeof(env->sc_certreqtype);\n\tif (iovcnt == 0)\n\t\tiovcnt++;\n\t(void)proc_composev(&env->sc_ps, PROC_IKEV2, IMSG_CERTREQ, iov, iovcnt);", "\treturn (0);\n}", "X509 *\nca_by_subjectpubkey(X509_STORE *ctx, uint8_t *sig, size_t siglen)\n{\n\tSTACK_OF(X509_OBJECT)\t*h;\n\tX509_OBJECT\t\t*xo;\n\tX509\t\t\t*ca;\n\tint\t\t\t i;\n\tunsigned int\t\t len;\n\tuint8_t\t\t\t md[EVP_MAX_MD_SIZE];", "\th = ctx->objs;", "\tfor (i = 0; i < sk_X509_OBJECT_num(h); i++) {\n\t\txo = sk_X509_OBJECT_value(h, i);\n\t\tif (xo->type != X509_LU_X509)\n\t\t\tcontinue;", "\t\tca = xo->data.x509;\n\t\tlen = sizeof(md);\n\t\tca_subjectpubkey_digest(ca, md, &len);", "\t\tif (len == siglen && memcmp(md, sig, len) == 0)\n\t\t\treturn (ca);\n\t}", "\treturn (NULL);\n}", "X509 *\nca_by_issuer(X509_STORE *ctx, X509_NAME *subject, struct iked_static_id *id)\n{\n\tSTACK_OF(X509_OBJECT)\t*h;\n\tX509_OBJECT\t\t*xo;\n\tX509\t\t\t*cert;\n\tint\t\t\t i;\n\tX509_NAME\t\t*issuer;", "\tif (subject == NULL)\n\t\treturn (NULL);", "\th = ctx->objs;\n\tfor (i = 0; i < sk_X509_OBJECT_num(h); i++) {\n\t\txo = sk_X509_OBJECT_value(h, i);\n\t\tif (xo->type != X509_LU_X509)\n\t\t\tcontinue;", "\t\tcert = xo->data.x509;\n\t\tif ((issuer = X509_get_issuer_name(cert)) == NULL)\n\t\t\tcontinue;\n\t\telse if (X509_NAME_cmp(subject, issuer) == 0) {\n\t\t\tswitch (id->id_type) {\n\t\t\tcase IKEV2_ID_ASN1_DN:\n\t\t\t\tif (ca_x509_subject_cmp(cert, id) == 0)\n\t\t\t\t\treturn (cert);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (ca_x509_subjectaltname_cmp(cert, id) == 0)\n\t\t\t\t\treturn (cert);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}", "\treturn (NULL);\n}", "X509 *\nca_by_subjectaltname(X509_STORE *ctx, struct iked_static_id *id)\n{\n\tSTACK_OF(X509_OBJECT)\t*h;\n\tX509_OBJECT\t\t*xo;\n\tX509\t\t\t*cert;\n\tint\t\t\t i;", "\th = ctx->objs;\n\tfor (i = 0; i < sk_X509_OBJECT_num(h); i++) {\n\t\txo = sk_X509_OBJECT_value(h, i);\n\t\tif (xo->type != X509_LU_X509)\n\t\t\tcontinue;", "\t\tcert = xo->data.x509;\n\t\tswitch (id->id_type) {\n\t\tcase IKEV2_ID_ASN1_DN:\n\t\t\tif (ca_x509_subject_cmp(cert, id) == 0)\n\t\t\t\treturn (cert);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (ca_x509_subjectaltname_cmp(cert, id) == 0)\n\t\t\t\treturn (cert);\n\t\t\tbreak;\n\t\t}\n\t}", "\treturn (NULL);\n}", "void\nca_store_certs_info(const char *msg, X509_STORE *ctx)\n{\n\tSTACK_OF(X509_OBJECT)\t*h;\n\tX509_OBJECT\t\t*xo;\n\tX509\t\t\t*cert;\n\tint\t\t\t i;", "\th = ctx->objs;\n\tfor (i = 0; i < sk_X509_OBJECT_num(h); i++) {\n\t\txo = sk_X509_OBJECT_value(h, i);\n\t\tif (xo->type != X509_LU_X509)\n\t\t\tcontinue;\n\t\tcert = xo->data.x509;\n\t\tca_cert_info(msg, cert);\n\t}\n}", "void\nca_cert_info(const char *msg, X509 *cert)\n{\n\tASN1_INTEGER\t*asn1_serial;\n\tBUF_MEM\t\t*memptr;\n\tBIO\t\t*rawserial = NULL;\n\tchar\t\t buf[BUFSIZ];", "\tif ((asn1_serial = X509_get_serialNumber(cert)) == NULL ||\n\t (rawserial = BIO_new(BIO_s_mem())) == NULL ||\n\t i2a_ASN1_INTEGER(rawserial, asn1_serial) <= 0)\n\t\tgoto out;\n\tif (X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf)))\n\t\tlog_info(\"%s: issuer: %s\", msg, buf);\n\tBIO_get_mem_ptr(rawserial, &memptr);\n\tif (memptr->data != NULL && memptr->length < INT32_MAX)\n\t\tlog_info(\"%s: serial: %.*s\", msg, (int)memptr->length,\n\t\t memptr->data);\n\tif (X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf)))\n\t\tlog_info(\"%s: subject: %s\", msg, buf);\n\tca_x509_subjectaltname_log(cert, msg);\nout:\n\tif (rawserial)\n\t\tBIO_free(rawserial);\n}", "int\nca_subjectpubkey_digest(X509 *x509, uint8_t *md, unsigned int *size)\n{\n\tEVP_PKEY\t*pkey;\n\tuint8_t\t\t*buf = NULL;\n\tint\t\t buflen;", "\tif (*size < SHA_DIGEST_LENGTH)\n\t\treturn (-1);", "\t/*\n\t * Generate a SHA-1 digest of the Subject Public Key Info\n\t * element in the X.509 certificate, an ASN.1 sequence\n\t * that includes the public key type (eg. RSA) and the\n\t * public key value (see 3.7 of RFC7296).\n\t */\n\tif ((pkey = X509_get_pubkey(x509)) == NULL)\n\t\treturn (-1);\n\tbuflen = i2d_PUBKEY(pkey, &buf);\n\tEVP_PKEY_free(pkey);\n\tif (buflen == 0)\n\t\treturn (-1);\n\tif (!EVP_Digest(buf, buflen, md, size, EVP_sha1(), NULL)) {\n\t\tfree(buf);\n\t\treturn (-1);\n\t}\n\tfree(buf);", "\treturn (0);\n}", "struct ibuf *\nca_x509_serialize(X509 *x509)\n{\n\tlong\t\t len;\n\tstruct ibuf\t*buf;\n\tuint8_t\t\t*d = NULL;\n\tBIO\t\t*out;", "\tif ((out = BIO_new(BIO_s_mem())) == NULL)\n\t\treturn (NULL);\n\tif (!i2d_X509_bio(out, x509)) {\n\t\tBIO_free(out);\n\t\treturn (NULL);\n\t}", "\tlen = BIO_get_mem_data(out, &d);\n\tbuf = ibuf_new(d, len);\n\tBIO_free(out);", "\treturn (buf);\n}", "int\nca_pubkey_serialize(EVP_PKEY *key, struct iked_id *id)\n{\n\tRSA\t\t*rsa = NULL;\n\tEC_KEY\t\t*ec = NULL;\n\tuint8_t\t\t*d;\n\tint\t\t len = 0;\n\tint\t\t ret = -1;", "\tswitch (key->type) {\n\tcase EVP_PKEY_RSA:\n\t\tid->id_type = 0;\n\t\tid->id_offset = 0;\n\t\tibuf_release(id->id_buf);\n\t\tid->id_buf = NULL;", "\t\tif ((rsa = EVP_PKEY_get1_RSA(key)) == NULL)\n\t\t\tgoto done;\n\t\tif ((len = i2d_RSAPublicKey(rsa, NULL)) <= 0)\n\t\t\tgoto done;\n\t\tif ((id->id_buf = ibuf_new(NULL, len)) == NULL)\n\t\t\tgoto done;", "\t\td = ibuf_data(id->id_buf);\n\t\tif (i2d_RSAPublicKey(rsa, &d) != len) {\n\t\t\tibuf_release(id->id_buf);\n\t\t\tid->id_buf = NULL;\n\t\t\tgoto done;\n\t\t}", "\t\tid->id_type = IKEV2_CERT_RSA_KEY;\n\t\tbreak;\n\tcase EVP_PKEY_EC:\n\t\tid->id_type = 0;\n\t\tid->id_offset = 0;\n\t\tibuf_release(id->id_buf);\n\t\tid->id_buf = NULL;", "\t\tif ((ec = EVP_PKEY_get1_EC_KEY(key)) == NULL)\n\t\t\tgoto done;\n\t\tif ((len = i2d_EC_PUBKEY(ec, NULL)) <= 0)\n\t\t\tgoto done;\n\t\tif ((id->id_buf = ibuf_new(NULL, len)) == NULL)\n\t\t\tgoto done;", "\t\td = ibuf_data(id->id_buf);\n\t\tif (i2d_EC_PUBKEY(ec, &d) != len) {\n\t\t\tibuf_release(id->id_buf);\n\t\t\tid->id_buf = NULL;\n\t\t\tgoto done;\n\t\t}", "\t\tid->id_type = IKEV2_CERT_ECDSA;\n\t\tbreak;\n\tdefault:\n\t\tlog_debug(\"%s: unsupported key type %d\", __func__, key->type);\n\t\treturn (-1);\n\t}", "\tlog_debug(\"%s: type %s length %d\", __func__,\n\t print_map(id->id_type, ikev2_cert_map), len);", "\tret = 0;\n done:\n\tif (rsa != NULL)\n\t\tRSA_free(rsa);\n\tif (ec != NULL)\n\t\tEC_KEY_free(ec);\n\treturn (ret);\n}", "int\nca_privkey_serialize(EVP_PKEY *key, struct iked_id *id)\n{\n\tRSA\t\t*rsa = NULL;\n\tEC_KEY\t\t*ec = NULL;\n\tuint8_t\t\t*d;\n\tint\t\t len = 0;\n\tint\t\t ret = -1;", "\tswitch (key->type) {\n\tcase EVP_PKEY_RSA:\n\t\tid->id_type = 0;\n\t\tid->id_offset = 0;\n\t\tibuf_release(id->id_buf);\n\t\tid->id_buf = NULL;", "\t\tif ((rsa = EVP_PKEY_get1_RSA(key)) == NULL)\n\t\t\tgoto done;\n\t\tif ((len = i2d_RSAPrivateKey(rsa, NULL)) <= 0)\n\t\t\tgoto done;\n\t\tif ((id->id_buf = ibuf_new(NULL, len)) == NULL)\n\t\t\tgoto done;", "\t\td = ibuf_data(id->id_buf);\n\t\tif (i2d_RSAPrivateKey(rsa, &d) != len) {\n\t\t\tibuf_release(id->id_buf);\n\t\t\tid->id_buf = NULL;\n\t\t\tgoto done;\n\t\t}", "\t\tid->id_type = IKEV2_CERT_RSA_KEY;\n\t\tbreak;\n\tcase EVP_PKEY_EC:\n\t\tid->id_type = 0;\n\t\tid->id_offset = 0;\n\t\tibuf_release(id->id_buf);\n\t\tid->id_buf = NULL;", "\t\tif ((ec = EVP_PKEY_get1_EC_KEY(key)) == NULL)\n\t\t\tgoto done;\n\t\tif ((len = i2d_ECPrivateKey(ec, NULL)) <= 0)\n\t\t\tgoto done;\n\t\tif ((id->id_buf = ibuf_new(NULL, len)) == NULL)\n\t\t\tgoto done;", "\t\td = ibuf_data(id->id_buf);\n\t\tif (i2d_ECPrivateKey(ec, &d) != len) {\n\t\t\tibuf_release(id->id_buf);\n\t\t\tid->id_buf = NULL;\n\t\t\tgoto done;\n\t\t}", "\t\tid->id_type = IKEV2_CERT_ECDSA;\n\t\tbreak;\n\tdefault:\n\t\tlog_debug(\"%s: unsupported key type %d\", __func__, key->type);\n\t\treturn (-1);\n\t}", "\tlog_debug(\"%s: type %s length %d\", __func__,\n\t print_map(id->id_type, ikev2_cert_map), len);", "\tret = 0;\n done:\n\tif (rsa != NULL)\n\t\tRSA_free(rsa);\n\tif (ec != NULL)\n\t\tEC_KEY_free(ec);\n\treturn (ret);\n}", "int\nca_privkey_to_method(struct iked_id *privkey)\n{\n\tBIO\t\t*rawcert = NULL;\n\tEC_KEY\t\t*ec = NULL;\n\tconst EC_GROUP\t*group = NULL;\n\tuint8_t\t method = IKEV2_AUTH_NONE;", "\tswitch (privkey->id_type) {\n\tcase IKEV2_CERT_RSA_KEY:\n\t\tmethod = IKEV2_AUTH_RSA_SIG;\n\t\tbreak;\n\tcase IKEV2_CERT_ECDSA:\n\t\tif ((rawcert = BIO_new_mem_buf(ibuf_data(privkey->id_buf),\n\t\t ibuf_length(privkey->id_buf))) == NULL)\n\t\t\tgoto out;\n\t\tif ((ec = d2i_ECPrivateKey_bio(rawcert, NULL)) == NULL)\n\t\t\tgoto out;\n\t\tif ((group = EC_KEY_get0_group(ec)) == NULL)\n\t\t\tgoto out;\n\t\tswitch (EC_GROUP_get_degree(group)) {\n\t\tcase 256:\n\t\t\tmethod = IKEV2_AUTH_ECDSA_256;\n\t\t\tbreak;\n\t\tcase 384:\n\t\t\tmethod = IKEV2_AUTH_ECDSA_384;\n\t\t\tbreak;\n\t\tcase 521:\n\t\t\tmethod = IKEV2_AUTH_ECDSA_521;\n\t\t\tbreak;\n\t\t}\n\t}", "\tlog_debug(\"%s: type %s method %s\", __func__,\n\t print_map(privkey->id_type, ikev2_cert_map),\n\t print_map(method, ikev2_auth_map));", " out:\n\tif (ec != NULL)\n\t\tEC_KEY_free(ec);\n\tif (rawcert != NULL)\n\t\tBIO_free(rawcert);", "\treturn (method);\n}", "char *\nca_asn1_name(uint8_t *asn1, size_t len)\n{\n\tX509_NAME\t*name = NULL;\n\tchar\t\t*str = NULL;\n\tconst uint8_t\t*p;", "\tp = asn1;\n\tif ((name = d2i_X509_NAME(NULL, &p, len)) == NULL)\n\t\treturn (NULL);\n\tstr = X509_NAME_oneline(name, NULL, 0);\n\tX509_NAME_free(name);", "\treturn (str);\n}", "/*\n * Copy 'src' to 'dst' until 'marker' is found while unescaping '\\'\n * characters. The return value tells the caller where to continue\n * parsing (might be the end of the string) or NULL on error.\n */\nstatic char *\nca_x509_name_unescape(char *src, char *dst, char marker)\n{\n\twhile (*src) {\n\t\tif (*src == marker) {\n\t\t\tsrc++;\n\t\t\tbreak;\n\t\t}\n\t\tif (*src == '\\\\') {\n\t\t\tsrc++;\n\t\t\tif (!*src) {\n\t\t\t\tlog_warnx(\"%s: '\\\\' at end of string\",\n\t\t\t\t __func__);\n\t\t\t\t*dst = '\\0';\n\t\t\t\treturn (NULL);\n\t\t\t}\n\t\t}\n\t\t*dst++ = *src++;\n\t}\n\t*dst = '\\0';\n\treturn (src);\n}\n/*\n * Parse an X509 subject name where 'subject' is in the format\n * /type0=value0/type1=value1/type2=...\n * where characters may be escaped by '\\'.\n * See lib/libssl/src/apps/apps.c:parse_name()\n */\nvoid *\nca_x509_name_parse(char *subject)\n{\n\tchar\t\t*cp, *value = NULL, *type = NULL;\n\tsize_t\t\t maxlen;\n\tX509_NAME\t*name = NULL;", "\tif (*subject != '/') {\n\t\tlog_warnx(\"%s: leading '/' missing in '%s'\", __func__, subject);\n\t\tgoto err;\n\t}", "\t/* length of subject is upper bound for unescaped type/value */\n\tmaxlen = strlen(subject) + 1;", "\tif ((type = calloc(1, maxlen)) == NULL ||\n\t (value = calloc(1, maxlen)) == NULL ||\n\t (name = X509_NAME_new()) == NULL)\n\t\tgoto err;", "\tcp = subject + 1;\n\twhile (*cp) {\n\t\t/* unescape type, terminated by '=' */\n\t\tcp = ca_x509_name_unescape(cp, type, '=');\n\t\tif (cp == NULL) {\n\t\t\tlog_warnx(\"%s: could not parse type\", __func__);\n\t\t\tgoto err;\n\t\t}\n\t\tif (!*cp) {\n\t\t\tlog_warnx(\"%s: missing value\", __func__);\n\t\t\tgoto err;\n\t\t}\n\t\t/* unescape value, terminated by '/' */\n\t\tcp = ca_x509_name_unescape(cp, value, '/');\n\t\tif (cp == NULL) {\n\t\t\tlog_warnx(\"%s: could not parse value\", __func__);\n\t\t\tgoto err;\n\t\t}\n\t\tif (!*type || !*value) {\n\t\t\tlog_warnx(\"%s: empty type or value\", __func__);\n\t\t\tgoto err;\n\t\t}\n\t\tlog_debug(\"%s: setting '%s' to '%s'\", __func__, type, value);\n\t\tif (!X509_NAME_add_entry_by_txt(name, type, MBSTRING_ASC,\n\t\t value, -1, -1, 0)) {\n\t\t\tlog_warnx(\"%s: setting '%s' to '%s' failed\", __func__,\n\t\t\t type, value);\n\t\t\tca_sslerror(__func__);\n\t\t\tgoto err;\n\t\t}\n\t}\n\tfree(type);\n\tfree(value);\n\treturn (name);", "err:\n\tX509_NAME_free(name);\n\tfree(type);\n\tfree(value);\n\treturn (NULL);\n}", "int\nca_validate_pubkey(struct iked *env, struct iked_static_id *id,\n void *data, size_t len, struct iked_id *out)\n{\n\tBIO\t\t*rawcert = NULL;\n\tRSA\t\t*peerrsa = NULL, *localrsa = NULL;\n\tEC_KEY\t\t*peerec = NULL;\n\tEVP_PKEY\t*peerkey = NULL, *localkey = NULL;\n\tint\t\t ret = -1;\n\tFILE\t\t*fp = NULL;\n\tchar\t\t idstr[IKED_ID_SIZE];\n\tchar\t\t file[PATH_MAX];\n\tstruct iked_id\t idp;", "\tswitch (id->id_type) {\n\tcase IKEV2_ID_IPV4:\n\tcase IKEV2_ID_FQDN:\n\tcase IKEV2_ID_UFQDN:\n\tcase IKEV2_ID_IPV6:\n\t\tbreak;\n\tdefault:\n\t\t/* Some types like ASN1_DN will not be mapped to file names */\n\t\tlog_debug(\"%s: unsupported public key type %s\",\n\t\t __func__, print_map(id->id_type, ikev2_id_map));\n\t\treturn (-1);\n\t}", "\tbzero(&idp, sizeof(idp));\n\tif ((idp.id_buf = ibuf_new(id->id_data, id->id_length)) == NULL)\n\t\tgoto done;", "\tidp.id_type = id->id_type;\n\tidp.id_offset = id->id_offset;\n\tif (ikev2_print_id(&idp, idstr, sizeof(idstr)) == -1)\n\t\tgoto done;", "\tif (len == 0 && data) {\n\t\t/* Data is already an public key */\n\t\tpeerkey = (EVP_PKEY *)data;\n\t}\n\tif (len > 0) {\n\t\tif ((rawcert = BIO_new_mem_buf(data, len)) == NULL)\n\t\t\tgoto done;", "\t\tif ((peerkey = EVP_PKEY_new()) == NULL)\n\t\t\tgoto sslerr;\n\t\tif ((peerrsa = d2i_RSAPublicKey_bio(rawcert, NULL))) {\n\t\t\tif (!EVP_PKEY_set1_RSA(peerkey, peerrsa)) {\n\t\t\t\tgoto sslerr;\n\t\t\t}\n\t\t} else if (BIO_reset(rawcert) == 1 &&\n\t\t (peerec = d2i_EC_PUBKEY_bio(rawcert, NULL))) {\n\t\t\tif (!EVP_PKEY_set1_EC_KEY(peerkey, peerec)) {\n\t\t\t\tgoto sslerr;\n\t\t\t}\n\t\t} else {\n\t\t\tlog_debug(\"%s: unknown key type received\", __func__);\n\t\t\tgoto sslerr;\n\t\t}\n\t}", "\tlc_idtype(idstr);\n\tif (strlcpy(file, IKED_PUBKEY_DIR, sizeof(file)) >= sizeof(file) ||\n\t strlcat(file, idstr, sizeof(file)) >= sizeof(file)) {\n\t\tlog_debug(\"%s: public key id too long %s\", __func__, idstr);\n\t\tgoto done;\n\t}", "\tif ((fp = fopen(file, \"r\")) == NULL) {\n\t\t/* Log to debug when called from ca_validate_cert */\n\t\tlogit(len == 0 ? LOG_DEBUG : LOG_INFO,\n\t\t \"%s: could not open public key %s\", __func__, file);\n\t\tgoto done;\n\t}\n\tlocalkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL);\n\tif (localkey == NULL) {\n\t\t/* reading PKCS #8 failed, try PEM RSA */\n\t\trewind(fp);\n\t\tlocalrsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL);\n\t\tfclose(fp);\n\t\tif (localrsa == NULL)\n\t\t\tgoto sslerr;\n\t\tif ((localkey = EVP_PKEY_new()) == NULL)\n\t\t\tgoto sslerr;\n\t\tif (!EVP_PKEY_set1_RSA(localkey, localrsa))\n\t\t\tgoto sslerr;\n\t} else {\n\t\tfclose(fp);\n\t}\n\tif (localkey == NULL)\n\t\tgoto sslerr;\n", "\tif (peerkey && EVP_PKEY_cmp(peerkey, localkey) != 1) {", "\t\tlog_debug(\"%s: public key does not match %s\", __func__, file);\n\t\tgoto done;\n\t}", "\tlog_debug(\"%s: valid public key in file %s\", __func__, file);", "\tif (out && ca_pubkey_serialize(localkey, out))\n\t\tgoto done;", "\tret = 0;\n sslerr:\n\tif (ret != 0)\n\t\tca_sslerror(__func__);\n done:\n\tibuf_release(idp.id_buf);\n\tif (localkey != NULL)\n\t\tEVP_PKEY_free(localkey);\n\tif (peerrsa != NULL)\n\t\tRSA_free(peerrsa);\n\tif (peerec != NULL)\n\t\tEC_KEY_free(peerec);\n\tif (localrsa != NULL)\n\t\tRSA_free(localrsa);\n\tif (rawcert != NULL) {\n\t\tBIO_free(rawcert);\n\t\tif (peerkey != NULL)\n\t\t\tEVP_PKEY_free(peerkey);\n\t}", "\treturn (ret);\n}", "int\nca_validate_cert(struct iked *env, struct iked_static_id *id,\n void *data, size_t len)\n{\n\tstruct ca_store\t*store = env->sc_priv;\n\tX509_STORE_CTX\t csc;\n\tBIO\t\t*rawcert = NULL;\n\tX509\t\t*cert = NULL;\n\tEVP_PKEY\t*pkey;\n\tint\t\t ret = -1, result, error;\n\tX509_NAME\t*subject;\n\tconst char\t*errstr = \"failed\";", "\tif (len == 0) {\n\t\t/* Data is already an X509 certificate */\n\t\tcert = (X509 *)data;\n\t} else {\n\t\t/* Convert data to X509 certificate */\n\t\tif ((rawcert = BIO_new_mem_buf(data, len)) == NULL)\n\t\t\tgoto done;\n\t\tif ((cert = d2i_X509_bio(rawcert, NULL)) == NULL)\n\t\t\tgoto done;\n\t}", "\t/* Certificate needs a valid subjectName */\n\tif ((subject = X509_get_subject_name(cert)) == NULL) {\n\t\terrstr = \"invalid subject\";\n\t\tgoto done;\n\t}", "\tif (id != NULL) {\n\t\tif ((pkey = X509_get_pubkey(cert)) == NULL) {\n\t\t\terrstr = \"no public key in cert\";\n\t\t\tgoto done;\n\t\t}\n\t\tret = ca_validate_pubkey(env, id, pkey, 0, NULL);\n\t\tEVP_PKEY_free(pkey);\n\t\tif (ret == 0) {\n\t\t\terrstr = \"in public key file, ok\";\n\t\t\tgoto done;\n\t\t}", "\t\tswitch (id->id_type) {\n\t\tcase IKEV2_ID_ASN1_DN:\n\t\t\tif (ca_x509_subject_cmp(cert, id) < 0) {\n\t\t\t\terrstr = \"ASN1_DN identifier mismatch\";\n\t\t\t\tgoto done;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (ca_x509_subjectaltname_cmp(cert, id) != 0) {\n\t\t\t\terrstr = \"invalid subjectAltName extension\";\n\t\t\t\tgoto done;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}", "\tbzero(&csc, sizeof(csc));\n\tX509_STORE_CTX_init(&csc, store->ca_cas, cert, NULL);\n\tif (store->ca_cas->param->flags & X509_V_FLAG_CRL_CHECK) {\n\t\tX509_STORE_CTX_set_flags(&csc, X509_V_FLAG_CRL_CHECK);\n\t\tX509_STORE_CTX_set_flags(&csc, X509_V_FLAG_CRL_CHECK_ALL);\n\t}", "\tresult = X509_verify_cert(&csc);\n\terror = csc.error;\n\tX509_STORE_CTX_cleanup(&csc);\n\tif (error != 0) {\n\t\terrstr = X509_verify_cert_error_string(error);\n\t\tgoto done;\n\t}", "\tif (!result) {\n\t\t/* XXX should we accept self-signed certificates? */\n\t\terrstr = \"rejecting self-signed certificate\";\n\t\tgoto done;\n\t}", "\t/* Success */\n\tret = 0;\n\terrstr = \"ok\";", " done:\n\tif (cert != NULL)\n\t\tlog_debug(\"%s: %s %.100s\", __func__, cert->name, errstr);", "\tif (rawcert != NULL) {\n\t\tBIO_free(rawcert);\n\t\tif (cert != NULL)\n\t\t\tX509_free(cert);\n\t}", "\treturn (ret);\n}", "/* check if subject from cert matches the id */\nint\nca_x509_subject_cmp(X509 *cert, struct iked_static_id *id)\n{\n\tX509_NAME\t*subject, *idname = NULL;\n\tconst uint8_t\t*idptr;\n\tsize_t\t\t idlen;\n\tint\t\t ret = -1;", "\tif (id->id_type != IKEV2_ID_ASN1_DN)\n\t\treturn (-1);\n\tif ((subject = X509_get_subject_name(cert)) == NULL)\n\t\treturn (-1);\n\tif (id->id_length <= id->id_offset)\n\t\treturn (-1);\n\tidlen = id->id_length - id->id_offset;\n\tidptr = id->id_data + id->id_offset;\n\tif ((idname = d2i_X509_NAME(NULL, &idptr, idlen)) == NULL)\n\t\treturn (-1);\n\tif (X509_NAME_cmp(subject, idname) == 0)\n\t\tret = 0;\n\tX509_NAME_free(idname);\n\treturn (ret);\n}", "#define MODE_ALT_LOG\t1\n#define MODE_ALT_GET\t2\n#define MODE_ALT_CMP\t3\nint\nca_x509_subjectaltname_do(X509 *cert, int mode, const char *logmsg,\n struct iked_static_id *id, struct iked_id *retid)\n{\n\tSTACK_OF(GENERAL_NAME) *stack = NULL;\n\tGENERAL_NAME *entry;\n\tASN1_STRING *cstr;\n\tchar idstr[IKED_ID_SIZE];\n\tint idx, ret, i, type, len;\n\tuint8_t *data;", "\tret = -1;\n\tidx = -1;\n\twhile ((stack = X509_get_ext_d2i(cert, NID_subject_alt_name,\n\t NULL, &idx)) != NULL) {\n\t\tfor (i = 0; i < sk_GENERAL_NAME_num(stack); i++) {\n\t\t\tentry = sk_GENERAL_NAME_value(stack, i);\n\t\t\tswitch (entry->type) {\n\t\t\tcase GEN_DNS:\n\t\t\t\tcstr = entry->d.dNSName;\n\t\t\t\tif (ASN1_STRING_type(cstr) != V_ASN1_IA5STRING)\n\t\t\t\t\tcontinue;\n\t\t\t\ttype = IKEV2_ID_FQDN;\n\t\t\t\tbreak;\n\t\t\tcase GEN_EMAIL:\n\t\t\t\tcstr = entry->d.rfc822Name;\n\t\t\t\tif (ASN1_STRING_type(cstr) != V_ASN1_IA5STRING)\n\t\t\t\t\tcontinue;\n\t\t\t\ttype = IKEV2_ID_UFQDN;\n\t\t\t\tbreak;\n\t\t\tcase GEN_IPADD:\n\t\t\t\tcstr = entry->d.iPAddress;\n\t\t\t\tswitch (ASN1_STRING_length(cstr)) {\n\t\t\t\tcase 4:\n\t\t\t\t\ttype = IKEV2_ID_IPV4;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 16:\n\t\t\t\t\ttype = IKEV2_ID_IPV6;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlog_debug(\"%s: invalid subjectAltName\"\n\t\t\t\t\t \" IP address\", __func__);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlen = ASN1_STRING_length(cstr);\n\t\t\tdata = ASN1_STRING_data(cstr);\n\t\t\tif (mode == MODE_ALT_LOG) {\n\t\t\t\tstruct iked_id sanid;", "\t\t\t\tbzero(&sanid, sizeof(sanid));\n\t\t\t\tsanid.id_offset = 0;\n\t\t\t\tsanid.id_type = type;\n\t\t\t\tif ((sanid.id_buf = ibuf_new(data, len))\n\t\t\t\t == NULL) {\n\t\t\t\t\tlog_debug(\"%s: failed to get id buffer\",\n\t\t\t\t\t __func__);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tikev2_print_id(&sanid, idstr, sizeof(idstr));\n\t\t\t\tlog_info(\"%s: altname: %s\", logmsg, idstr);\n\t\t\t\tibuf_release(sanid.id_buf);\n\t\t\t\tsanid.id_buf = NULL;\n\t\t\t}\n\t\t\t/* Compare length and data */\n\t\t\tif (mode == MODE_ALT_CMP) {\n\t\t\t\tif (type == id->id_type &&\n\t\t\t\t (len == (id->id_length - id->id_offset)) &&\n\t\t\t\t (memcmp(id->id_data + id->id_offset,\n\t\t\t\t data, len)) == 0) {\n\t\t\t\t\tret = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t/* Get first ID */\n\t\t\tif (mode == MODE_ALT_GET) {\n\t\t\t\tibuf_release(retid->id_buf);\n\t\t\t\tif ((retid->id_buf = ibuf_new(data, len)) == NULL) {\n\t\t\t\t\tlog_debug(\"%s: failed to get id buffer\",\n\t\t\t\t\t __func__);\n\t\t\t\t\tret = -2;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tretid->id_offset = 0;\n\t\t\t\tikev2_print_id(retid, idstr, sizeof(idstr));\n\t\t\t\tlog_debug(\"%s: %s\", __func__, idstr);\n\t\t\t\tret = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tsk_GENERAL_NAME_pop_free(stack, GENERAL_NAME_free);\n\t\tif (ret != -1)\n\t\t\tbreak;\n\t}\n\tif (idx == -1)\n\t\tlog_debug(\"%s: did not find subjectAltName in certificate\",\n\t\t __func__);\n\treturn ret;\n}", "int\nca_x509_subjectaltname_log(X509 *cert, const char *logmsg)\n{\n\treturn ca_x509_subjectaltname_do(cert, MODE_ALT_LOG, logmsg, NULL, NULL);\n}", "int\nca_x509_subjectaltname_cmp(X509 *cert, struct iked_static_id *id)\n{\n\treturn ca_x509_subjectaltname_do(cert, MODE_ALT_CMP, NULL, id, NULL);\n}", "int\nca_x509_subjectaltname_get(X509 *cert, struct iked_id *retid)\n{\n\treturn ca_x509_subjectaltname_do(cert, MODE_ALT_GET, NULL, NULL, retid);\n}", "void\nca_sslinit(void)\n{\n\tOpenSSL_add_all_algorithms();\n\tERR_load_crypto_strings();", "\t/* Init hardware crypto engines. */\n\tENGINE_load_builtin_engines();\n\tENGINE_register_all_complete();\n}", "void\nca_sslerror(const char *caller)\n{\n\tunsigned long\t error;", "\twhile ((error = ERR_get_error()) != 0)\n\t\tlog_warnx(\"%s: %s: %.100s\", __func__, caller,\n\t\t ERR_error_string(error, NULL));\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1424], "buggy_code_start_loc": [1], "filenames": ["sbin/iked/ca.c"], "fixing_code_end_loc": [1424], "fixing_code_start_loc": [1], "message": "iked in OpenIKED, as used in OpenBSD through 6.7, allows authentication bypass because ca.c has the wrong logic for checking whether a public key matches.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:openbsd:openbsd:*:*:*:*:*:*:*:*", "matchCriteriaId": "9A2FECEE-1724-4D96-8165-3AA952EDD4DC", "versionEndExcluding": null, "versionEndIncluding": "6.7", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "iked in OpenIKED, as used in OpenBSD through 6.7, allows authentication bypass because ca.c has the wrong logic for checking whether a public key matches."}, {"lang": "es", "value": "iked en OpenIKED, como es usado en OpenBSD versiones hasta 6.7, permite omitir una autenticaci\u00f3n porque el archivo ca.c presenta una l\u00f3gica equivocada para comprobar si una clave p\u00fablica coincide"}], "evaluatorComment": null, "id": "CVE-2020-16088", "lastModified": "2022-01-04T16:32:52.703", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-07-28T12:15:12.067", "references": [{"source": "cve@mitre.org", "tags": ["Exploit", "Vendor Advisory"], "url": "https://ftp.openbsd.org/pub/OpenBSD/patches/6.7/common/014_iked.patch.sig"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/openbsd/src/commit/7afb2d41c6d373cf965285840b85c45011357115"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/xcllnt/openiked/commits/master"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://www.openiked.org/security.html"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-287"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/openbsd/src/commit/7afb2d41c6d373cf965285840b85c45011357115"}, "type": "CWE-287"}
322
Determine whether the {function_name} code is vulnerable or not.
[ "1.3.1 (2019-08-27)", "------------------", "Bugfixes\n~~~~~~~~\n", "- Waitress won't accidentally throw away part of the path if it starts with a\n double slash (``GET //testing/whatever HTTP/1.0``). WSGI applications will\n now receive a ``PATH_INFO`` in the environment that contains\n ``//testing/whatever`` as required. See\n https://github.com/Pylons/waitress/issues/260 and\n https://github.com/Pylons/waitress/pull/261", "", "", "", "1.3.0 (2019-04-22)\n------------------", "", "Deprecations\n~~~~~~~~~~~~", "", "- The ``send_bytes`` adjustment now defaults to ``1`` and is deprecated\n pending removal in a future release.\n and https://github.com/Pylons/waitress/pull/246", "", "Features\n~~~~~~~~", "", "- Add a new ``outbuf_high_watermark`` adjustment which is used to apply\n backpressure on the ``app_iter`` to avoid letting it spin faster than data\n can be written to the socket. This stabilizes responses that iterate quickly\n with a lot of data.\n See https://github.com/Pylons/waitress/pull/242", "", "- Stop early and close the ``app_iter`` when attempting to write to a closed\n socket due to a client disconnect. This should notify a long-lived streaming\n response when a client hangs up.\n See https://github.com/Pylons/waitress/pull/238\n and https://github.com/Pylons/waitress/pull/240\n and https://github.com/Pylons/waitress/pull/241", "", "- Adjust the flush to output ``SO_SNDBUF`` bytes instead of whatever was\n set in the ``send_bytes`` adjustment. ``send_bytes`` now only controls how\n much waitress will buffer internally before flushing to the kernel, whereas\n previously it used to also throttle how much data was sent to the kernel.\n This change enables a streaming ``app_iter`` containing small chunks to\n still be flushed efficiently.\n See https://github.com/Pylons/waitress/pull/246", "", "Bugfixes\n~~~~~~~~", "", "- Upon receiving a request that does not include HTTP/1.0 or HTTP/1.1 we will\n no longer set the version to the string value \"None\". See\n https://github.com/Pylons/waitress/pull/252 and\n https://github.com/Pylons/waitress/issues/110", "", "- When a client closes a socket unexpectedly there was potential for memory\n leaks in which data was written to the buffers after they were closed,\n causing them to reopen.\n See https://github.com/Pylons/waitress/pull/239", "", "- Fix the queue depth warnings to only show when all threads are busy.\n See https://github.com/Pylons/waitress/pull/243\n and https://github.com/Pylons/waitress/pull/247", "", "- Trigger the ``app_iter`` to close as part of shutdown. This will only be\n noticeable for users of the internal server api. In more typical operations\n the server will die before benefiting from these changes.\n See https://github.com/Pylons/waitress/pull/245", "", "- Fix a bug in which a streaming ``app_iter`` may never cleanup data that has\n already been sent. This would cause buffers in waitress to grow without\n bounds. These buffers now properly rotate and release their data.\n See https://github.com/Pylons/waitress/pull/242", "- Fix a bug in which non-seekable subclasses of ``io.IOBase`` would trigger\n an exception when passed to the ``wsgi.file_wrapper`` callback.\n See https://github.com/Pylons/waitress/pull/249" ]
[ 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "1.4.0 (2019-12-20)", "------------------", "Bugfixes\n~~~~~~~~\n", "- Waitress used to slam the door shut on HTTP pipelined requests without\n setting the ``Connection: close`` header as appropriate in the response. This\n is of course not very friendly. Waitress now explicitly sets the header when\n responding with an internally generated error such as 400 Bad Request or 500\n Internal Server Error to notify the remote client that it will be closing the\n connection after the response is sent.", "", "- Waitress no longer allows any spaces to exist between the header field-name\n and the colon. While waitress did not strip the space and thereby was not\n vulnerable to any potential header field-name confusion, it should have sent\n back a 400 Bad Request. See https://github.com/Pylons/waitress/issues/273", "", "Security Fixes\n~~~~~~~~~~~~~~", "", "- Waitress implemented a \"MAY\" part of the RFC7230\n (https://tools.ietf.org/html/rfc7230#section-3.5) which states:", "", " Although the line terminator for the start-line and header fields is\n the sequence CRLF, a recipient MAY recognize a single LF as a line\n terminator and ignore any preceding CR.", "", " Unfortunately if a front-end server does not parse header fields with an LF\n the same way as it does those with a CRLF it can lead to the front-end and\n the back-end server parsing the same HTTP message in two different ways. This\n can lead to a potential for HTTP request smuggling/splitting whereby Waitress\n may see two requests while the front-end server only sees a single HTTP\n message.", "", " For more information I can highly recommend the blog post by ZeddYu Lu\n https://blog.zeddyu.info/2019/12/08/HTTP-Smuggling-en/", "", "- Waitress used to treat LF the same as CRLF in ``Transfer-Encoding: chunked``\n requests, while the maintainer doesn't believe this could lead to a security\n issue, this is no longer supported and all chunks are now validated to be\n properly framed with CRLF as required by RFC7230.", "", "- Waitress now validates that the ``Transfer-Encoding`` header contains only\n transfer codes that it is able to decode. At the moment that includes the\n only valid header value being ``chunked``.", "", " That means that if the following header is sent:", "", " ``Transfer-Encoding: gzip, chunked``", "", " Waitress will send back a 501 Not Implemented with an error message stating\n as such, as while Waitress supports ``chunked`` encoding it does not support\n ``gzip`` and it is unable to pass that to the underlying WSGI environment\n correctly.", "", " Waitress DOES NOT implement support for ``Transfer-Encoding: identity``\n eventhough ``identity`` was valid in RFC2616, it was removed in RFC7230.\n Please update your clients to remove the ``Transfer-Encoding`` header if the\n only transfer coding is ``identity`` or update your client to use\n ``Transfer-Encoding: chunked`` instead of ``Transfer-Encoding: identity,\n chunked``.", "", "- While validating the ``Transfer-Encoding`` header, Waitress now properly\n handles line-folded ``Transfer-Encoding`` headers or those that contain\n multiple comma seperated values. This closes a potential issue where a\n front-end server may treat the request as being a chunked request (and thus\n ignoring the Content-Length) and Waitress using the Content-Length as it was\n looking for the single value ``chunked`` and did not support comma seperated\n values.", "", "- Waitress used to explicitly set the Content-Length header to 0 if it was\n unable to parse it as an integer (for example if the Content-Length header\n was sent twice (and thus folded together), or was invalid) thereby allowing\n for a potential request to be split and treated as two requests by HTTP\n pipelining support in Waitress. If Waitress is now unable to parse the\n Content-Length header, a 400 Bad Request is sent back to the client." ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "", "1.2.1 (2019-01-25)\n------------------", "Bugfixes\n~~~~~~~~", "- When given an IPv6 address in ``X-Forwarded-For`` or ``Forwarded for=``\n waitress was placing the IP address in ``REMOTE_ADDR`` with brackets:\n ``[2001:db8::0]``, this does not match the requirements in the CGI spec which\n ``REMOTE_ADDR`` was lifted from. Waitress will now place the bare IPv6\n address in ``REMOTE_ADDR``: ``2001:db8::0``. See\n https://github.com/Pylons/waitress/pull/232 and\n https://github.com/Pylons/waitress/issues/230", "1.2.0 (2019-01-15)\n------------------", "No changes since the last beta release. Enjoy Waitress!", "1.2.0b3 (2019-01-07)\n--------------------", "Bugfixes\n~~~~~~~~", "- Modified ``clear_untrusted_proxy_headers`` to be usable without a\n ``trusted_proxy``.\n https://github.com/Pylons/waitress/pull/228", "- Modified ``trusted_proxy_count`` to error when used without a\n ``trusted_proxy``.\n https://github.com/Pylons/waitress/pull/228", "1.2.0b2 (2019-02-02)\n--------------------", "Bugfixes\n~~~~~~~~", "- Fixed logic to no longer warn on writes where the output is required to have\n a body but there may not be any data to be written. Solves issue posted on\n the Pylons Project mailing list with 1.2.0b1.", "1.2.0b1 (2018-12-31)\n--------------------", "Happy New Year!", "Features\n~~~~~~~~", "- Setting the ``trusted_proxy`` setting to ``'*'`` (wildcard) will allow all\n upstreams to be considered trusted proxies, thereby allowing services behind\n Cloudflare/ELBs to function correctly whereby there may not be a singular IP\n address that requests are received from.", " Using this setting is potentially dangerous if your server is also available\n from anywhere on the internet, and further protections should be used to lock\n down access to Waitress. See https://github.com/Pylons/waitress/pull/224", "- Waitress has increased its support of the X-Forwarded-* headers and includes\n Forwarded (RFC7239) support. This may be used to allow proxy servers to\n influence the WSGI environment. See\n https://github.com/Pylons/waitress/pull/209", " This also provides a new security feature when using Waitress behind a proxy\n in that it is possible to remove untrusted proxy headers thereby making sure\n that downstream WSGI applications don't accidentally use those proxy headers\n to make security decisions.", " The documentation has more information, see the following new arguments:", " - trusted_proxy_count\n - trusted_proxy_headers\n - clear_untrusted_proxy_headers\n - log_untrusted_proxy_headers (useful for debugging)", " Be aware that the defaults for these are currently backwards compatible with\n older versions of Waitress, this will change in a future release of waitress.\n If you expect to need this behaviour please explicitly set these variables in\n your configuration, or pin this version of waitress.", " Documentation:\n https://docs.pylonsproject.org/projects/waitress/en/latest/reverse-proxy.html", "- Waitress can now accept a list of sockets that are already pre-bound rather\n than creating its own to allow for socket activation. Support for init\n systems/other systems that create said activated sockets is not included. See\n https://github.com/Pylons/waitress/pull/215", "- Server header can be omitted by specifying ``ident=None`` or ``ident=''``.\n See https://github.com/Pylons/waitress/pull/187", "Bugfixes\n~~~~~~~~", "- Waitress will no longer send Transfer-Encoding or Content-Length for 1xx,\n 204, or 304 responses, and will completely ignore any message body sent by\n the WSGI application, making sure to follow the HTTP standard. See\n https://github.com/Pylons/waitress/pull/166,\n https://github.com/Pylons/waitress/issues/165,\n https://github.com/Pylons/waitress/issues/152, and\n https://github.com/Pylons/waitress/pull/202", "Compatibility\n~~~~~~~~~~~~~", "- Waitress has now \"vendored\" asyncore into itself as ``waitress.wasyncore``.\n This is to cope with the eventuality that asyncore will be removed from\n the Python standard library in 3.8 or so.", "Documentation\n~~~~~~~~~~~~~", "- Bring in documentation of paste.translogger from Pyramid. Reorganize and\n clean up documentation. See\n https://github.com/Pylons/waitress/pull/205\n https://github.com/Pylons/waitress/pull/70\n https://github.com/Pylons/waitress/pull/206", "1.1.0 (2017-10-10)\n------------------", "Features\n~~~~~~~~", "- Waitress now has a __main__ and thus may be called with ``python -mwaitress``", "Bugfixes\n~~~~~~~~", "- Waitress no longer allows lowercase HTTP verbs. This change was made to fall\n in line with most HTTP servers. See https://github.com/Pylons/waitress/pull/170", "- When receiving non-ascii bytes in the request URL, waitress will no longer\n abruptly close the connection, instead returning a 400 Bad Request. See\n https://github.com/Pylons/waitress/pull/162 and\n https://github.com/Pylons/waitress/issues/64", "1.0.2 (2017-02-04)\n------------------", "Features\n~~~~~~~~", "- Python 3.6 is now officially supported in Waitress", "Bugfixes\n~~~~~~~~", "- Add a work-around for libc issue on Linux not following the documented\n standards. If getnameinfo() fails because of DNS not being available it\n should return the IP address instead of the reverse DNS entry, however\n instead getnameinfo() raises. We catch this, and ask getnameinfo()\n for the same information again, explicitly asking for IP address instead of\n reverse DNS hostname. See https://github.com/Pylons/waitress/issues/149 and\n https://github.com/Pylons/waitress/pull/153", "1.0.1 (2016-10-22)\n------------------", "Bugfixes\n~~~~~~~~", "- IPv6 support on Windows was broken due to missing constants in the socket\n module. This has been resolved by setting the constants on Windows if they\n are missing. See https://github.com/Pylons/waitress/issues/138", "- A ValueError was raised on Windows when passing a string for the port, on\n Windows in Python 2 using service names instead of port numbers doesn't work\n with `getaddrinfo`. This has been resolved by attempting to convert the port\n number to an integer, if that fails a ValueError will be raised. See\n https://github.com/Pylons/waitress/issues/139", "\n1.0.0 (2016-08-31)\n------------------", "Bugfixes\n~~~~~~~~", "- Removed `AI_ADDRCONFIG` from the call to `getaddrinfo`, this resolves an\n issue whereby `getaddrinfo` wouldn't return any addresses to `bind` to on\n hosts where there is no internet connection but localhost is requested to be\n bound to. See https://github.com/Pylons/waitress/issues/131 for more\n information.", "Deprecations\n~~~~~~~~~~~~", "- Python 2.6 is no longer supported.", "Features\n~~~~~~~~", "- IPv6 support", "- Waitress is now able to listen on multiple sockets, including IPv4 and IPv6.\n Instead of passing in a host/port combination you now provide waitress with a\n space delineated list, and it will create as many sockets as required.", " .. code-block:: python", "\tfrom waitress import serve\n\tserve(wsgiapp, listen='0.0.0.0:8080 [::]:9090 *:6543')", "Security\n~~~~~~~~", "- Waitress will now drop HTTP headers that contain an underscore in the key\n when received from a client. This is to stop any possible underscore/dash\n conflation that may lead to security issues. See\n https://github.com/Pylons/waitress/pull/80 and\n https://www.djangoproject.com/weblog/2015/jan/13/security/", "0.9.0 (2016-04-15)\n------------------", "Deprecations\n~~~~~~~~~~~~", "- Python 3.2 is no longer supported by Waitress.", "- Python 2.6 will no longer be supported by Waitress in future releases.", "Security/Protections\n~~~~~~~~~~~~~~~~~~~~", "- Building on the changes made in pull request 117, add in checking for line\n feed/carriage return HTTP Response Splitting in the status line, as well as\n the key of a header. See https://github.com/Pylons/waitress/pull/124 and\n https://github.com/Pylons/waitress/issues/122.", "- Waitress will no longer accept headers or status lines with\n newline/carriage returns in them, thereby disallowing HTTP Response\n Splitting. See https://github.com/Pylons/waitress/issues/117 for\n more information, as well as\n https://www.owasp.org/index.php/HTTP_Response_Splitting.", "Bugfixes\n~~~~~~~~", "- FileBasedBuffer and more important ReadOnlyFileBasedBuffer no longer report\n False when tested with bool(), instead always returning True, and becoming\n more iterator like.\n See: https://github.com/Pylons/waitress/pull/82 and\n https://github.com/Pylons/waitress/issues/76", "- Call prune() on the output buffer at the end of a request so that it doesn't\n continue to grow without bounds. See\n https://github.com/Pylons/waitress/issues/111 for more information.", "0.8.10 (2015-09-02)\n-------------------", "- Add support for Python 3.4, 3.5b2, and PyPy3.", "- Use a nonglobal asyncore socket map by default, trying to prevent conflicts\n with apps and libs that use the asyncore global socket map ala\n https://github.com/Pylons/waitress/issues/63. You can get the old\n use-global-socket-map behavior back by passing ``asyncore.socket_map`` to the\n ``create_server`` function as the ``map`` argument.", "- Waitress violated PEP 3333 with respect to reraising an exception when\n ``start_response`` was called with an ``exc_info`` argument. It would\n reraise the exception even if no data had been sent to the client. It now\n only reraises the exception if data has actually been sent to the client.\n See https://github.com/Pylons/waitress/pull/52 and\n https://github.com/Pylons/waitress/issues/51", "- Add a ``docs`` section to tox.ini that, when run, ensures docs can be built.", "- If an ``application`` value of ``None`` is supplied to the ``create_server``\n constructor function, a ValueError is now raised eagerly instead of an error\n occuring during runtime. See https://github.com/Pylons/waitress/pull/60", "- Fix parsing of multi-line (folded) headers.\n See https://github.com/Pylons/waitress/issues/53 and\n https://github.com/Pylons/waitress/pull/90", "- Switch from the low level Python thread/_thread module to the threading\n module.", "- Improved exception information should module import go awry.", "0.8.9 (2014-05-16)\n------------------", "- Fix tests under Windows. NB: to run tests under Windows, you cannot run\n \"setup.py test\" or \"setup.py nosetests\". Instead you must run ``python.exe\n -c \"import nose; nose.main()\"``. If you try to run the tests using the\n normal method under Windows, each subprocess created by the test suite will\n attempt to run the test suite again. See\n https://github.com/nose-devs/nose/issues/407 for more information.", "- Give the WSGI app_iter generated when ``wsgi.file_wrapper`` is used\n (ReadOnlyFileBasedBuffer) a ``close`` method. Do not call ``close`` on an\n instance of such a class when it's used as a WSGI app_iter, however. This is\n part of a fix which prevents a leakage of file descriptors; the other part of\n the fix was in WebOb\n (https://github.com/Pylons/webob/commit/951a41ce57bd853947f842028bccb500bd5237da).", "- Allow trusted proxies to override ``wsgi.url_scheme`` via a request header,\n ``X_FORWARDED_PROTO``. Allows proxies which serve mixed HTTP / HTTPS\n requests to control signal which are served as HTTPS. See\n https://github.com/Pylons/waitress/pull/42.", "0.8.8 (2013-11-30)\n------------------", "- Fix some cases where the creation of extremely large output buffers (greater\n than 2GB, suspected to be buffers added via ``wsgi.file_wrapper``) might\n cause an OverflowError on Python 2. See\n https://github.com/Pylons/waitress/issues/47.", "- When the ``url_prefix`` adjustment starts with more than one slash, all\n slashes except one will be stripped from its beginning. This differs from\n older behavior where more than one leading slash would be preserved in\n ``url_prefix``.", "- If a client somehow manages to send an empty path, we no longer convert the\n empty path to a single slash in ``PATH_INFO``. Instead, the path remains\n empty. According to RFC 2616 section \"5.1.2 Request-URI\", the scenario of a\n client sending an empty path is actually not possible because the request URI\n portion cannot be empty.", "- If the ``url_prefix`` adjustment matches the request path exactly, we now\n compute ``SCRIPT_NAME`` and ``PATH_INFO`` properly. Previously, if the\n ``url_prefix`` was ``/foo`` and the path received from a client was ``/foo``,\n we would set *both* ``SCRIPT_NAME`` and ``PATH_INFO`` to ``/foo``. This was\n incorrect. Now in such a case we set ``PATH_INFO`` to the empty string and\n we set ``SCRIPT_NAME`` to ``/foo``. Note that the change we made has no\n effect on paths that do not match the ``url_prefix`` exactly (such as\n ``/foo/bar``); these continue to operate as they did. See\n https://github.com/Pylons/waitress/issues/46", "- Preserve header ordering of headers with the same name as per RFC 2616. See\n https://github.com/Pylons/waitress/pull/44", "- When waitress receives a ``Transfer-Encoding: chunked`` request, we no longer\n send the ``TRANSFER_ENCODING`` nor the ``HTTP_TRANSFER_ENCODING`` value to\n the application in the environment. Instead, we pop this header. Since we\n cope with chunked requests by buffering the data in the server, we also know\n when a chunked request has ended, and therefore we know the content length.\n We set the content-length header in the environment, such that applications\n effectively never know the original request was a T-E: chunked request; it\n will appear to them as if the request is a non-chunked request with an\n accurate content-length.", "- Cope with the fact that the ``Transfer-Encoding`` value is case-insensitive.", "- When the ``--unix-socket-perms`` option was used as an argument to\n ``waitress-serve``, a ``TypeError`` would be raised. See\n https://github.com/Pylons/waitress/issues/50.", "0.8.7 (2013-08-29)\n------------------", "- The HTTP version of the response returned by waitress when it catches an\n exception will now match the HTTP request version.", "- Fix: CONNECTION header will be HTTP_CONNECTION and not CONNECTION_TYPE\n (see https://github.com/Pylons/waitress/issues/13)", "0.8.6 (2013-08-12)\n------------------", "- Do alternate type of checking for UNIX socket support, instead of checking\n for platform == windows.", "- Functional tests now use multiprocessing module instead of subprocess module,\n speeding up test suite and making concurrent execution more reliable.", "- Runner now appends the current working directory to ``sys.path`` to support\n running WSGI applications from a directory (i.e., not installed in a\n virtualenv).", "- Add a ``url_prefix`` adjustment setting. You can use it by passing\n ``script_name='/foo'`` to ``waitress.serve`` or you can use it in a\n ``PasteDeploy`` ini file as ``script_name = /foo``. This will cause the WSGI\n ``SCRIPT_NAME`` value to be the value passed minus any trailing slashes you\n add, and it will cause the ``PATH_INFO`` of any request which is prefixed\n with this value to be stripped of the prefix. You can use this instead of\n PasteDeploy's ``prefixmiddleware`` to always prefix the path.", "0.8.5 (2013-05-27)\n------------------", "- Fix runner multisegment imports in some Python 2 revisions (see\n https://github.com/Pylons/waitress/pull/34).", "- For compatibility, WSGIServer is now an alias of TcpWSGIServer. The\n signature of BaseWSGIServer is now compatible with WSGIServer pre-0.8.4.", "0.8.4 (2013-05-24)\n------------------", "- Add a command-line runner called ``waitress-serve`` to allow Waitress\n to run WSGI applications without any addional machinery. This is\n essentially a thin wrapper around the ``waitress.serve()`` function.", "- Allow parallel testing (e.g., under ``detox`` or ``nosetests --processes``)\n using PID-dependent port / socket for functest servers.", "- Fix integer overflow errors on large buffers. Thanks to Marcin Kuzminski\n for the patch. See: https://github.com/Pylons/waitress/issues/22", "- Add support for listening on Unix domain sockets.", "0.8.3 (2013-04-28)\n------------------", "Features\n~~~~~~~~", "- Add an ``asyncore_loop_timeout`` adjustment value, which controls the\n ``timeout`` value passed to ``asyncore.loop``; defaults to 1.", "Bug Fixes\n~~~~~~~~~", "- The default asyncore loop timeout is now 1 second. This prevents slow\n shutdown on Windows. See https://github.com/Pylons/waitress/issues/6 . This\n shouldn't matter to anyone in particular, but it can be changed via the\n ``asyncore_loop_timeout`` adjustment (it used to previously default to 30\n seconds).", "- Don't complain if there's a response to a HEAD request that contains a\n Content-Length > 0. See https://github.com/Pylons/waitress/pull/7.", "- Fix bug in HTTP Expect/Continue support. See\n https://github.com/Pylons/waitress/issues/9 .", "\n0.8.2 (2012-11-14)\n------------------", "Bug Fixes\n~~~~~~~~~", "- https://corte.si/posts/code/pathod/pythonservers/index.html pointed out that\n sending a bad header resulted in an exception leading to a 500 response\n instead of the more proper 400 response without an exception.", "- Fix a race condition in the test suite.", "- Allow \"ident\" to be used as a keyword to ``serve()`` as per docs.", "- Add py33 to tox.ini.", "0.8.1 (2012-02-13)\n------------------", "Bug Fixes\n~~~~~~~~~", "- A brown-bag bug prevented request concurrency. A slow request would block\n subsequent the responses of subsequent requests until the slow request's\n response was fully generated. This was due to a \"task lock\" being declared\n as a class attribute rather than as an instance attribute on HTTPChannel.\n Also took the opportunity to move another lock named \"outbuf lock\" to the\n channel instance rather than the class. See\n https://github.com/Pylons/waitress/pull/1 .", "0.8 (2012-01-31)\n----------------", "Features\n~~~~~~~~", "- Support the WSGI ``wsgi.file_wrapper`` protocol as per\n https://www.python.org/dev/peps/pep-0333/#optional-platform-specific-file-handling.\n Here's a usage example::", " import os", " here = os.path.dirname(os.path.abspath(__file__))", " def myapp(environ, start_response):\n f = open(os.path.join(here, 'myphoto.jpg'), 'rb')\n headers = [('Content-Type', 'image/jpeg')]\n start_response(\n '200 OK',\n headers\n )\n return environ['wsgi.file_wrapper'](f, 32768)", " The signature of the file wrapper constructor is ``(filelike_object,\n block_size)``. Both arguments must be passed as positional (not keyword)\n arguments. The result of creating a file wrapper should be **returned** as\n the ``app_iter`` from a WSGI application.", " The object passed as ``filelike_object`` to the wrapper must be a file-like\n object which supports *at least* the ``read()`` method, and the ``read()``\n method must support an optional size hint argument. It *should* support\n the ``seek()`` and ``tell()`` methods. If it does not, normal iteration\n over the filelike object using the provided block_size is used (and copying\n is done, negating any benefit of the file wrapper). It *should* support a\n ``close()`` method.", " The specified ``block_size`` argument to the file wrapper constructor will\n be used only when the ``filelike_object`` doesn't support ``seek`` and/or\n ``tell`` methods. Waitress needs to use normal iteration to serve the file\n in this degenerate case (as per the WSGI spec), and this block size will be\n used as the iteration chunk size. The ``block_size`` argument is optional;\n if it is not passed, a default value``32768`` is used.", " Waitress will set a ``Content-Length`` header on the behalf of an\n application when a file wrapper with a sufficiently filelike object is used\n if the application hasn't already set one.", " The machinery which handles a file wrapper currently doesn't do anything\n particularly special using fancy system calls (it doesn't use ``sendfile``\n for example); using it currently just prevents the system from needing to\n copy data to a temporary buffer in order to send it to the client. No\n copying of data is done when a WSGI app returns a file wrapper that wraps a\n sufficiently filelike object. It may do something fancier in the future.", "0.7 (2012-01-11)\n----------------", "Features\n~~~~~~~~", "- Default ``send_bytes`` value is now 18000 instead of 9000. The larger\n default value prevents asyncore from needing to execute select so many\n times to serve large files, speeding up file serving by about 15%-20% or\n so. This is probably only an optimization for LAN communications, and\n could slow things down across a WAN (due to higher TCP overhead), but we're\n likely to be behind a reverse proxy on a LAN anyway if in production.", "- Added an (undocumented) profiling feature to the ``serve()`` command.", "0.6.1 (2012-01-08)\n------------------", "Bug Fixes\n~~~~~~~~~", "- Remove performance-sapping call to ``pull_trigger`` in the channel's\n ``write_soon`` method added mistakenly in 0.6.", "0.6 (2012-01-07)\n----------------", "Bug Fixes\n~~~~~~~~~", "- A logic error prevented the internal outbuf buffer of a channel from being\n flushed when the client could not accept the entire contents of the output\n buffer in a single succession of socket.send calls when the channel was in\n a \"pending close\" state. The socket in such a case would be closed\n prematurely, sometimes resulting in partially delivered content. This was\n discovered by a user using waitress behind an Nginx reverse proxy, which\n apparently is not always ready to receive data. The symptom was that he\n received \"half\" of a large CSS file (110K) while serving content via\n waitress behind the proxy.", "0.5 (2012-01-03)\n----------------", "Bug Fixes\n~~~~~~~~~", "- Fix PATH_INFO encoding/decoding on Python 3 (as per PEP 3333, tunnel\n bytes-in-unicode-as-latin-1-after-unquoting).", "0.4 (2012-01-02)\n----------------", "Features\n~~~~~~~~", "- Added \"design\" document to docs.", "Bug Fixes\n~~~~~~~~~", "- Set default ``connection_limit`` back to 100 for benefit of maximal\n platform compatibility.", "- Normalize setting of ``last_activity`` during send.", "- Minor resource cleanups during tests.", "- Channel timeout cleanup was broken.", "0.3 (2012-01-02)\n----------------", "Features\n~~~~~~~~", "- Dont hang a thread up trying to send data to slow clients.", "- Use self.logger to log socket errors instead of self.log_info (normalize).", "- Remove pointless handle_error method from channel.", "- Queue requests instead of tasks in a channel.", "Bug Fixes\n~~~~~~~~~", "- Expect: 100-continue responses were broken.", "\n0.2 (2011-12-31)\n----------------", "Bug Fixes\n~~~~~~~~~", "- Set up logging by calling logging.basicConfig() when ``serve`` is called\n (show tracebacks and other warnings to console by default).", "- Disallow WSGI applications to set \"hop-by-hop\" headers (Connection,\n Transfer-Encoding, etc).", "- Don't treat 304 status responses specially in HTTP/1.1 mode.", "- Remove out of date ``interfaces.py`` file.", "- Normalize logging (all output is now sent to the ``waitress`` logger rather\n than in degenerate cases some output being sent directly to stderr).", "Features\n~~~~~~~~", "- Support HTTP/1.1 ``Transfer-Encoding: chunked`` responses.", "- Slightly better docs about logging.", "0.1 (2011-12-30)\n----------------", "- Initial release." ]
[ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "1.3.1 (2019-08-27)\n------------------", "Bugfixes\n~~~~~~~~", "- Waitress won't accidentally throw away part of the path if it starts with a\n double slash (``GET //testing/whatever HTTP/1.0``). WSGI applications will\n now receive a ``PATH_INFO`` in the environment that contains\n ``//testing/whatever`` as required. See\n https://github.com/Pylons/waitress/issues/260 and\n https://github.com/Pylons/waitress/pull/261", "\n1.3.0 (2019-04-22)\n------------------", "Deprecations\n~~~~~~~~~~~~", "- The ``send_bytes`` adjustment now defaults to ``1`` and is deprecated\n pending removal in a future release.\n and https://github.com/Pylons/waitress/pull/246", "Features\n~~~~~~~~", "- Add a new ``outbuf_high_watermark`` adjustment which is used to apply\n backpressure on the ``app_iter`` to avoid letting it spin faster than data\n can be written to the socket. This stabilizes responses that iterate quickly\n with a lot of data.\n See https://github.com/Pylons/waitress/pull/242", "- Stop early and close the ``app_iter`` when attempting to write to a closed\n socket due to a client disconnect. This should notify a long-lived streaming\n response when a client hangs up.\n See https://github.com/Pylons/waitress/pull/238\n and https://github.com/Pylons/waitress/pull/240\n and https://github.com/Pylons/waitress/pull/241", "- Adjust the flush to output ``SO_SNDBUF`` bytes instead of whatever was\n set in the ``send_bytes`` adjustment. ``send_bytes`` now only controls how\n much waitress will buffer internally before flushing to the kernel, whereas\n previously it used to also throttle how much data was sent to the kernel.\n This change enables a streaming ``app_iter`` containing small chunks to\n still be flushed efficiently.\n See https://github.com/Pylons/waitress/pull/246", "Bugfixes\n~~~~~~~~", "- Upon receiving a request that does not include HTTP/1.0 or HTTP/1.1 we will\n no longer set the version to the string value \"None\". See\n https://github.com/Pylons/waitress/pull/252 and\n https://github.com/Pylons/waitress/issues/110", "- When a client closes a socket unexpectedly there was potential for memory\n leaks in which data was written to the buffers after they were closed,\n causing them to reopen.\n See https://github.com/Pylons/waitress/pull/239", "- Fix the queue depth warnings to only show when all threads are busy.\n See https://github.com/Pylons/waitress/pull/243\n and https://github.com/Pylons/waitress/pull/247", "- Trigger the ``app_iter`` to close as part of shutdown. This will only be\n noticeable for users of the internal server api. In more typical operations\n the server will die before benefiting from these changes.\n See https://github.com/Pylons/waitress/pull/245", "- Fix a bug in which a streaming ``app_iter`` may never cleanup data that has\n already been sent. This would cause buffers in waitress to grow without\n bounds. These buffers now properly rotate and release their data.\n See https://github.com/Pylons/waitress/pull/242", "- Fix a bug in which non-seekable subclasses of ``io.IOBase`` would trigger\n an exception when passed to the ``wsgi.file_wrapper`` callback.\n See https://github.com/Pylons/waitress/pull/249\n", "1.2.1 (2019-01-25)\n------------------", "Bugfixes\n~~~~~~~~", "- When given an IPv6 address in ``X-Forwarded-For`` or ``Forwarded for=``\n waitress was placing the IP address in ``REMOTE_ADDR`` with brackets:\n ``[2001:db8::0]``, this does not match the requirements in the CGI spec which\n ``REMOTE_ADDR`` was lifted from. Waitress will now place the bare IPv6\n address in ``REMOTE_ADDR``: ``2001:db8::0``. See\n https://github.com/Pylons/waitress/pull/232 and\n https://github.com/Pylons/waitress/issues/230", "1.2.0 (2019-01-15)\n------------------", "No changes since the last beta release. Enjoy Waitress!", "1.2.0b3 (2019-01-07)\n--------------------", "Bugfixes\n~~~~~~~~", "- Modified ``clear_untrusted_proxy_headers`` to be usable without a\n ``trusted_proxy``.\n https://github.com/Pylons/waitress/pull/228", "- Modified ``trusted_proxy_count`` to error when used without a\n ``trusted_proxy``.\n https://github.com/Pylons/waitress/pull/228", "1.2.0b2 (2019-02-02)\n--------------------", "Bugfixes\n~~~~~~~~", "- Fixed logic to no longer warn on writes where the output is required to have\n a body but there may not be any data to be written. Solves issue posted on\n the Pylons Project mailing list with 1.2.0b1.", "1.2.0b1 (2018-12-31)\n--------------------", "Happy New Year!", "Features\n~~~~~~~~", "- Setting the ``trusted_proxy`` setting to ``'*'`` (wildcard) will allow all\n upstreams to be considered trusted proxies, thereby allowing services behind\n Cloudflare/ELBs to function correctly whereby there may not be a singular IP\n address that requests are received from.", " Using this setting is potentially dangerous if your server is also available\n from anywhere on the internet, and further protections should be used to lock\n down access to Waitress. See https://github.com/Pylons/waitress/pull/224", "- Waitress has increased its support of the X-Forwarded-* headers and includes\n Forwarded (RFC7239) support. This may be used to allow proxy servers to\n influence the WSGI environment. See\n https://github.com/Pylons/waitress/pull/209", " This also provides a new security feature when using Waitress behind a proxy\n in that it is possible to remove untrusted proxy headers thereby making sure\n that downstream WSGI applications don't accidentally use those proxy headers\n to make security decisions.", " The documentation has more information, see the following new arguments:", " - trusted_proxy_count\n - trusted_proxy_headers\n - clear_untrusted_proxy_headers\n - log_untrusted_proxy_headers (useful for debugging)", " Be aware that the defaults for these are currently backwards compatible with\n older versions of Waitress, this will change in a future release of waitress.\n If you expect to need this behaviour please explicitly set these variables in\n your configuration, or pin this version of waitress.", " Documentation:\n https://docs.pylonsproject.org/projects/waitress/en/latest/reverse-proxy.html", "- Waitress can now accept a list of sockets that are already pre-bound rather\n than creating its own to allow for socket activation. Support for init\n systems/other systems that create said activated sockets is not included. See\n https://github.com/Pylons/waitress/pull/215", "- Server header can be omitted by specifying ``ident=None`` or ``ident=''``.\n See https://github.com/Pylons/waitress/pull/187", "Bugfixes\n~~~~~~~~", "- Waitress will no longer send Transfer-Encoding or Content-Length for 1xx,\n 204, or 304 responses, and will completely ignore any message body sent by\n the WSGI application, making sure to follow the HTTP standard. See\n https://github.com/Pylons/waitress/pull/166,\n https://github.com/Pylons/waitress/issues/165,\n https://github.com/Pylons/waitress/issues/152, and\n https://github.com/Pylons/waitress/pull/202", "Compatibility\n~~~~~~~~~~~~~", "- Waitress has now \"vendored\" asyncore into itself as ``waitress.wasyncore``.\n This is to cope with the eventuality that asyncore will be removed from\n the Python standard library in 3.8 or so.", "Documentation\n~~~~~~~~~~~~~", "- Bring in documentation of paste.translogger from Pyramid. Reorganize and\n clean up documentation. See\n https://github.com/Pylons/waitress/pull/205\n https://github.com/Pylons/waitress/pull/70\n https://github.com/Pylons/waitress/pull/206", "1.1.0 (2017-10-10)\n------------------", "Features\n~~~~~~~~", "- Waitress now has a __main__ and thus may be called with ``python -mwaitress``", "Bugfixes\n~~~~~~~~", "- Waitress no longer allows lowercase HTTP verbs. This change was made to fall\n in line with most HTTP servers. See https://github.com/Pylons/waitress/pull/170", "- When receiving non-ascii bytes in the request URL, waitress will no longer\n abruptly close the connection, instead returning a 400 Bad Request. See\n https://github.com/Pylons/waitress/pull/162 and\n https://github.com/Pylons/waitress/issues/64", "1.0.2 (2017-02-04)\n------------------", "Features\n~~~~~~~~", "- Python 3.6 is now officially supported in Waitress", "Bugfixes\n~~~~~~~~", "- Add a work-around for libc issue on Linux not following the documented\n standards. If getnameinfo() fails because of DNS not being available it\n should return the IP address instead of the reverse DNS entry, however\n instead getnameinfo() raises. We catch this, and ask getnameinfo()\n for the same information again, explicitly asking for IP address instead of\n reverse DNS hostname. See https://github.com/Pylons/waitress/issues/149 and\n https://github.com/Pylons/waitress/pull/153", "1.0.1 (2016-10-22)\n------------------", "Bugfixes\n~~~~~~~~", "- IPv6 support on Windows was broken due to missing constants in the socket\n module. This has been resolved by setting the constants on Windows if they\n are missing. See https://github.com/Pylons/waitress/issues/138", "- A ValueError was raised on Windows when passing a string for the port, on\n Windows in Python 2 using service names instead of port numbers doesn't work\n with `getaddrinfo`. This has been resolved by attempting to convert the port\n number to an integer, if that fails a ValueError will be raised. See\n https://github.com/Pylons/waitress/issues/139", "\n1.0.0 (2016-08-31)\n------------------", "Bugfixes\n~~~~~~~~", "- Removed `AI_ADDRCONFIG` from the call to `getaddrinfo`, this resolves an\n issue whereby `getaddrinfo` wouldn't return any addresses to `bind` to on\n hosts where there is no internet connection but localhost is requested to be\n bound to. See https://github.com/Pylons/waitress/issues/131 for more\n information.", "Deprecations\n~~~~~~~~~~~~", "- Python 2.6 is no longer supported.", "Features\n~~~~~~~~", "- IPv6 support", "- Waitress is now able to listen on multiple sockets, including IPv4 and IPv6.\n Instead of passing in a host/port combination you now provide waitress with a\n space delineated list, and it will create as many sockets as required.", " .. code-block:: python", "\tfrom waitress import serve\n\tserve(wsgiapp, listen='0.0.0.0:8080 [::]:9090 *:6543')", "Security\n~~~~~~~~", "- Waitress will now drop HTTP headers that contain an underscore in the key\n when received from a client. This is to stop any possible underscore/dash\n conflation that may lead to security issues. See\n https://github.com/Pylons/waitress/pull/80 and\n https://www.djangoproject.com/weblog/2015/jan/13/security/", "0.9.0 (2016-04-15)\n------------------", "Deprecations\n~~~~~~~~~~~~", "- Python 3.2 is no longer supported by Waitress.", "- Python 2.6 will no longer be supported by Waitress in future releases.", "Security/Protections\n~~~~~~~~~~~~~~~~~~~~", "- Building on the changes made in pull request 117, add in checking for line\n feed/carriage return HTTP Response Splitting in the status line, as well as\n the key of a header. See https://github.com/Pylons/waitress/pull/124 and\n https://github.com/Pylons/waitress/issues/122.", "- Waitress will no longer accept headers or status lines with\n newline/carriage returns in them, thereby disallowing HTTP Response\n Splitting. See https://github.com/Pylons/waitress/issues/117 for\n more information, as well as\n https://www.owasp.org/index.php/HTTP_Response_Splitting.", "Bugfixes\n~~~~~~~~", "- FileBasedBuffer and more important ReadOnlyFileBasedBuffer no longer report\n False when tested with bool(), instead always returning True, and becoming\n more iterator like.\n See: https://github.com/Pylons/waitress/pull/82 and\n https://github.com/Pylons/waitress/issues/76", "- Call prune() on the output buffer at the end of a request so that it doesn't\n continue to grow without bounds. See\n https://github.com/Pylons/waitress/issues/111 for more information.", "0.8.10 (2015-09-02)\n-------------------", "- Add support for Python 3.4, 3.5b2, and PyPy3.", "- Use a nonglobal asyncore socket map by default, trying to prevent conflicts\n with apps and libs that use the asyncore global socket map ala\n https://github.com/Pylons/waitress/issues/63. You can get the old\n use-global-socket-map behavior back by passing ``asyncore.socket_map`` to the\n ``create_server`` function as the ``map`` argument.", "- Waitress violated PEP 3333 with respect to reraising an exception when\n ``start_response`` was called with an ``exc_info`` argument. It would\n reraise the exception even if no data had been sent to the client. It now\n only reraises the exception if data has actually been sent to the client.\n See https://github.com/Pylons/waitress/pull/52 and\n https://github.com/Pylons/waitress/issues/51", "- Add a ``docs`` section to tox.ini that, when run, ensures docs can be built.", "- If an ``application`` value of ``None`` is supplied to the ``create_server``\n constructor function, a ValueError is now raised eagerly instead of an error\n occuring during runtime. See https://github.com/Pylons/waitress/pull/60", "- Fix parsing of multi-line (folded) headers.\n See https://github.com/Pylons/waitress/issues/53 and\n https://github.com/Pylons/waitress/pull/90", "- Switch from the low level Python thread/_thread module to the threading\n module.", "- Improved exception information should module import go awry.", "0.8.9 (2014-05-16)\n------------------", "- Fix tests under Windows. NB: to run tests under Windows, you cannot run\n \"setup.py test\" or \"setup.py nosetests\". Instead you must run ``python.exe\n -c \"import nose; nose.main()\"``. If you try to run the tests using the\n normal method under Windows, each subprocess created by the test suite will\n attempt to run the test suite again. See\n https://github.com/nose-devs/nose/issues/407 for more information.", "- Give the WSGI app_iter generated when ``wsgi.file_wrapper`` is used\n (ReadOnlyFileBasedBuffer) a ``close`` method. Do not call ``close`` on an\n instance of such a class when it's used as a WSGI app_iter, however. This is\n part of a fix which prevents a leakage of file descriptors; the other part of\n the fix was in WebOb\n (https://github.com/Pylons/webob/commit/951a41ce57bd853947f842028bccb500bd5237da).", "- Allow trusted proxies to override ``wsgi.url_scheme`` via a request header,\n ``X_FORWARDED_PROTO``. Allows proxies which serve mixed HTTP / HTTPS\n requests to control signal which are served as HTTPS. See\n https://github.com/Pylons/waitress/pull/42.", "0.8.8 (2013-11-30)\n------------------", "- Fix some cases where the creation of extremely large output buffers (greater\n than 2GB, suspected to be buffers added via ``wsgi.file_wrapper``) might\n cause an OverflowError on Python 2. See\n https://github.com/Pylons/waitress/issues/47.", "- When the ``url_prefix`` adjustment starts with more than one slash, all\n slashes except one will be stripped from its beginning. This differs from\n older behavior where more than one leading slash would be preserved in\n ``url_prefix``.", "- If a client somehow manages to send an empty path, we no longer convert the\n empty path to a single slash in ``PATH_INFO``. Instead, the path remains\n empty. According to RFC 2616 section \"5.1.2 Request-URI\", the scenario of a\n client sending an empty path is actually not possible because the request URI\n portion cannot be empty.", "- If the ``url_prefix`` adjustment matches the request path exactly, we now\n compute ``SCRIPT_NAME`` and ``PATH_INFO`` properly. Previously, if the\n ``url_prefix`` was ``/foo`` and the path received from a client was ``/foo``,\n we would set *both* ``SCRIPT_NAME`` and ``PATH_INFO`` to ``/foo``. This was\n incorrect. Now in such a case we set ``PATH_INFO`` to the empty string and\n we set ``SCRIPT_NAME`` to ``/foo``. Note that the change we made has no\n effect on paths that do not match the ``url_prefix`` exactly (such as\n ``/foo/bar``); these continue to operate as they did. See\n https://github.com/Pylons/waitress/issues/46", "- Preserve header ordering of headers with the same name as per RFC 2616. See\n https://github.com/Pylons/waitress/pull/44", "- When waitress receives a ``Transfer-Encoding: chunked`` request, we no longer\n send the ``TRANSFER_ENCODING`` nor the ``HTTP_TRANSFER_ENCODING`` value to\n the application in the environment. Instead, we pop this header. Since we\n cope with chunked requests by buffering the data in the server, we also know\n when a chunked request has ended, and therefore we know the content length.\n We set the content-length header in the environment, such that applications\n effectively never know the original request was a T-E: chunked request; it\n will appear to them as if the request is a non-chunked request with an\n accurate content-length.", "- Cope with the fact that the ``Transfer-Encoding`` value is case-insensitive.", "- When the ``--unix-socket-perms`` option was used as an argument to\n ``waitress-serve``, a ``TypeError`` would be raised. See\n https://github.com/Pylons/waitress/issues/50.", "0.8.7 (2013-08-29)\n------------------", "- The HTTP version of the response returned by waitress when it catches an\n exception will now match the HTTP request version.", "- Fix: CONNECTION header will be HTTP_CONNECTION and not CONNECTION_TYPE\n (see https://github.com/Pylons/waitress/issues/13)", "0.8.6 (2013-08-12)\n------------------", "- Do alternate type of checking for UNIX socket support, instead of checking\n for platform == windows.", "- Functional tests now use multiprocessing module instead of subprocess module,\n speeding up test suite and making concurrent execution more reliable.", "- Runner now appends the current working directory to ``sys.path`` to support\n running WSGI applications from a directory (i.e., not installed in a\n virtualenv).", "- Add a ``url_prefix`` adjustment setting. You can use it by passing\n ``script_name='/foo'`` to ``waitress.serve`` or you can use it in a\n ``PasteDeploy`` ini file as ``script_name = /foo``. This will cause the WSGI\n ``SCRIPT_NAME`` value to be the value passed minus any trailing slashes you\n add, and it will cause the ``PATH_INFO`` of any request which is prefixed\n with this value to be stripped of the prefix. You can use this instead of\n PasteDeploy's ``prefixmiddleware`` to always prefix the path.", "0.8.5 (2013-05-27)\n------------------", "- Fix runner multisegment imports in some Python 2 revisions (see\n https://github.com/Pylons/waitress/pull/34).", "- For compatibility, WSGIServer is now an alias of TcpWSGIServer. The\n signature of BaseWSGIServer is now compatible with WSGIServer pre-0.8.4.", "0.8.4 (2013-05-24)\n------------------", "- Add a command-line runner called ``waitress-serve`` to allow Waitress\n to run WSGI applications without any addional machinery. This is\n essentially a thin wrapper around the ``waitress.serve()`` function.", "- Allow parallel testing (e.g., under ``detox`` or ``nosetests --processes``)\n using PID-dependent port / socket for functest servers.", "- Fix integer overflow errors on large buffers. Thanks to Marcin Kuzminski\n for the patch. See: https://github.com/Pylons/waitress/issues/22", "- Add support for listening on Unix domain sockets.", "0.8.3 (2013-04-28)\n------------------", "Features\n~~~~~~~~", "- Add an ``asyncore_loop_timeout`` adjustment value, which controls the\n ``timeout`` value passed to ``asyncore.loop``; defaults to 1.", "Bug Fixes\n~~~~~~~~~", "- The default asyncore loop timeout is now 1 second. This prevents slow\n shutdown on Windows. See https://github.com/Pylons/waitress/issues/6 . This\n shouldn't matter to anyone in particular, but it can be changed via the\n ``asyncore_loop_timeout`` adjustment (it used to previously default to 30\n seconds).", "- Don't complain if there's a response to a HEAD request that contains a\n Content-Length > 0. See https://github.com/Pylons/waitress/pull/7.", "- Fix bug in HTTP Expect/Continue support. See\n https://github.com/Pylons/waitress/issues/9 .", "\n0.8.2 (2012-11-14)\n------------------", "Bug Fixes\n~~~~~~~~~", "- https://corte.si/posts/code/pathod/pythonservers/index.html pointed out that\n sending a bad header resulted in an exception leading to a 500 response\n instead of the more proper 400 response without an exception.", "- Fix a race condition in the test suite.", "- Allow \"ident\" to be used as a keyword to ``serve()`` as per docs.", "- Add py33 to tox.ini.", "0.8.1 (2012-02-13)\n------------------", "Bug Fixes\n~~~~~~~~~", "- A brown-bag bug prevented request concurrency. A slow request would block\n subsequent the responses of subsequent requests until the slow request's\n response was fully generated. This was due to a \"task lock\" being declared\n as a class attribute rather than as an instance attribute on HTTPChannel.\n Also took the opportunity to move another lock named \"outbuf lock\" to the\n channel instance rather than the class. See\n https://github.com/Pylons/waitress/pull/1 .", "0.8 (2012-01-31)\n----------------", "Features\n~~~~~~~~", "- Support the WSGI ``wsgi.file_wrapper`` protocol as per\n https://www.python.org/dev/peps/pep-0333/#optional-platform-specific-file-handling.\n Here's a usage example::", " import os", " here = os.path.dirname(os.path.abspath(__file__))", " def myapp(environ, start_response):\n f = open(os.path.join(here, 'myphoto.jpg'), 'rb')\n headers = [('Content-Type', 'image/jpeg')]\n start_response(\n '200 OK',\n headers\n )\n return environ['wsgi.file_wrapper'](f, 32768)", " The signature of the file wrapper constructor is ``(filelike_object,\n block_size)``. Both arguments must be passed as positional (not keyword)\n arguments. The result of creating a file wrapper should be **returned** as\n the ``app_iter`` from a WSGI application.", " The object passed as ``filelike_object`` to the wrapper must be a file-like\n object which supports *at least* the ``read()`` method, and the ``read()``\n method must support an optional size hint argument. It *should* support\n the ``seek()`` and ``tell()`` methods. If it does not, normal iteration\n over the filelike object using the provided block_size is used (and copying\n is done, negating any benefit of the file wrapper). It *should* support a\n ``close()`` method.", " The specified ``block_size`` argument to the file wrapper constructor will\n be used only when the ``filelike_object`` doesn't support ``seek`` and/or\n ``tell`` methods. Waitress needs to use normal iteration to serve the file\n in this degenerate case (as per the WSGI spec), and this block size will be\n used as the iteration chunk size. The ``block_size`` argument is optional;\n if it is not passed, a default value``32768`` is used.", " Waitress will set a ``Content-Length`` header on the behalf of an\n application when a file wrapper with a sufficiently filelike object is used\n if the application hasn't already set one.", " The machinery which handles a file wrapper currently doesn't do anything\n particularly special using fancy system calls (it doesn't use ``sendfile``\n for example); using it currently just prevents the system from needing to\n copy data to a temporary buffer in order to send it to the client. No\n copying of data is done when a WSGI app returns a file wrapper that wraps a\n sufficiently filelike object. It may do something fancier in the future.", "0.7 (2012-01-11)\n----------------", "Features\n~~~~~~~~", "- Default ``send_bytes`` value is now 18000 instead of 9000. The larger\n default value prevents asyncore from needing to execute select so many\n times to serve large files, speeding up file serving by about 15%-20% or\n so. This is probably only an optimization for LAN communications, and\n could slow things down across a WAN (due to higher TCP overhead), but we're\n likely to be behind a reverse proxy on a LAN anyway if in production.", "- Added an (undocumented) profiling feature to the ``serve()`` command.", "0.6.1 (2012-01-08)\n------------------", "Bug Fixes\n~~~~~~~~~", "- Remove performance-sapping call to ``pull_trigger`` in the channel's\n ``write_soon`` method added mistakenly in 0.6.", "0.6 (2012-01-07)\n----------------", "Bug Fixes\n~~~~~~~~~", "- A logic error prevented the internal outbuf buffer of a channel from being\n flushed when the client could not accept the entire contents of the output\n buffer in a single succession of socket.send calls when the channel was in\n a \"pending close\" state. The socket in such a case would be closed\n prematurely, sometimes resulting in partially delivered content. This was\n discovered by a user using waitress behind an Nginx reverse proxy, which\n apparently is not always ready to receive data. The symptom was that he\n received \"half\" of a large CSS file (110K) while serving content via\n waitress behind the proxy.", "0.5 (2012-01-03)\n----------------", "Bug Fixes\n~~~~~~~~~", "- Fix PATH_INFO encoding/decoding on Python 3 (as per PEP 3333, tunnel\n bytes-in-unicode-as-latin-1-after-unquoting).", "0.4 (2012-01-02)\n----------------", "Features\n~~~~~~~~", "- Added \"design\" document to docs.", "Bug Fixes\n~~~~~~~~~", "- Set default ``connection_limit`` back to 100 for benefit of maximal\n platform compatibility.", "- Normalize setting of ``last_activity`` during send.", "- Minor resource cleanups during tests.", "- Channel timeout cleanup was broken.", "0.3 (2012-01-02)\n----------------", "Features\n~~~~~~~~", "- Dont hang a thread up trying to send data to slow clients.", "- Use self.logger to log socket errors instead of self.log_info (normalize).", "- Remove pointless handle_error method from channel.", "- Queue requests instead of tasks in a channel.", "Bug Fixes\n~~~~~~~~~", "- Expect: 100-continue responses were broken.", "\n0.2 (2011-12-31)\n----------------", "Bug Fixes\n~~~~~~~~~", "- Set up logging by calling logging.basicConfig() when ``serve`` is called\n (show tracebacks and other warnings to console by default).", "- Disallow WSGI applications to set \"hop-by-hop\" headers (Connection,\n Transfer-Encoding, etc).", "- Don't treat 304 status responses specially in HTTP/1.1 mode.", "- Remove out of date ``interfaces.py`` file.", "- Normalize logging (all output is now sent to the ``waitress`` logger rather\n than in degenerate cases some output being sent directly to stderr).", "Features\n~~~~~~~~", "- Support HTTP/1.1 ``Transfer-Encoding: chunked`` responses.", "- Slightly better docs about logging.", "0.1 (2011-12-30)\n----------------", "- Initial release." ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "##############################################################################\n#\n# Copyright (c) 2006 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\nimport os\nfrom setuptools import setup, find_packages", "here = os.path.abspath(os.path.dirname(__file__))\ntry:\n README = open(os.path.join(here, \"README.rst\")).read()\n CHANGES = open(os.path.join(here, \"CHANGES.txt\")).read()\nexcept IOError:\n README = CHANGES = \"\"", "docs_extras = [\n \"Sphinx>=1.8.1\",\n \"docutils\",\n \"pylons-sphinx-themes>=1.0.9\",\n]", "testing_extras = [\n \"nose\",\n \"coverage>=5.0\",\n]", "setup(\n name=\"waitress\",", " version=\"1.3.1\",", " author=\"Zope Foundation and Contributors\",\n author_email=\"zope-dev@zope.org\",\n maintainer=\"Pylons Project\",\n maintainer_email=\"pylons-discuss@googlegroups.com\",\n description=\"Waitress WSGI server\",\n long_description=README + \"\\n\\n\" + CHANGES,\n license=\"ZPL 2.1\",\n keywords=\"waitress wsgi server http\",\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Environment :: Web Environment\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: Zope Public License\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 2.7\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.4\",\n \"Programming Language :: Python :: 3.5\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n \"Programming Language :: Python :: Implementation :: PyPy\",\n \"Natural Language :: English\",\n \"Operating System :: OS Independent\",\n \"Topic :: Internet :: WWW/HTTP\",\n \"Topic :: Internet :: WWW/HTTP :: WSGI\",\n ],\n url=\"https://github.com/Pylons/waitress\",\n packages=find_packages(),\n extras_require={\"testing\": testing_extras, \"docs\": docs_extras,},\n include_package_data=True,\n test_suite=\"waitress\",\n zip_safe=False,\n entry_points=\"\"\"\n [paste.server_runner]\n main = waitress:serve_paste\n [console_scripts]\n waitress-serve = waitress.runner:run\n \"\"\",\n)" ]
[ 1, 1, 1, 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "##############################################################################\n#\n# Copyright (c) 2006 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\nimport os\nfrom setuptools import setup, find_packages", "here = os.path.abspath(os.path.dirname(__file__))\ntry:\n README = open(os.path.join(here, \"README.rst\")).read()\n CHANGES = open(os.path.join(here, \"CHANGES.txt\")).read()\nexcept IOError:\n README = CHANGES = \"\"", "docs_extras = [\n \"Sphinx>=1.8.1\",\n \"docutils\",\n \"pylons-sphinx-themes>=1.0.9\",\n]", "testing_extras = [\n \"nose\",\n \"coverage>=5.0\",\n]", "setup(\n name=\"waitress\",", " version=\"1.4.0\",", " author=\"Zope Foundation and Contributors\",\n author_email=\"zope-dev@zope.org\",\n maintainer=\"Pylons Project\",\n maintainer_email=\"pylons-discuss@googlegroups.com\",\n description=\"Waitress WSGI server\",\n long_description=README + \"\\n\\n\" + CHANGES,\n license=\"ZPL 2.1\",\n keywords=\"waitress wsgi server http\",\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Environment :: Web Environment\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: Zope Public License\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 2.7\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.4\",\n \"Programming Language :: Python :: 3.5\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n \"Programming Language :: Python :: Implementation :: PyPy\",\n \"Natural Language :: English\",\n \"Operating System :: OS Independent\",\n \"Topic :: Internet :: WWW/HTTP\",\n \"Topic :: Internet :: WWW/HTTP :: WSGI\",\n ],\n url=\"https://github.com/Pylons/waitress\",\n packages=find_packages(),\n extras_require={\"testing\": testing_extras, \"docs\": docs_extras,},\n include_package_data=True,\n test_suite=\"waitress\",\n zip_safe=False,\n entry_points=\"\"\"\n [paste.server_runner]\n main = waitress:serve_paste\n [console_scripts]\n waitress-serve = waitress.runner:run\n \"\"\",\n)" ]
[ 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "##############################################################################\n#\n# Copyright (c) 2001, 2002 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"HTTP Request Parser", "This server uses asyncore to accept connections and do initial\nprocessing but threads to do work.\n\"\"\"\nimport re\nfrom io import BytesIO\n", "from waitress.compat import (\n tostr,\n urlparse,\n unquote_bytes_to_wsgi,\n)\n", "from waitress.buffers import OverflowableBuffer", "\nfrom waitress.receiver import (\n FixedStreamReceiver,\n ChunkedReceiver,\n)\n", "from waitress.utilities import (", " find_double_newline,", " RequestEntityTooLarge,\n RequestHeaderFieldsTooLarge,", " BadRequest,", ")", "\nclass ParsingError(Exception):", "", " pass", "\nclass HTTPRequestParser(object):\n \"\"\"A structure that collects the HTTP request.", " Once the stream is completed, the instance is passed to\n a server task constructor.\n \"\"\"", " completed = False # Set once request is completed.\n empty = False # Set if no request was made.\n expect_continue = False # client sent \"Expect: 100-continue\" header\n headers_finished = False # True when headers have been read\n header_plus = b\"\"\n chunked = False\n content_length = 0\n header_bytes_received = 0\n body_bytes_received = 0\n body_rcv = None\n version = \"1.0\"\n error = None\n connection_close = False", " # Other attributes: first_line, header, headers, command, uri, version,\n # path, query, fragment", " def __init__(self, adj):\n \"\"\"\n adj is an Adjustments object.\n \"\"\"\n # headers is a mapping containing keys translated to uppercase\n # with dashes turned into underscores.\n self.headers = {}\n self.adj = adj", " def received(self, data):\n \"\"\"\n Receives the HTTP stream for one request. Returns the number of\n bytes consumed. Sets the completed flag once both the header and the\n body have been received.\n \"\"\"\n if self.completed:\n return 0 # Can't consume any more.", "", " datalen = len(data)\n br = self.body_rcv\n if br is None:\n # In header.", "", " s = self.header_plus + data\n index = find_double_newline(s)", "", " if index >= 0:\n # Header finished.\n header_plus = s[:index]", " consumed = len(data) - (len(s) - index)\n # Remove preceeding blank lines.", " header_plus = header_plus.lstrip()", "", " if not header_plus:\n self.empty = True\n self.completed = True\n else:\n try:\n self.parse_header(header_plus)\n except ParsingError as e:\n self.error = BadRequest(e.args[0])\n self.completed = True", "", " else:\n if self.body_rcv is None:\n # no content-length header and not a t-e: chunked\n # request\n self.completed = True", "", " if self.content_length > 0:\n max_body = self.adj.max_request_body_size\n # we won't accept this request if the content-length\n # is too large", "", " if self.content_length >= max_body:\n self.error = RequestEntityTooLarge(\n \"exceeds max_body of %s\" % max_body\n )\n self.completed = True\n self.headers_finished = True", "", " return consumed", " else:\n # Header not finished yet.\n self.header_bytes_received += datalen\n max_header = self.adj.max_request_header_size\n if self.header_bytes_received >= max_header:\n # malformed header, we need to construct some request\n # on our own. we disregard the incoming(?) requests HTTP\n # version and just use 1.0. IOW someone just sent garbage\n # over the wire\n self.parse_header(b\"GET / HTTP/1.0\\n\")\n self.error = RequestHeaderFieldsTooLarge(\n \"exceeds max_header of %s\" % max_header\n )\n self.completed = True\n self.header_plus = s\n return datalen", " else:\n # In body.\n consumed = br.received(data)\n self.body_bytes_received += consumed\n max_body = self.adj.max_request_body_size", "", " if self.body_bytes_received >= max_body:\n # this will only be raised during t-e: chunked requests\n self.error = RequestEntityTooLarge(\"exceeds max_body of %s\" % max_body)\n self.completed = True\n elif br.error:\n # garbage in chunked encoding input probably\n self.error = br.error\n self.completed = True\n elif br.completed:\n # The request (with the body) is ready to use.\n self.completed = True", "", " if self.chunked:\n # We've converted the chunked transfer encoding request\n # body into a normal request body, so we know its content\n # length; set the header here. We already popped the\n # TRANSFER_ENCODING header in parse_header, so this will\n # appear to the client to be an entirely non-chunked HTTP\n # request with a valid content-length.\n self.headers[\"CONTENT_LENGTH\"] = str(br.__len__())", "", " return consumed", " def parse_header(self, header_plus):\n \"\"\"\n Parses the header_plus block of text (the headers plus the\n first line of the request).\n \"\"\"", " index = header_plus.find(b\"\\n\")", " if index >= 0:\n first_line = header_plus[:index].rstrip()", " header = header_plus[index + 1 :]\n else:\n first_line = header_plus.rstrip()\n header = b\"\"", "\n self.first_line = first_line # for testing", " lines = get_header_lines(header)", " headers = self.headers\n for line in lines:\n index = line.find(b\":\")\n if index > 0:\n key = line[:index]", "", " if b\"_\" in key:\n continue\n value = line[index + 1 :].strip()\n key1 = tostr(key.upper().replace(b\"-\", b\"_\"))\n # If a header already exists, we append subsequent values\n # seperated by a comma. Applications already need to handle\n # the comma seperated values, as HTTP front ends might do\n # the concatenation for you (behavior specified in RFC2616).\n try:\n headers[key1] += tostr(b\", \" + value)\n except KeyError:\n headers[key1] = tostr(value)\n # else there's garbage in the headers?", " # command, uri, version will be bytes\n command, uri, version = crack_first_line(first_line)\n version = tostr(version)\n command = tostr(command)\n self.command = command\n self.version = version\n (\n self.proxy_scheme,\n self.proxy_netloc,\n self.path,\n self.query,\n self.fragment,\n ) = split_uri(uri)\n self.url_scheme = self.adj.url_scheme\n connection = headers.get(\"CONNECTION\", \"\")", " if version == \"1.0\":\n if connection.lower() != \"keep-alive\":\n self.connection_close = True", " if version == \"1.1\":\n # since the server buffers data from chunked transfers and clients\n # never need to deal with chunked requests, downstream clients\n # should not see the HTTP_TRANSFER_ENCODING header; we pop it\n # here\n te = headers.pop(\"TRANSFER_ENCODING\", \"\")", " if te.lower() == \"chunked\":", " self.chunked = True\n buf = OverflowableBuffer(self.adj.inbuf_overflow)\n self.body_rcv = ChunkedReceiver(buf)", "", " expect = headers.get(\"EXPECT\", \"\").lower()\n self.expect_continue = expect == \"100-continue\"\n if connection.lower() == \"close\":\n self.connection_close = True", " if not self.chunked:\n try:\n cl = int(headers.get(\"CONTENT_LENGTH\", 0))\n except ValueError:", " cl = 0", " self.content_length = cl\n if cl > 0:\n buf = OverflowableBuffer(self.adj.inbuf_overflow)\n self.body_rcv = FixedStreamReceiver(cl, buf)", " def get_body_stream(self):\n body_rcv = self.body_rcv\n if body_rcv is not None:\n return body_rcv.getfile()\n else:\n return BytesIO()", " def close(self):\n body_rcv = self.body_rcv\n if body_rcv is not None:\n body_rcv.getbuf().close()", "\ndef split_uri(uri):\n # urlsplit handles byte input by returning bytes on py3, so\n # scheme, netloc, path, query, and fragment are bytes", " scheme = netloc = path = query = fragment = b\"\"", " # urlsplit below will treat this as a scheme-less netloc, thereby losing\n # the original intent of the request. Here we shamelessly stole 4 lines of\n # code from the CPython stdlib to parse out the fragment and query but\n # leave the path alone. See\n # https://github.com/python/cpython/blob/8c9e9b0cd5b24dfbf1424d1f253d02de80e8f5ef/Lib/urllib/parse.py#L465-L468\n # and https://github.com/Pylons/waitress/issues/260", " if uri[:2] == b\"//\":\n path = uri", " if b\"#\" in path:\n path, fragment = path.split(b\"#\", 1)", " if b\"?\" in path:\n path, query = path.split(b\"?\", 1)\n else:\n try:\n scheme, netloc, path, query, fragment = urlparse.urlsplit(uri)\n except UnicodeError:\n raise ParsingError(\"Bad URI\")", " return (\n tostr(scheme),\n tostr(netloc),\n unquote_bytes_to_wsgi(path),\n tostr(query),\n tostr(fragment),\n )", "\ndef get_header_lines(header):\n \"\"\"\n Splits the header into lines, putting multi-line headers together.\n \"\"\"\n r = []", " lines = header.split(b\"\\n\")", " for line in lines:", "", " if line.startswith((b\" \", b\"\\t\")):\n if not r:\n # https://corte.si/posts/code/pathod/pythonservers/index.html\n raise ParsingError('Malformed header line \"%s\"' % tostr(line))\n r[-1] += line\n else:\n r.append(line)\n return r", "\nfirst_line_re = re.compile(\n b\"([^ ]+) \"\n b\"((?:[^ :?#]+://[^ ?#/]*(?:[0-9]{1,5})?)?[^ ]+)\"\n b\"(( HTTP/([0-9.]+))$|$)\"\n)", "\ndef crack_first_line(line):\n m = first_line_re.match(line)\n if m is not None and m.end() == len(line):\n if m.group(3):\n version = m.group(5)\n else:\n version = b\"\"\n method = m.group(1)", " # the request methods that are currently defined are all uppercase:\n # https://www.iana.org/assignments/http-methods/http-methods.xhtml and\n # the request method is case sensitive according to\n # https://tools.ietf.org/html/rfc7231#section-4.1", " # By disallowing anything but uppercase methods we save poor\n # unsuspecting souls from sending lowercase HTTP methods to waitress\n # and having the request complete, while servers like nginx drop the\n # request onto the floor.\n if method != method.upper():\n raise ParsingError('Malformed HTTP method \"%s\"' % tostr(method))\n uri = m.group(2)\n return method, uri, version\n else:\n return b\"\", b\"\", b\"\"" ]
[ 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "##############################################################################\n#\n# Copyright (c) 2001, 2002 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"HTTP Request Parser", "This server uses asyncore to accept connections and do initial\nprocessing but threads to do work.\n\"\"\"\nimport re\nfrom io import BytesIO\n", "", "from waitress.buffers import OverflowableBuffer", "from waitress.compat import tostr, unquote_bytes_to_wsgi, urlparse\nfrom waitress.receiver import ChunkedReceiver, FixedStreamReceiver", "from waitress.utilities import (", " BadRequest,", " RequestEntityTooLarge,\n RequestHeaderFieldsTooLarge,", " ServerNotImplemented,\n find_double_newline,", ")", "\nclass ParsingError(Exception):", " pass", "\nclass TransferEncodingNotImplemented(Exception):", " pass", "\nclass HTTPRequestParser(object):\n \"\"\"A structure that collects the HTTP request.", " Once the stream is completed, the instance is passed to\n a server task constructor.\n \"\"\"", " completed = False # Set once request is completed.\n empty = False # Set if no request was made.\n expect_continue = False # client sent \"Expect: 100-continue\" header\n headers_finished = False # True when headers have been read\n header_plus = b\"\"\n chunked = False\n content_length = 0\n header_bytes_received = 0\n body_bytes_received = 0\n body_rcv = None\n version = \"1.0\"\n error = None\n connection_close = False", " # Other attributes: first_line, header, headers, command, uri, version,\n # path, query, fragment", " def __init__(self, adj):\n \"\"\"\n adj is an Adjustments object.\n \"\"\"\n # headers is a mapping containing keys translated to uppercase\n # with dashes turned into underscores.\n self.headers = {}\n self.adj = adj", " def received(self, data):\n \"\"\"\n Receives the HTTP stream for one request. Returns the number of\n bytes consumed. Sets the completed flag once both the header and the\n body have been received.\n \"\"\"\n if self.completed:\n return 0 # Can't consume any more.", "", " datalen = len(data)\n br = self.body_rcv\n if br is None:\n # In header.", " max_header = self.adj.max_request_header_size\n", " s = self.header_plus + data\n index = find_double_newline(s)", " consumed = 0", " if index >= 0:\n # If the headers have ended, and we also have part of the body\n # message in data we still want to validate we aren't going\n # over our limit for received headers.\n self.header_bytes_received += index\n consumed = datalen - (len(s) - index)\n else:\n self.header_bytes_received += datalen\n consumed = datalen", " # If the first line + headers is over the max length, we return a\n # RequestHeaderFieldsTooLarge error rather than continuing to\n # attempt to parse the headers.\n if self.header_bytes_received >= max_header:\n self.parse_header(b\"GET / HTTP/1.0\\r\\n\")\n self.error = RequestHeaderFieldsTooLarge(\n \"exceeds max_header of %s\" % max_header\n )\n self.completed = True\n return consumed\n", " if index >= 0:\n # Header finished.\n header_plus = s[:index]", "\n # Remove preceeding blank lines. This is suggested by\n # https://tools.ietf.org/html/rfc7230#section-3.5 to support\n # clients sending an extra CR LF after another request when\n # using HTTP pipelining", " header_plus = header_plus.lstrip()", "", " if not header_plus:\n self.empty = True\n self.completed = True\n else:\n try:\n self.parse_header(header_plus)\n except ParsingError as e:\n self.error = BadRequest(e.args[0])\n self.completed = True", " except TransferEncodingNotImplemented as e:\n self.error = ServerNotImplemented(e.args[0])\n self.completed = True", " else:\n if self.body_rcv is None:\n # no content-length header and not a t-e: chunked\n # request\n self.completed = True", "", " if self.content_length > 0:\n max_body = self.adj.max_request_body_size\n # we won't accept this request if the content-length\n # is too large", "", " if self.content_length >= max_body:\n self.error = RequestEntityTooLarge(\n \"exceeds max_body of %s\" % max_body\n )\n self.completed = True\n self.headers_finished = True", "", " return consumed", "\n # Header not finished yet.\n self.header_plus = s", " return datalen", " else:\n # In body.\n consumed = br.received(data)\n self.body_bytes_received += consumed\n max_body = self.adj.max_request_body_size", "", " if self.body_bytes_received >= max_body:\n # this will only be raised during t-e: chunked requests\n self.error = RequestEntityTooLarge(\"exceeds max_body of %s\" % max_body)\n self.completed = True\n elif br.error:\n # garbage in chunked encoding input probably\n self.error = br.error\n self.completed = True\n elif br.completed:\n # The request (with the body) is ready to use.\n self.completed = True", "", " if self.chunked:\n # We've converted the chunked transfer encoding request\n # body into a normal request body, so we know its content\n # length; set the header here. We already popped the\n # TRANSFER_ENCODING header in parse_header, so this will\n # appear to the client to be an entirely non-chunked HTTP\n # request with a valid content-length.\n self.headers[\"CONTENT_LENGTH\"] = str(br.__len__())", "", " return consumed", " def parse_header(self, header_plus):\n \"\"\"\n Parses the header_plus block of text (the headers plus the\n first line of the request).\n \"\"\"", " index = header_plus.find(b\"\\r\\n\")", " if index >= 0:\n first_line = header_plus[:index].rstrip()", " header = header_plus[index + 2 :]\n else:\n raise ParsingError(\"HTTP message header invalid\")", " if b\"\\r\" in first_line or b\"\\n\" in first_line:\n raise ParsingError(\"Bare CR or LF found in HTTP message\")", "\n self.first_line = first_line # for testing", " lines = get_header_lines(header)", " headers = self.headers\n for line in lines:\n index = line.find(b\":\")\n if index > 0:\n key = line[:index]", "\n if key != key.strip():\n raise ParsingError(\"Invalid whitespace after field-name\")\n", " if b\"_\" in key:\n continue\n value = line[index + 1 :].strip()\n key1 = tostr(key.upper().replace(b\"-\", b\"_\"))\n # If a header already exists, we append subsequent values\n # seperated by a comma. Applications already need to handle\n # the comma seperated values, as HTTP front ends might do\n # the concatenation for you (behavior specified in RFC2616).\n try:\n headers[key1] += tostr(b\", \" + value)\n except KeyError:\n headers[key1] = tostr(value)\n # else there's garbage in the headers?", " # command, uri, version will be bytes\n command, uri, version = crack_first_line(first_line)\n version = tostr(version)\n command = tostr(command)\n self.command = command\n self.version = version\n (\n self.proxy_scheme,\n self.proxy_netloc,\n self.path,\n self.query,\n self.fragment,\n ) = split_uri(uri)\n self.url_scheme = self.adj.url_scheme\n connection = headers.get(\"CONNECTION\", \"\")", " if version == \"1.0\":\n if connection.lower() != \"keep-alive\":\n self.connection_close = True", " if version == \"1.1\":\n # since the server buffers data from chunked transfers and clients\n # never need to deal with chunked requests, downstream clients\n # should not see the HTTP_TRANSFER_ENCODING header; we pop it\n # here\n te = headers.pop(\"TRANSFER_ENCODING\", \"\")", "\n encodings = [encoding.strip().lower() for encoding in te.split(\",\") if encoding]", " for encoding in encodings:\n # Out of the transfer-codings listed in\n # https://tools.ietf.org/html/rfc7230#section-4 we only support\n # chunked at this time.", " # Note: the identity transfer-coding was removed in RFC7230:\n # https://tools.ietf.org/html/rfc7230#appendix-A.2 and is thus\n # not supported\n if encoding not in {\"chunked\"}:\n raise TransferEncodingNotImplemented(\n \"Transfer-Encoding requested is not supported.\"\n )", " if encodings and encodings[-1] == \"chunked\":", " self.chunked = True\n buf = OverflowableBuffer(self.adj.inbuf_overflow)\n self.body_rcv = ChunkedReceiver(buf)", " elif encodings: # pragma: nocover\n raise TransferEncodingNotImplemented(\n \"Transfer-Encoding requested is not supported.\"\n )\n", " expect = headers.get(\"EXPECT\", \"\").lower()\n self.expect_continue = expect == \"100-continue\"\n if connection.lower() == \"close\":\n self.connection_close = True", " if not self.chunked:\n try:\n cl = int(headers.get(\"CONTENT_LENGTH\", 0))\n except ValueError:", " raise ParsingError(\"Content-Length is invalid\")\n", " self.content_length = cl\n if cl > 0:\n buf = OverflowableBuffer(self.adj.inbuf_overflow)\n self.body_rcv = FixedStreamReceiver(cl, buf)", " def get_body_stream(self):\n body_rcv = self.body_rcv\n if body_rcv is not None:\n return body_rcv.getfile()\n else:\n return BytesIO()", " def close(self):\n body_rcv = self.body_rcv\n if body_rcv is not None:\n body_rcv.getbuf().close()", "\ndef split_uri(uri):\n # urlsplit handles byte input by returning bytes on py3, so\n # scheme, netloc, path, query, and fragment are bytes", " scheme = netloc = path = query = fragment = b\"\"", " # urlsplit below will treat this as a scheme-less netloc, thereby losing\n # the original intent of the request. Here we shamelessly stole 4 lines of\n # code from the CPython stdlib to parse out the fragment and query but\n # leave the path alone. See\n # https://github.com/python/cpython/blob/8c9e9b0cd5b24dfbf1424d1f253d02de80e8f5ef/Lib/urllib/parse.py#L465-L468\n # and https://github.com/Pylons/waitress/issues/260", " if uri[:2] == b\"//\":\n path = uri", " if b\"#\" in path:\n path, fragment = path.split(b\"#\", 1)", " if b\"?\" in path:\n path, query = path.split(b\"?\", 1)\n else:\n try:\n scheme, netloc, path, query, fragment = urlparse.urlsplit(uri)\n except UnicodeError:\n raise ParsingError(\"Bad URI\")", " return (\n tostr(scheme),\n tostr(netloc),\n unquote_bytes_to_wsgi(path),\n tostr(query),\n tostr(fragment),\n )", "\ndef get_header_lines(header):\n \"\"\"\n Splits the header into lines, putting multi-line headers together.\n \"\"\"\n r = []", " lines = header.split(b\"\\r\\n\")", " for line in lines:", " if b\"\\r\" in line or b\"\\n\" in line:\n raise ParsingError('Bare CR or LF found in header line \"%s\"' % tostr(line))\n", " if line.startswith((b\" \", b\"\\t\")):\n if not r:\n # https://corte.si/posts/code/pathod/pythonservers/index.html\n raise ParsingError('Malformed header line \"%s\"' % tostr(line))\n r[-1] += line\n else:\n r.append(line)\n return r", "\nfirst_line_re = re.compile(\n b\"([^ ]+) \"\n b\"((?:[^ :?#]+://[^ ?#/]*(?:[0-9]{1,5})?)?[^ ]+)\"\n b\"(( HTTP/([0-9.]+))$|$)\"\n)", "\ndef crack_first_line(line):\n m = first_line_re.match(line)\n if m is not None and m.end() == len(line):\n if m.group(3):\n version = m.group(5)\n else:\n version = b\"\"\n method = m.group(1)", " # the request methods that are currently defined are all uppercase:\n # https://www.iana.org/assignments/http-methods/http-methods.xhtml and\n # the request method is case sensitive according to\n # https://tools.ietf.org/html/rfc7231#section-4.1", " # By disallowing anything but uppercase methods we save poor\n # unsuspecting souls from sending lowercase HTTP methods to waitress\n # and having the request complete, while servers like nginx drop the\n # request onto the floor.\n if method != method.upper():\n raise ParsingError('Malformed HTTP method \"%s\"' % tostr(method))\n uri = m.group(2)\n return method, uri, version\n else:\n return b\"\", b\"\", b\"\"" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "##############################################################################\n#\n# Copyright (c) 2001, 2002 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Data Chunk Receiver\n\"\"\"\n", "from waitress.utilities import find_double_newline", "from waitress.utilities import BadRequest", "", "class FixedStreamReceiver(object):", " # See IStreamConsumer\n completed = False\n error = None", " def __init__(self, cl, buf):\n self.remain = cl\n self.buf = buf", " def __len__(self):\n return self.buf.__len__()", " def received(self, data):\n \"See IStreamConsumer\"\n rm = self.remain", "", " if rm < 1:\n self.completed = True # Avoid any chance of spinning", "", " return 0\n datalen = len(data)", "", " if rm <= datalen:\n self.buf.append(data[:rm])\n self.remain = 0\n self.completed = True", "", " return rm\n else:\n self.buf.append(data)\n self.remain -= datalen", "", " return datalen", " def getfile(self):\n return self.buf.getfile()", " def getbuf(self):\n return self.buf", "\nclass ChunkedReceiver(object):", " chunk_remainder = 0", "", " control_line = b\"\"", "", " all_chunks_received = False\n trailer = b\"\"\n completed = False\n error = None", " # max_control_line = 1024\n # max_trailer = 65536", " def __init__(self, buf):\n self.buf = buf", " def __len__(self):\n return self.buf.__len__()", " def received(self, s):\n # Returns the number of bytes consumed.", "", " if self.completed:\n return 0\n orig_size = len(s)", "", " while s:\n rm = self.chunk_remainder", "", " if rm > 0:\n # Receive the remainder of a chunk.\n to_write = s[:rm]\n self.buf.append(to_write)\n written = len(to_write)\n s = s[written:]", "", " self.chunk_remainder -= written", "", " elif not self.all_chunks_received:\n # Receive a control line.\n s = self.control_line + s", " pos = s.find(b\"\\n\")", " if pos < 0:\n # Control line not finished.\n self.control_line = s", " s = \"\"", " else:\n # Control line finished.\n line = s[:pos]", " s = s[pos + 1 :]", " self.control_line = b\"\"\n line = line.strip()", "", " if line:\n # Begin a new chunk.\n semi = line.find(b\";\")", "", " if semi >= 0:\n # discard extension info.\n line = line[:semi]\n try:\n sz = int(line.strip(), 16) # hexadecimal\n except ValueError: # garbage in input\n self.error = BadRequest(\"garbage in chunked encoding input\")\n sz = 0", "", " if sz > 0:\n # Start a new chunk.\n self.chunk_remainder = sz\n else:\n # Finished chunks.\n self.all_chunks_received = True\n # else expect a control line.\n else:\n # Receive the trailer.\n trailer = self.trailer + s", "", " if trailer.startswith(b\"\\r\\n\"):\n # No trailer.\n self.completed = True", "", " return orig_size - (len(trailer) - 2)", " elif trailer.startswith(b\"\\n\"):\n # No trailer.\n self.completed = True\n return orig_size - (len(trailer) - 1)", " pos = find_double_newline(trailer)", "", " if pos < 0:\n # Trailer not finished.\n self.trailer = trailer\n s = b\"\"\n else:\n # Finished the trailer.\n self.completed = True\n self.trailer = trailer[:pos]", "", " return orig_size - (len(trailer) - pos)", "", " return orig_size", " def getfile(self):\n return self.buf.getfile()", " def getbuf(self):\n return self.buf" ]
[ 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "##############################################################################\n#\n# Copyright (c) 2001, 2002 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Data Chunk Receiver\n\"\"\"\n", "from waitress.utilities import BadRequest, find_double_newline", "", "class FixedStreamReceiver(object):", " # See IStreamConsumer\n completed = False\n error = None", " def __init__(self, cl, buf):\n self.remain = cl\n self.buf = buf", " def __len__(self):\n return self.buf.__len__()", " def received(self, data):\n \"See IStreamConsumer\"\n rm = self.remain", "", " if rm < 1:\n self.completed = True # Avoid any chance of spinning", "", " return 0\n datalen = len(data)", "", " if rm <= datalen:\n self.buf.append(data[:rm])\n self.remain = 0\n self.completed = True", "", " return rm\n else:\n self.buf.append(data)\n self.remain -= datalen", "", " return datalen", " def getfile(self):\n return self.buf.getfile()", " def getbuf(self):\n return self.buf", "\nclass ChunkedReceiver(object):", " chunk_remainder = 0", " validate_chunk_end = False", " control_line = b\"\"", " chunk_end = b\"\"", " all_chunks_received = False\n trailer = b\"\"\n completed = False\n error = None", " # max_control_line = 1024\n # max_trailer = 65536", " def __init__(self, buf):\n self.buf = buf", " def __len__(self):\n return self.buf.__len__()", " def received(self, s):\n # Returns the number of bytes consumed.", "", " if self.completed:\n return 0\n orig_size = len(s)", "", " while s:\n rm = self.chunk_remainder", "", " if rm > 0:\n # Receive the remainder of a chunk.\n to_write = s[:rm]\n self.buf.append(to_write)\n written = len(to_write)\n s = s[written:]", "", " self.chunk_remainder -= written", "\n if self.chunk_remainder == 0:\n self.validate_chunk_end = True\n elif self.validate_chunk_end:\n s = self.chunk_end + s", " pos = s.find(b\"\\r\\n\")", " if pos < 0 and len(s) < 2:\n self.chunk_end = s\n s = b\"\"\n else:\n self.chunk_end = b\"\"\n if pos == 0:\n # Chop off the terminating CR LF from the chunk\n s = s[2:]\n else:\n self.error = BadRequest(\"Chunk not properly terminated\")\n self.all_chunks_received = True", " # Always exit this loop\n self.validate_chunk_end = False", " elif not self.all_chunks_received:\n # Receive a control line.\n s = self.control_line + s", " pos = s.find(b\"\\r\\n\")\n", " if pos < 0:\n # Control line not finished.\n self.control_line = s", " s = b\"\"", " else:\n # Control line finished.\n line = s[:pos]", " s = s[pos + 2 :]", " self.control_line = b\"\"\n line = line.strip()", "", " if line:\n # Begin a new chunk.\n semi = line.find(b\";\")", "", " if semi >= 0:\n # discard extension info.\n line = line[:semi]\n try:\n sz = int(line.strip(), 16) # hexadecimal\n except ValueError: # garbage in input\n self.error = BadRequest(\"garbage in chunked encoding input\")\n sz = 0", "", " if sz > 0:\n # Start a new chunk.\n self.chunk_remainder = sz\n else:\n # Finished chunks.\n self.all_chunks_received = True\n # else expect a control line.\n else:\n # Receive the trailer.\n trailer = self.trailer + s", "", " if trailer.startswith(b\"\\r\\n\"):\n # No trailer.\n self.completed = True", "", " return orig_size - (len(trailer) - 2)", "", " pos = find_double_newline(trailer)", "", " if pos < 0:\n # Trailer not finished.\n self.trailer = trailer\n s = b\"\"\n else:\n # Finished the trailer.\n self.completed = True\n self.trailer = trailer[:pos]", "", " return orig_size - (len(trailer) - pos)", "", " return orig_size", " def getfile(self):\n return self.buf.getfile()", " def getbuf(self):\n return self.buf" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "##############################################################################\n#\n# Copyright (c) 2001, 2002 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################", "import socket\nimport sys\nimport threading\nimport time\nfrom collections import deque", "from .buffers import ReadOnlyFileBasedBuffer\nfrom .compat import reraise, tobytes\nfrom .utilities import build_http_date, logger, queue_logger", "rename_headers = { # or keep them without the HTTP_ prefix added\n \"CONTENT_LENGTH\": \"CONTENT_LENGTH\",\n \"CONTENT_TYPE\": \"CONTENT_TYPE\",\n}", "hop_by_hop = frozenset(\n (\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"te\",\n \"trailers\",\n \"transfer-encoding\",\n \"upgrade\",\n )\n)", "\nclass ThreadedTaskDispatcher(object):\n \"\"\"A Task Dispatcher that creates a thread for each task.\n \"\"\"", " stop_count = 0 # Number of threads that will stop soon.\n active_count = 0 # Number of currently active threads\n logger = logger\n queue_logger = queue_logger", " def __init__(self):\n self.threads = set()\n self.queue = deque()\n self.lock = threading.Lock()\n self.queue_cv = threading.Condition(self.lock)\n self.thread_exit_cv = threading.Condition(self.lock)", " def start_new_thread(self, target, args):\n t = threading.Thread(target=target, name=\"waitress\", args=args)\n t.daemon = True\n t.start()", " def handler_thread(self, thread_no):\n while True:\n with self.lock:\n while not self.queue and self.stop_count == 0:\n # Mark ourselves as idle before waiting to be\n # woken up, then we will once again be active\n self.active_count -= 1\n self.queue_cv.wait()\n self.active_count += 1", " if self.stop_count > 0:\n self.active_count -= 1\n self.stop_count -= 1\n self.threads.discard(thread_no)\n self.thread_exit_cv.notify()\n break", " task = self.queue.popleft()\n try:\n task.service()\n except BaseException:\n self.logger.exception(\"Exception when servicing %r\", task)", " def set_thread_count(self, count):\n with self.lock:\n threads = self.threads\n thread_no = 0\n running = len(threads) - self.stop_count\n while running < count:\n # Start threads.\n while thread_no in threads:\n thread_no = thread_no + 1\n threads.add(thread_no)\n running += 1\n self.start_new_thread(self.handler_thread, (thread_no,))\n self.active_count += 1\n thread_no = thread_no + 1\n if running > count:\n # Stop threads.\n self.stop_count += running - count\n self.queue_cv.notify_all()", " def add_task(self, task):\n with self.lock:\n self.queue.append(task)\n self.queue_cv.notify()\n queue_size = len(self.queue)\n idle_threads = len(self.threads) - self.stop_count - self.active_count\n if queue_size > idle_threads:\n self.queue_logger.warning(\n \"Task queue depth is %d\", queue_size - idle_threads\n )", " def shutdown(self, cancel_pending=True, timeout=5):\n self.set_thread_count(0)\n # Ensure the threads shut down.\n threads = self.threads\n expiration = time.time() + timeout\n with self.lock:\n while threads:\n if time.time() >= expiration:\n self.logger.warning(\"%d thread(s) still running\", len(threads))\n break\n self.thread_exit_cv.wait(0.1)\n if cancel_pending:\n # Cancel remaining tasks.\n queue = self.queue\n if len(queue) > 0:\n self.logger.warning(\"Canceling %d pending task(s)\", len(queue))\n while queue:\n task = queue.popleft()\n task.cancel()\n self.queue_cv.notify_all()\n return True\n return False", "\nclass Task(object):\n close_on_finish = False\n status = \"200 OK\"\n wrote_header = False\n start_time = 0\n content_length = None\n content_bytes_written = 0\n logged_write_excess = False\n logged_write_no_body = False\n complete = False\n chunked_response = False\n logger = logger", " def __init__(self, channel, request):\n self.channel = channel\n self.request = request\n self.response_headers = []\n version = request.version\n if version not in (\"1.0\", \"1.1\"):\n # fall back to a version we support.\n version = \"1.0\"\n self.version = version", " def service(self):\n try:\n try:\n self.start()\n self.execute()\n self.finish()\n except socket.error:\n self.close_on_finish = True\n if self.channel.adj.log_socket_errors:\n raise\n finally:\n pass", " @property\n def has_body(self):\n return not (\n self.status.startswith(\"1\")\n or self.status.startswith(\"204\")\n or self.status.startswith(\"304\")\n )", " def build_response_header(self):\n version = self.version\n # Figure out whether the connection should be closed.\n connection = self.request.headers.get(\"CONNECTION\", \"\").lower()\n response_headers = []\n content_length_header = None\n date_header = None\n server_header = None\n connection_close_header = None", " for (headername, headerval) in self.response_headers:\n headername = \"-\".join([x.capitalize() for x in headername.split(\"-\")])", " if headername == \"Content-Length\":\n if self.has_body:\n content_length_header = headerval\n else:\n continue # pragma: no cover", " if headername == \"Date\":\n date_header = headerval", " if headername == \"Server\":\n server_header = headerval", " if headername == \"Connection\":\n connection_close_header = headerval.lower()\n # replace with properly capitalized version\n response_headers.append((headername, headerval))", " if (\n content_length_header is None\n and self.content_length is not None\n and self.has_body\n ):\n content_length_header = str(self.content_length)\n response_headers.append((\"Content-Length\", content_length_header))", " def close_on_finish():\n if connection_close_header is None:\n response_headers.append((\"Connection\", \"close\"))\n self.close_on_finish = True", " if version == \"1.0\":\n if connection == \"keep-alive\":\n if not content_length_header:\n close_on_finish()\n else:\n response_headers.append((\"Connection\", \"Keep-Alive\"))\n else:\n close_on_finish()", " elif version == \"1.1\":\n if connection == \"close\":\n close_on_finish()", " if not content_length_header:\n # RFC 7230: MUST NOT send Transfer-Encoding or Content-Length\n # for any response with a status code of 1xx, 204 or 304.", " if self.has_body:\n response_headers.append((\"Transfer-Encoding\", \"chunked\"))\n self.chunked_response = True", " if not self.close_on_finish:\n close_on_finish()", " # under HTTP 1.1 keep-alive is default, no need to set the header\n else:\n raise AssertionError(\"neither HTTP/1.0 or HTTP/1.1\")", " # Set the Server and Date field, if not yet specified. This is needed\n # if the server is used as a proxy.\n ident = self.channel.server.adj.ident", " if not server_header:\n if ident:\n response_headers.append((\"Server\", ident))\n else:\n response_headers.append((\"Via\", ident or \"waitress\"))", " if not date_header:\n response_headers.append((\"Date\", build_http_date(self.start_time)))", " self.response_headers = response_headers", " first_line = \"HTTP/%s %s\" % (self.version, self.status)\n # NB: sorting headers needs to preserve same-named-header order\n # as per RFC 2616 section 4.2; thus the key=lambda x: x[0] here;\n # rely on stable sort to keep relative position of same-named headers\n next_lines = [\n \"%s: %s\" % hv for hv in sorted(self.response_headers, key=lambda x: x[0])\n ]\n lines = [first_line] + next_lines\n res = \"%s\\r\\n\\r\\n\" % \"\\r\\n\".join(lines)", " return tobytes(res)", " def remove_content_length_header(self):\n response_headers = []", " for header_name, header_value in self.response_headers:\n if header_name.lower() == \"content-length\":\n continue # pragma: nocover\n response_headers.append((header_name, header_value))", " self.response_headers = response_headers", " def start(self):\n self.start_time = time.time()", " def finish(self):\n if not self.wrote_header:\n self.write(b\"\")\n if self.chunked_response:\n # not self.write, it will chunk it!\n self.channel.write_soon(b\"0\\r\\n\\r\\n\")", " def write(self, data):\n if not self.complete:\n raise RuntimeError(\"start_response was not called before body written\")\n channel = self.channel\n if not self.wrote_header:\n rh = self.build_response_header()\n channel.write_soon(rh)\n self.wrote_header = True", " if data and self.has_body:\n towrite = data\n cl = self.content_length\n if self.chunked_response:\n # use chunked encoding response\n towrite = tobytes(hex(len(data))[2:].upper()) + b\"\\r\\n\"\n towrite += data + b\"\\r\\n\"\n elif cl is not None:\n towrite = data[: cl - self.content_bytes_written]\n self.content_bytes_written += len(towrite)\n if towrite != data and not self.logged_write_excess:\n self.logger.warning(\n \"application-written content exceeded the number of \"\n \"bytes specified by Content-Length header (%s)\" % cl\n )\n self.logged_write_excess = True\n if towrite:\n channel.write_soon(towrite)\n elif data:\n # Cheat, and tell the application we have written all of the bytes,\n # even though the response shouldn't have a body and we are\n # ignoring it entirely.\n self.content_bytes_written += len(data)", " if not self.logged_write_no_body:\n self.logger.warning(\n \"application-written content was ignored due to HTTP \"\n \"response that may not contain a message-body: (%s)\" % self.status\n )\n self.logged_write_no_body = True", "\nclass ErrorTask(Task):\n \"\"\" An error task produces an error response\n \"\"\"", " complete = True", " def execute(self):\n e = self.request.error\n status, headers, body = e.to_response()\n self.status = status\n self.response_headers.extend(headers)", " if self.version == \"1.1\":\n connection = self.request.headers.get(\"CONNECTION\", \"\").lower()\n if connection == \"close\":\n self.response_headers.append((\"Connection\", \"close\"))\n # under HTTP 1.1 keep-alive is default, no need to set the header\n else:\n # HTTP 1.0\n self.response_headers.append((\"Connection\", \"close\"))", " self.close_on_finish = True\n self.content_length = len(body)\n self.write(tobytes(body))", "\nclass WSGITask(Task):\n \"\"\"A WSGI task produces a response from a WSGI application.\n \"\"\"", " environ = None", " def execute(self):\n environ = self.get_environment()", " def start_response(status, headers, exc_info=None):\n if self.complete and not exc_info:\n raise AssertionError(\n \"start_response called a second time without providing exc_info.\"\n )\n if exc_info:\n try:\n if self.wrote_header:\n # higher levels will catch and handle raised exception:\n # 1. \"service\" method in task.py\n # 2. \"service\" method in channel.py\n # 3. \"handler_thread\" method in task.py\n reraise(exc_info[0], exc_info[1], exc_info[2])\n else:\n # As per WSGI spec existing headers must be cleared\n self.response_headers = []\n finally:\n exc_info = None", " self.complete = True", " if not status.__class__ is str:\n raise AssertionError(\"status %s is not a string\" % status)\n if \"\\n\" in status or \"\\r\" in status:\n raise ValueError(\n \"carriage return/line feed character present in status\"\n )", " self.status = status", " # Prepare the headers for output\n for k, v in headers:\n if not k.__class__ is str:\n raise AssertionError(\n \"Header name %r is not a string in %r\" % (k, (k, v))\n )\n if not v.__class__ is str:\n raise AssertionError(\n \"Header value %r is not a string in %r\" % (v, (k, v))\n )", " if \"\\n\" in v or \"\\r\" in v:\n raise ValueError(\n \"carriage return/line feed character present in header value\"\n )\n if \"\\n\" in k or \"\\r\" in k:\n raise ValueError(\n \"carriage return/line feed character present in header name\"\n )", " kl = k.lower()\n if kl == \"content-length\":\n self.content_length = int(v)\n elif kl in hop_by_hop:\n raise AssertionError(\n '%s is a \"hop-by-hop\" header; it cannot be used by '\n \"a WSGI application (see PEP 3333)\" % k\n )", " self.response_headers.extend(headers)", " # Return a method used to write the response data.\n return self.write", " # Call the application to handle the request and write a response\n app_iter = self.channel.server.application(environ, start_response)", " can_close_app_iter = True\n try:\n if app_iter.__class__ is ReadOnlyFileBasedBuffer:\n cl = self.content_length\n size = app_iter.prepare(cl)\n if size:\n if cl != size:\n if cl is not None:\n self.remove_content_length_header()\n self.content_length = size\n self.write(b\"\") # generate headers\n # if the write_soon below succeeds then the channel will\n # take over closing the underlying file via the channel's\n # _flush_some or handle_close so we intentionally avoid\n # calling close in the finally block\n self.channel.write_soon(app_iter)\n can_close_app_iter = False\n return", " first_chunk_len = None\n for chunk in app_iter:\n if first_chunk_len is None:\n first_chunk_len = len(chunk)\n # Set a Content-Length header if one is not supplied.\n # start_response may not have been called until first\n # iteration as per PEP, so we must reinterrogate\n # self.content_length here\n if self.content_length is None:\n app_iter_len = None\n if hasattr(app_iter, \"__len__\"):\n app_iter_len = len(app_iter)\n if app_iter_len == 1:\n self.content_length = first_chunk_len\n # transmit headers only after first iteration of the iterable\n # that returns a non-empty bytestring (PEP 3333)\n if chunk:\n self.write(chunk)", " cl = self.content_length\n if cl is not None:\n if self.content_bytes_written != cl:\n # close the connection so the client isn't sitting around\n # waiting for more data when there are too few bytes\n # to service content-length\n self.close_on_finish = True\n if self.request.command != \"HEAD\":\n self.logger.warning(\n \"application returned too few bytes (%s) \"\n \"for specified Content-Length (%s) via app_iter\"\n % (self.content_bytes_written, cl),\n )\n finally:\n if can_close_app_iter and hasattr(app_iter, \"close\"):\n app_iter.close()", " def get_environment(self):\n \"\"\"Returns a WSGI environment.\"\"\"\n environ = self.environ\n if environ is not None:\n # Return the cached copy.\n return environ", " request = self.request\n path = request.path\n channel = self.channel\n server = channel.server\n url_prefix = server.adj.url_prefix", " if path.startswith(\"/\"):\n # strip extra slashes at the beginning of a path that starts\n # with any number of slashes\n path = \"/\" + path.lstrip(\"/\")", " if url_prefix:\n # NB: url_prefix is guaranteed by the configuration machinery to\n # be either the empty string or a string that starts with a single\n # slash and ends without any slashes\n if path == url_prefix:\n # if the path is the same as the url prefix, the SCRIPT_NAME\n # should be the url_prefix and PATH_INFO should be empty\n path = \"\"\n else:\n # if the path starts with the url prefix plus a slash,\n # the SCRIPT_NAME should be the url_prefix and PATH_INFO should\n # the value of path from the slash until its end\n url_prefix_with_trailing_slash = url_prefix + \"/\"\n if path.startswith(url_prefix_with_trailing_slash):\n path = path[len(url_prefix) :]", " environ = {\n \"REMOTE_ADDR\": channel.addr[0],\n # Nah, we aren't actually going to look up the reverse DNS for\n # REMOTE_ADDR, but we will happily set this environment variable\n # for the WSGI application. Spec says we can just set this to\n # REMOTE_ADDR, so we do.\n \"REMOTE_HOST\": channel.addr[0],\n # try and set the REMOTE_PORT to something useful, but maybe None\n \"REMOTE_PORT\": str(channel.addr[1]),\n \"REQUEST_METHOD\": request.command.upper(),\n \"SERVER_PORT\": str(server.effective_port),\n \"SERVER_NAME\": server.server_name,\n \"SERVER_SOFTWARE\": server.adj.ident,\n \"SERVER_PROTOCOL\": \"HTTP/%s\" % self.version,\n \"SCRIPT_NAME\": url_prefix,\n \"PATH_INFO\": path,\n \"QUERY_STRING\": request.query,\n \"wsgi.url_scheme\": request.url_scheme,\n # the following environment variables are required by the WSGI spec\n \"wsgi.version\": (1, 0),\n # apps should use the logging module\n \"wsgi.errors\": sys.stderr,\n \"wsgi.multithread\": True,\n \"wsgi.multiprocess\": False,\n \"wsgi.run_once\": False,\n \"wsgi.input\": request.get_body_stream(),\n \"wsgi.file_wrapper\": ReadOnlyFileBasedBuffer,\n \"wsgi.input_terminated\": True, # wsgi.input is EOF terminated\n }", " for key, value in dict(request.headers).items():\n value = value.strip()\n mykey = rename_headers.get(key, None)\n if mykey is None:\n mykey = \"HTTP_\" + key\n if mykey not in environ:\n environ[mykey] = value", " # cache the environ for this request\n self.environ = environ\n return environ" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "##############################################################################\n#\n# Copyright (c) 2001, 2002 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################", "import socket\nimport sys\nimport threading\nimport time\nfrom collections import deque", "from .buffers import ReadOnlyFileBasedBuffer\nfrom .compat import reraise, tobytes\nfrom .utilities import build_http_date, logger, queue_logger", "rename_headers = { # or keep them without the HTTP_ prefix added\n \"CONTENT_LENGTH\": \"CONTENT_LENGTH\",\n \"CONTENT_TYPE\": \"CONTENT_TYPE\",\n}", "hop_by_hop = frozenset(\n (\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"te\",\n \"trailers\",\n \"transfer-encoding\",\n \"upgrade\",\n )\n)", "\nclass ThreadedTaskDispatcher(object):\n \"\"\"A Task Dispatcher that creates a thread for each task.\n \"\"\"", " stop_count = 0 # Number of threads that will stop soon.\n active_count = 0 # Number of currently active threads\n logger = logger\n queue_logger = queue_logger", " def __init__(self):\n self.threads = set()\n self.queue = deque()\n self.lock = threading.Lock()\n self.queue_cv = threading.Condition(self.lock)\n self.thread_exit_cv = threading.Condition(self.lock)", " def start_new_thread(self, target, args):\n t = threading.Thread(target=target, name=\"waitress\", args=args)\n t.daemon = True\n t.start()", " def handler_thread(self, thread_no):\n while True:\n with self.lock:\n while not self.queue and self.stop_count == 0:\n # Mark ourselves as idle before waiting to be\n # woken up, then we will once again be active\n self.active_count -= 1\n self.queue_cv.wait()\n self.active_count += 1", " if self.stop_count > 0:\n self.active_count -= 1\n self.stop_count -= 1\n self.threads.discard(thread_no)\n self.thread_exit_cv.notify()\n break", " task = self.queue.popleft()\n try:\n task.service()\n except BaseException:\n self.logger.exception(\"Exception when servicing %r\", task)", " def set_thread_count(self, count):\n with self.lock:\n threads = self.threads\n thread_no = 0\n running = len(threads) - self.stop_count\n while running < count:\n # Start threads.\n while thread_no in threads:\n thread_no = thread_no + 1\n threads.add(thread_no)\n running += 1\n self.start_new_thread(self.handler_thread, (thread_no,))\n self.active_count += 1\n thread_no = thread_no + 1\n if running > count:\n # Stop threads.\n self.stop_count += running - count\n self.queue_cv.notify_all()", " def add_task(self, task):\n with self.lock:\n self.queue.append(task)\n self.queue_cv.notify()\n queue_size = len(self.queue)\n idle_threads = len(self.threads) - self.stop_count - self.active_count\n if queue_size > idle_threads:\n self.queue_logger.warning(\n \"Task queue depth is %d\", queue_size - idle_threads\n )", " def shutdown(self, cancel_pending=True, timeout=5):\n self.set_thread_count(0)\n # Ensure the threads shut down.\n threads = self.threads\n expiration = time.time() + timeout\n with self.lock:\n while threads:\n if time.time() >= expiration:\n self.logger.warning(\"%d thread(s) still running\", len(threads))\n break\n self.thread_exit_cv.wait(0.1)\n if cancel_pending:\n # Cancel remaining tasks.\n queue = self.queue\n if len(queue) > 0:\n self.logger.warning(\"Canceling %d pending task(s)\", len(queue))\n while queue:\n task = queue.popleft()\n task.cancel()\n self.queue_cv.notify_all()\n return True\n return False", "\nclass Task(object):\n close_on_finish = False\n status = \"200 OK\"\n wrote_header = False\n start_time = 0\n content_length = None\n content_bytes_written = 0\n logged_write_excess = False\n logged_write_no_body = False\n complete = False\n chunked_response = False\n logger = logger", " def __init__(self, channel, request):\n self.channel = channel\n self.request = request\n self.response_headers = []\n version = request.version\n if version not in (\"1.0\", \"1.1\"):\n # fall back to a version we support.\n version = \"1.0\"\n self.version = version", " def service(self):\n try:\n try:\n self.start()\n self.execute()\n self.finish()\n except socket.error:\n self.close_on_finish = True\n if self.channel.adj.log_socket_errors:\n raise\n finally:\n pass", " @property\n def has_body(self):\n return not (\n self.status.startswith(\"1\")\n or self.status.startswith(\"204\")\n or self.status.startswith(\"304\")\n )", " def build_response_header(self):\n version = self.version\n # Figure out whether the connection should be closed.\n connection = self.request.headers.get(\"CONNECTION\", \"\").lower()\n response_headers = []\n content_length_header = None\n date_header = None\n server_header = None\n connection_close_header = None", " for (headername, headerval) in self.response_headers:\n headername = \"-\".join([x.capitalize() for x in headername.split(\"-\")])", " if headername == \"Content-Length\":\n if self.has_body:\n content_length_header = headerval\n else:\n continue # pragma: no cover", " if headername == \"Date\":\n date_header = headerval", " if headername == \"Server\":\n server_header = headerval", " if headername == \"Connection\":\n connection_close_header = headerval.lower()\n # replace with properly capitalized version\n response_headers.append((headername, headerval))", " if (\n content_length_header is None\n and self.content_length is not None\n and self.has_body\n ):\n content_length_header = str(self.content_length)\n response_headers.append((\"Content-Length\", content_length_header))", " def close_on_finish():\n if connection_close_header is None:\n response_headers.append((\"Connection\", \"close\"))\n self.close_on_finish = True", " if version == \"1.0\":\n if connection == \"keep-alive\":\n if not content_length_header:\n close_on_finish()\n else:\n response_headers.append((\"Connection\", \"Keep-Alive\"))\n else:\n close_on_finish()", " elif version == \"1.1\":\n if connection == \"close\":\n close_on_finish()", " if not content_length_header:\n # RFC 7230: MUST NOT send Transfer-Encoding or Content-Length\n # for any response with a status code of 1xx, 204 or 304.", " if self.has_body:\n response_headers.append((\"Transfer-Encoding\", \"chunked\"))\n self.chunked_response = True", " if not self.close_on_finish:\n close_on_finish()", " # under HTTP 1.1 keep-alive is default, no need to set the header\n else:\n raise AssertionError(\"neither HTTP/1.0 or HTTP/1.1\")", " # Set the Server and Date field, if not yet specified. This is needed\n # if the server is used as a proxy.\n ident = self.channel.server.adj.ident", " if not server_header:\n if ident:\n response_headers.append((\"Server\", ident))\n else:\n response_headers.append((\"Via\", ident or \"waitress\"))", " if not date_header:\n response_headers.append((\"Date\", build_http_date(self.start_time)))", " self.response_headers = response_headers", " first_line = \"HTTP/%s %s\" % (self.version, self.status)\n # NB: sorting headers needs to preserve same-named-header order\n # as per RFC 2616 section 4.2; thus the key=lambda x: x[0] here;\n # rely on stable sort to keep relative position of same-named headers\n next_lines = [\n \"%s: %s\" % hv for hv in sorted(self.response_headers, key=lambda x: x[0])\n ]\n lines = [first_line] + next_lines\n res = \"%s\\r\\n\\r\\n\" % \"\\r\\n\".join(lines)", " return tobytes(res)", " def remove_content_length_header(self):\n response_headers = []", " for header_name, header_value in self.response_headers:\n if header_name.lower() == \"content-length\":\n continue # pragma: nocover\n response_headers.append((header_name, header_value))", " self.response_headers = response_headers", " def start(self):\n self.start_time = time.time()", " def finish(self):\n if not self.wrote_header:\n self.write(b\"\")\n if self.chunked_response:\n # not self.write, it will chunk it!\n self.channel.write_soon(b\"0\\r\\n\\r\\n\")", " def write(self, data):\n if not self.complete:\n raise RuntimeError(\"start_response was not called before body written\")\n channel = self.channel\n if not self.wrote_header:\n rh = self.build_response_header()\n channel.write_soon(rh)\n self.wrote_header = True", " if data and self.has_body:\n towrite = data\n cl = self.content_length\n if self.chunked_response:\n # use chunked encoding response\n towrite = tobytes(hex(len(data))[2:].upper()) + b\"\\r\\n\"\n towrite += data + b\"\\r\\n\"\n elif cl is not None:\n towrite = data[: cl - self.content_bytes_written]\n self.content_bytes_written += len(towrite)\n if towrite != data and not self.logged_write_excess:\n self.logger.warning(\n \"application-written content exceeded the number of \"\n \"bytes specified by Content-Length header (%s)\" % cl\n )\n self.logged_write_excess = True\n if towrite:\n channel.write_soon(towrite)\n elif data:\n # Cheat, and tell the application we have written all of the bytes,\n # even though the response shouldn't have a body and we are\n # ignoring it entirely.\n self.content_bytes_written += len(data)", " if not self.logged_write_no_body:\n self.logger.warning(\n \"application-written content was ignored due to HTTP \"\n \"response that may not contain a message-body: (%s)\" % self.status\n )\n self.logged_write_no_body = True", "\nclass ErrorTask(Task):\n \"\"\" An error task produces an error response\n \"\"\"", " complete = True", " def execute(self):\n e = self.request.error\n status, headers, body = e.to_response()\n self.status = status\n self.response_headers.extend(headers)", " # We need to explicitly tell the remote client we are closing the\n # connection, because self.close_on_finish is set, and we are going to\n # slam the door in the clients face.\n self.response_headers.append((\"Connection\", \"close\"))", " self.close_on_finish = True\n self.content_length = len(body)\n self.write(tobytes(body))", "\nclass WSGITask(Task):\n \"\"\"A WSGI task produces a response from a WSGI application.\n \"\"\"", " environ = None", " def execute(self):\n environ = self.get_environment()", " def start_response(status, headers, exc_info=None):\n if self.complete and not exc_info:\n raise AssertionError(\n \"start_response called a second time without providing exc_info.\"\n )\n if exc_info:\n try:\n if self.wrote_header:\n # higher levels will catch and handle raised exception:\n # 1. \"service\" method in task.py\n # 2. \"service\" method in channel.py\n # 3. \"handler_thread\" method in task.py\n reraise(exc_info[0], exc_info[1], exc_info[2])\n else:\n # As per WSGI spec existing headers must be cleared\n self.response_headers = []\n finally:\n exc_info = None", " self.complete = True", " if not status.__class__ is str:\n raise AssertionError(\"status %s is not a string\" % status)\n if \"\\n\" in status or \"\\r\" in status:\n raise ValueError(\n \"carriage return/line feed character present in status\"\n )", " self.status = status", " # Prepare the headers for output\n for k, v in headers:\n if not k.__class__ is str:\n raise AssertionError(\n \"Header name %r is not a string in %r\" % (k, (k, v))\n )\n if not v.__class__ is str:\n raise AssertionError(\n \"Header value %r is not a string in %r\" % (v, (k, v))\n )", " if \"\\n\" in v or \"\\r\" in v:\n raise ValueError(\n \"carriage return/line feed character present in header value\"\n )\n if \"\\n\" in k or \"\\r\" in k:\n raise ValueError(\n \"carriage return/line feed character present in header name\"\n )", " kl = k.lower()\n if kl == \"content-length\":\n self.content_length = int(v)\n elif kl in hop_by_hop:\n raise AssertionError(\n '%s is a \"hop-by-hop\" header; it cannot be used by '\n \"a WSGI application (see PEP 3333)\" % k\n )", " self.response_headers.extend(headers)", " # Return a method used to write the response data.\n return self.write", " # Call the application to handle the request and write a response\n app_iter = self.channel.server.application(environ, start_response)", " can_close_app_iter = True\n try:\n if app_iter.__class__ is ReadOnlyFileBasedBuffer:\n cl = self.content_length\n size = app_iter.prepare(cl)\n if size:\n if cl != size:\n if cl is not None:\n self.remove_content_length_header()\n self.content_length = size\n self.write(b\"\") # generate headers\n # if the write_soon below succeeds then the channel will\n # take over closing the underlying file via the channel's\n # _flush_some or handle_close so we intentionally avoid\n # calling close in the finally block\n self.channel.write_soon(app_iter)\n can_close_app_iter = False\n return", " first_chunk_len = None\n for chunk in app_iter:\n if first_chunk_len is None:\n first_chunk_len = len(chunk)\n # Set a Content-Length header if one is not supplied.\n # start_response may not have been called until first\n # iteration as per PEP, so we must reinterrogate\n # self.content_length here\n if self.content_length is None:\n app_iter_len = None\n if hasattr(app_iter, \"__len__\"):\n app_iter_len = len(app_iter)\n if app_iter_len == 1:\n self.content_length = first_chunk_len\n # transmit headers only after first iteration of the iterable\n # that returns a non-empty bytestring (PEP 3333)\n if chunk:\n self.write(chunk)", " cl = self.content_length\n if cl is not None:\n if self.content_bytes_written != cl:\n # close the connection so the client isn't sitting around\n # waiting for more data when there are too few bytes\n # to service content-length\n self.close_on_finish = True\n if self.request.command != \"HEAD\":\n self.logger.warning(\n \"application returned too few bytes (%s) \"\n \"for specified Content-Length (%s) via app_iter\"\n % (self.content_bytes_written, cl),\n )\n finally:\n if can_close_app_iter and hasattr(app_iter, \"close\"):\n app_iter.close()", " def get_environment(self):\n \"\"\"Returns a WSGI environment.\"\"\"\n environ = self.environ\n if environ is not None:\n # Return the cached copy.\n return environ", " request = self.request\n path = request.path\n channel = self.channel\n server = channel.server\n url_prefix = server.adj.url_prefix", " if path.startswith(\"/\"):\n # strip extra slashes at the beginning of a path that starts\n # with any number of slashes\n path = \"/\" + path.lstrip(\"/\")", " if url_prefix:\n # NB: url_prefix is guaranteed by the configuration machinery to\n # be either the empty string or a string that starts with a single\n # slash and ends without any slashes\n if path == url_prefix:\n # if the path is the same as the url prefix, the SCRIPT_NAME\n # should be the url_prefix and PATH_INFO should be empty\n path = \"\"\n else:\n # if the path starts with the url prefix plus a slash,\n # the SCRIPT_NAME should be the url_prefix and PATH_INFO should\n # the value of path from the slash until its end\n url_prefix_with_trailing_slash = url_prefix + \"/\"\n if path.startswith(url_prefix_with_trailing_slash):\n path = path[len(url_prefix) :]", " environ = {\n \"REMOTE_ADDR\": channel.addr[0],\n # Nah, we aren't actually going to look up the reverse DNS for\n # REMOTE_ADDR, but we will happily set this environment variable\n # for the WSGI application. Spec says we can just set this to\n # REMOTE_ADDR, so we do.\n \"REMOTE_HOST\": channel.addr[0],\n # try and set the REMOTE_PORT to something useful, but maybe None\n \"REMOTE_PORT\": str(channel.addr[1]),\n \"REQUEST_METHOD\": request.command.upper(),\n \"SERVER_PORT\": str(server.effective_port),\n \"SERVER_NAME\": server.server_name,\n \"SERVER_SOFTWARE\": server.adj.ident,\n \"SERVER_PROTOCOL\": \"HTTP/%s\" % self.version,\n \"SCRIPT_NAME\": url_prefix,\n \"PATH_INFO\": path,\n \"QUERY_STRING\": request.query,\n \"wsgi.url_scheme\": request.url_scheme,\n # the following environment variables are required by the WSGI spec\n \"wsgi.version\": (1, 0),\n # apps should use the logging module\n \"wsgi.errors\": sys.stderr,\n \"wsgi.multithread\": True,\n \"wsgi.multiprocess\": False,\n \"wsgi.run_once\": False,\n \"wsgi.input\": request.get_body_stream(),\n \"wsgi.file_wrapper\": ReadOnlyFileBasedBuffer,\n \"wsgi.input_terminated\": True, # wsgi.input is EOF terminated\n }", " for key, value in dict(request.headers).items():\n value = value.strip()\n mykey = rename_headers.get(key, None)\n if mykey is None:\n mykey = \"HTTP_\" + key\n if mykey not in environ:\n environ[mykey] = value", " # cache the environ for this request\n self.environ = environ\n return environ" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "import unittest\nimport io", "\nclass TestHTTPChannel(unittest.TestCase):\n def _makeOne(self, sock, addr, adj, map=None):\n from waitress.channel import HTTPChannel", " server = DummyServer()\n return HTTPChannel(server, sock, addr, adj=adj, map=map)", " def _makeOneWithMap(self, adj=None):\n if adj is None:\n adj = DummyAdjustments()\n sock = DummySock()\n map = {}\n inst = self._makeOne(sock, \"127.0.0.1\", adj, map=map)\n inst.outbuf_lock = DummyLock()\n return inst, sock, map", " def test_ctor(self):\n inst, _, map = self._makeOneWithMap()\n self.assertEqual(inst.addr, \"127.0.0.1\")\n self.assertEqual(inst.sendbuf_len, 2048)\n self.assertEqual(map[100], inst)", " def test_total_outbufs_len_an_outbuf_size_gt_sys_maxint(self):\n from waitress.compat import MAXINT", " inst, _, map = self._makeOneWithMap()", " class DummyBuffer(object):\n chunks = []", " def append(self, data):\n self.chunks.append(data)", " class DummyData(object):\n def __len__(self):\n return MAXINT", " inst.total_outbufs_len = 1\n inst.outbufs = [DummyBuffer()]\n inst.write_soon(DummyData())\n # we are testing that this method does not raise an OverflowError\n # (see https://github.com/Pylons/waitress/issues/47)\n self.assertEqual(inst.total_outbufs_len, MAXINT + 1)", " def test_writable_something_in_outbuf(self):\n inst, sock, map = self._makeOneWithMap()\n inst.total_outbufs_len = 3\n self.assertTrue(inst.writable())", " def test_writable_nothing_in_outbuf(self):\n inst, sock, map = self._makeOneWithMap()\n self.assertFalse(inst.writable())", " def test_writable_nothing_in_outbuf_will_close(self):\n inst, sock, map = self._makeOneWithMap()\n inst.will_close = True\n self.assertTrue(inst.writable())", " def test_handle_write_not_connected(self):\n inst, sock, map = self._makeOneWithMap()\n inst.connected = False\n self.assertFalse(inst.handle_write())", " def test_handle_write_with_requests(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = True\n inst.last_activity = 0\n result = inst.handle_write()\n self.assertEqual(result, None)\n self.assertEqual(inst.last_activity, 0)", " def test_handle_write_no_request_with_outbuf(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = []\n inst.outbufs = [DummyBuffer(b\"abc\")]\n inst.total_outbufs_len = len(inst.outbufs[0])\n inst.last_activity = 0\n result = inst.handle_write()\n self.assertEqual(result, None)\n self.assertNotEqual(inst.last_activity, 0)\n self.assertEqual(sock.sent, b\"abc\")", " def test_handle_write_outbuf_raises_socketerror(self):\n import socket", " inst, sock, map = self._makeOneWithMap()\n inst.requests = []\n outbuf = DummyBuffer(b\"abc\", socket.error)\n inst.outbufs = [outbuf]\n inst.total_outbufs_len = len(outbuf)\n inst.last_activity = 0\n inst.logger = DummyLogger()\n result = inst.handle_write()\n self.assertEqual(result, None)\n self.assertEqual(inst.last_activity, 0)\n self.assertEqual(sock.sent, b\"\")\n self.assertEqual(len(inst.logger.exceptions), 1)\n self.assertTrue(outbuf.closed)", " def test_handle_write_outbuf_raises_othererror(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = []\n outbuf = DummyBuffer(b\"abc\", IOError)\n inst.outbufs = [outbuf]\n inst.total_outbufs_len = len(outbuf)\n inst.last_activity = 0\n inst.logger = DummyLogger()\n result = inst.handle_write()\n self.assertEqual(result, None)\n self.assertEqual(inst.last_activity, 0)\n self.assertEqual(sock.sent, b\"\")\n self.assertEqual(len(inst.logger.exceptions), 1)\n self.assertTrue(outbuf.closed)", " def test_handle_write_no_requests_no_outbuf_will_close(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = []\n outbuf = DummyBuffer(b\"\")\n inst.outbufs = [outbuf]\n inst.will_close = True\n inst.last_activity = 0\n result = inst.handle_write()\n self.assertEqual(result, None)\n self.assertEqual(inst.connected, False)\n self.assertEqual(sock.closed, True)\n self.assertEqual(inst.last_activity, 0)\n self.assertTrue(outbuf.closed)", " def test_handle_write_no_requests_outbuf_gt_send_bytes(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = [True]\n inst.outbufs = [DummyBuffer(b\"abc\")]\n inst.total_outbufs_len = len(inst.outbufs[0])\n inst.adj.send_bytes = 2\n inst.will_close = False\n inst.last_activity = 0\n result = inst.handle_write()\n self.assertEqual(result, None)\n self.assertEqual(inst.will_close, False)\n self.assertTrue(inst.outbuf_lock.acquired)\n self.assertEqual(sock.sent, b\"abc\")", " def test_handle_write_close_when_flushed(self):\n inst, sock, map = self._makeOneWithMap()\n outbuf = DummyBuffer(b\"abc\")\n inst.outbufs = [outbuf]\n inst.total_outbufs_len = len(outbuf)\n inst.will_close = False\n inst.close_when_flushed = True\n inst.last_activity = 0\n result = inst.handle_write()\n self.assertEqual(result, None)\n self.assertEqual(inst.will_close, True)\n self.assertEqual(inst.close_when_flushed, False)\n self.assertEqual(sock.sent, b\"abc\")\n self.assertTrue(outbuf.closed)", " def test_readable_no_requests_not_will_close(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = []\n inst.will_close = False\n self.assertEqual(inst.readable(), True)", " def test_readable_no_requests_will_close(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = []\n inst.will_close = True\n self.assertEqual(inst.readable(), False)", " def test_readable_with_requests(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = True\n self.assertEqual(inst.readable(), False)", " def test_handle_read_no_error(self):\n inst, sock, map = self._makeOneWithMap()\n inst.will_close = False\n inst.recv = lambda *arg: b\"abc\"\n inst.last_activity = 0\n L = []\n inst.received = lambda x: L.append(x)\n result = inst.handle_read()\n self.assertEqual(result, None)\n self.assertNotEqual(inst.last_activity, 0)\n self.assertEqual(L, [b\"abc\"])", " def test_handle_read_error(self):\n import socket", " inst, sock, map = self._makeOneWithMap()\n inst.will_close = False", " def recv(b):\n raise socket.error", " inst.recv = recv\n inst.last_activity = 0\n inst.logger = DummyLogger()\n result = inst.handle_read()\n self.assertEqual(result, None)\n self.assertEqual(inst.last_activity, 0)\n self.assertEqual(len(inst.logger.exceptions), 1)", " def test_write_soon_empty_byte(self):\n inst, sock, map = self._makeOneWithMap()\n wrote = inst.write_soon(b\"\")\n self.assertEqual(wrote, 0)\n self.assertEqual(len(inst.outbufs[0]), 0)", " def test_write_soon_nonempty_byte(self):\n inst, sock, map = self._makeOneWithMap()\n wrote = inst.write_soon(b\"a\")\n self.assertEqual(wrote, 1)\n self.assertEqual(len(inst.outbufs[0]), 1)", " def test_write_soon_filewrapper(self):\n from waitress.buffers import ReadOnlyFileBasedBuffer", " f = io.BytesIO(b\"abc\")\n wrapper = ReadOnlyFileBasedBuffer(f, 8192)\n wrapper.prepare()\n inst, sock, map = self._makeOneWithMap()\n outbufs = inst.outbufs\n orig_outbuf = outbufs[0]\n wrote = inst.write_soon(wrapper)\n self.assertEqual(wrote, 3)\n self.assertEqual(len(outbufs), 3)\n self.assertEqual(outbufs[0], orig_outbuf)\n self.assertEqual(outbufs[1], wrapper)\n self.assertEqual(outbufs[2].__class__.__name__, \"OverflowableBuffer\")", " def test_write_soon_disconnected(self):\n from waitress.channel import ClientDisconnected", " inst, sock, map = self._makeOneWithMap()\n inst.connected = False\n self.assertRaises(ClientDisconnected, lambda: inst.write_soon(b\"stuff\"))", " def test_write_soon_disconnected_while_over_watermark(self):\n from waitress.channel import ClientDisconnected", " inst, sock, map = self._makeOneWithMap()", " def dummy_flush():\n inst.connected = False", " inst._flush_outbufs_below_high_watermark = dummy_flush\n self.assertRaises(ClientDisconnected, lambda: inst.write_soon(b\"stuff\"))", " def test_write_soon_rotates_outbuf_on_overflow(self):\n inst, sock, map = self._makeOneWithMap()\n inst.adj.outbuf_high_watermark = 3\n inst.current_outbuf_count = 4\n wrote = inst.write_soon(b\"xyz\")\n self.assertEqual(wrote, 3)\n self.assertEqual(len(inst.outbufs), 2)\n self.assertEqual(inst.outbufs[0].get(), b\"\")\n self.assertEqual(inst.outbufs[1].get(), b\"xyz\")", " def test_write_soon_waits_on_backpressure(self):\n inst, sock, map = self._makeOneWithMap()\n inst.adj.outbuf_high_watermark = 3\n inst.total_outbufs_len = 4\n inst.current_outbuf_count = 4", " class Lock(DummyLock):\n def wait(self):\n inst.total_outbufs_len = 0\n super(Lock, self).wait()", " inst.outbuf_lock = Lock()\n wrote = inst.write_soon(b\"xyz\")\n self.assertEqual(wrote, 3)\n self.assertEqual(len(inst.outbufs), 2)\n self.assertEqual(inst.outbufs[0].get(), b\"\")\n self.assertEqual(inst.outbufs[1].get(), b\"xyz\")\n self.assertTrue(inst.outbuf_lock.waited)", " def test_handle_write_notify_after_flush(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = [True]\n inst.outbufs = [DummyBuffer(b\"abc\")]\n inst.total_outbufs_len = len(inst.outbufs[0])\n inst.adj.send_bytes = 1\n inst.adj.outbuf_high_watermark = 5\n inst.will_close = False\n inst.last_activity = 0\n result = inst.handle_write()\n self.assertEqual(result, None)\n self.assertEqual(inst.will_close, False)\n self.assertTrue(inst.outbuf_lock.acquired)\n self.assertTrue(inst.outbuf_lock.notified)\n self.assertEqual(sock.sent, b\"abc\")", " def test_handle_write_no_notify_after_flush(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = [True]\n inst.outbufs = [DummyBuffer(b\"abc\")]\n inst.total_outbufs_len = len(inst.outbufs[0])\n inst.adj.send_bytes = 1\n inst.adj.outbuf_high_watermark = 2\n sock.send = lambda x: False\n inst.will_close = False\n inst.last_activity = 0\n result = inst.handle_write()\n self.assertEqual(result, None)\n self.assertEqual(inst.will_close, False)\n self.assertTrue(inst.outbuf_lock.acquired)\n self.assertFalse(inst.outbuf_lock.notified)\n self.assertEqual(sock.sent, b\"\")", " def test__flush_some_empty_outbuf(self):\n inst, sock, map = self._makeOneWithMap()\n result = inst._flush_some()\n self.assertEqual(result, False)", " def test__flush_some_full_outbuf_socket_returns_nonzero(self):\n inst, sock, map = self._makeOneWithMap()\n inst.outbufs[0].append(b\"abc\")\n inst.total_outbufs_len = sum(len(x) for x in inst.outbufs)\n result = inst._flush_some()\n self.assertEqual(result, True)", " def test__flush_some_full_outbuf_socket_returns_zero(self):\n inst, sock, map = self._makeOneWithMap()\n sock.send = lambda x: False\n inst.outbufs[0].append(b\"abc\")\n inst.total_outbufs_len = sum(len(x) for x in inst.outbufs)\n result = inst._flush_some()\n self.assertEqual(result, False)", " def test_flush_some_multiple_buffers_first_empty(self):\n inst, sock, map = self._makeOneWithMap()\n sock.send = lambda x: len(x)\n buffer = DummyBuffer(b\"abc\")\n inst.outbufs.append(buffer)\n inst.total_outbufs_len = sum(len(x) for x in inst.outbufs)\n result = inst._flush_some()\n self.assertEqual(result, True)\n self.assertEqual(buffer.skipped, 3)\n self.assertEqual(inst.outbufs, [buffer])", " def test_flush_some_multiple_buffers_close_raises(self):\n inst, sock, map = self._makeOneWithMap()\n sock.send = lambda x: len(x)\n buffer = DummyBuffer(b\"abc\")\n inst.outbufs.append(buffer)\n inst.total_outbufs_len = sum(len(x) for x in inst.outbufs)\n inst.logger = DummyLogger()", " def doraise():\n raise NotImplementedError", " inst.outbufs[0].close = doraise\n result = inst._flush_some()\n self.assertEqual(result, True)\n self.assertEqual(buffer.skipped, 3)\n self.assertEqual(inst.outbufs, [buffer])\n self.assertEqual(len(inst.logger.exceptions), 1)", " def test__flush_some_outbuf_len_gt_sys_maxint(self):\n from waitress.compat import MAXINT", " inst, sock, map = self._makeOneWithMap()", " class DummyHugeOutbuffer(object):\n def __init__(self):\n self.length = MAXINT + 1", " def __len__(self):\n return self.length", " def get(self, numbytes):\n self.length = 0\n return b\"123\"", " buf = DummyHugeOutbuffer()\n inst.outbufs = [buf]\n inst.send = lambda *arg: 0\n result = inst._flush_some()\n # we are testing that _flush_some doesn't raise an OverflowError\n # when one of its outbufs has a __len__ that returns gt sys.maxint\n self.assertEqual(result, False)", " def test_handle_close(self):\n inst, sock, map = self._makeOneWithMap()\n inst.handle_close()\n self.assertEqual(inst.connected, False)\n self.assertEqual(sock.closed, True)", " def test_handle_close_outbuf_raises_on_close(self):\n inst, sock, map = self._makeOneWithMap()", " def doraise():\n raise NotImplementedError", " inst.outbufs[0].close = doraise\n inst.logger = DummyLogger()\n inst.handle_close()\n self.assertEqual(inst.connected, False)\n self.assertEqual(sock.closed, True)\n self.assertEqual(len(inst.logger.exceptions), 1)", " def test_add_channel(self):\n inst, sock, map = self._makeOneWithMap()\n fileno = inst._fileno\n inst.add_channel(map)\n self.assertEqual(map[fileno], inst)\n self.assertEqual(inst.server.active_channels[fileno], inst)", " def test_del_channel(self):\n inst, sock, map = self._makeOneWithMap()\n fileno = inst._fileno\n inst.server.active_channels[fileno] = True\n inst.del_channel(map)\n self.assertEqual(map.get(fileno), None)\n self.assertEqual(inst.server.active_channels.get(fileno), None)", " def test_received(self):\n inst, sock, map = self._makeOneWithMap()\n inst.server = DummyServer()", " inst.received(b\"GET / HTTP/1.1\\n\\n\")", " self.assertEqual(inst.server.tasks, [inst])\n self.assertTrue(inst.requests)", " def test_received_no_chunk(self):\n inst, sock, map = self._makeOneWithMap()\n self.assertEqual(inst.received(b\"\"), False)", " def test_received_preq_not_completed(self):\n inst, sock, map = self._makeOneWithMap()\n inst.server = DummyServer()\n preq = DummyParser()\n inst.request = preq\n preq.completed = False\n preq.empty = True", " inst.received(b\"GET / HTTP/1.1\\n\\n\")", " self.assertEqual(inst.requests, ())\n self.assertEqual(inst.server.tasks, [])", " def test_received_preq_completed_empty(self):\n inst, sock, map = self._makeOneWithMap()\n inst.server = DummyServer()\n preq = DummyParser()\n inst.request = preq\n preq.completed = True\n preq.empty = True", " inst.received(b\"GET / HTTP/1.1\\n\\n\")", " self.assertEqual(inst.request, None)\n self.assertEqual(inst.server.tasks, [])", " def test_received_preq_error(self):\n inst, sock, map = self._makeOneWithMap()\n inst.server = DummyServer()\n preq = DummyParser()\n inst.request = preq\n preq.completed = True\n preq.error = True", " inst.received(b\"GET / HTTP/1.1\\n\\n\")", " self.assertEqual(inst.request, None)\n self.assertEqual(len(inst.server.tasks), 1)\n self.assertTrue(inst.requests)", " def test_received_preq_completed_connection_close(self):\n inst, sock, map = self._makeOneWithMap()\n inst.server = DummyServer()\n preq = DummyParser()\n inst.request = preq\n preq.completed = True\n preq.empty = True\n preq.connection_close = True", " inst.received(b\"GET / HTTP/1.1\\n\\n\" + b\"a\" * 50000)", " self.assertEqual(inst.request, None)\n self.assertEqual(inst.server.tasks, [])", "\n def test_received_preq_completed_n_lt_data(self):\n inst, sock, map = self._makeOneWithMap()\n inst.server = DummyServer()\n preq = DummyParser()\n inst.request = preq\n preq.completed = True\n preq.empty = False\n line = b\"GET / HTTP/1.1\\n\\n\"\n preq.retval = len(line)\n inst.received(line + line)\n self.assertEqual(inst.request, None)\n self.assertEqual(len(inst.requests), 2)\n self.assertEqual(len(inst.server.tasks), 1)", "\n def test_received_headers_finished_expect_continue_false(self):\n inst, sock, map = self._makeOneWithMap()\n inst.server = DummyServer()\n preq = DummyParser()\n inst.request = preq\n preq.expect_continue = False\n preq.headers_finished = True\n preq.completed = False\n preq.empty = False\n preq.retval = 1", " inst.received(b\"GET / HTTP/1.1\\n\\n\")", " self.assertEqual(inst.request, preq)\n self.assertEqual(inst.server.tasks, [])\n self.assertEqual(inst.outbufs[0].get(100), b\"\")", " def test_received_headers_finished_expect_continue_true(self):\n inst, sock, map = self._makeOneWithMap()\n inst.server = DummyServer()\n preq = DummyParser()\n inst.request = preq\n preq.expect_continue = True\n preq.headers_finished = True\n preq.completed = False\n preq.empty = False", " inst.received(b\"GET / HTTP/1.1\\n\\n\")", " self.assertEqual(inst.request, preq)\n self.assertEqual(inst.server.tasks, [])\n self.assertEqual(sock.sent, b\"HTTP/1.1 100 Continue\\r\\n\\r\\n\")\n self.assertEqual(inst.sent_continue, True)\n self.assertEqual(preq.completed, False)", " def test_received_headers_finished_expect_continue_true_sent_true(self):\n inst, sock, map = self._makeOneWithMap()\n inst.server = DummyServer()\n preq = DummyParser()\n inst.request = preq\n preq.expect_continue = True\n preq.headers_finished = True\n preq.completed = False\n preq.empty = False\n inst.sent_continue = True", " inst.received(b\"GET / HTTP/1.1\\n\\n\")", " self.assertEqual(inst.request, preq)\n self.assertEqual(inst.server.tasks, [])\n self.assertEqual(sock.sent, b\"\")\n self.assertEqual(inst.sent_continue, True)\n self.assertEqual(preq.completed, False)", " def test_service_no_requests(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = []\n inst.service()\n self.assertEqual(inst.requests, [])\n self.assertTrue(inst.server.trigger_pulled)\n self.assertTrue(inst.last_activity)", " def test_service_with_one_request(self):\n inst, sock, map = self._makeOneWithMap()\n request = DummyRequest()\n inst.task_class = DummyTaskClass()\n inst.requests = [request]\n inst.service()\n self.assertEqual(inst.requests, [])\n self.assertTrue(request.serviced)\n self.assertTrue(request.closed)", " def test_service_with_one_error_request(self):\n inst, sock, map = self._makeOneWithMap()\n request = DummyRequest()\n request.error = DummyError()\n inst.error_task_class = DummyTaskClass()\n inst.requests = [request]\n inst.service()\n self.assertEqual(inst.requests, [])\n self.assertTrue(request.serviced)\n self.assertTrue(request.closed)", " def test_service_with_multiple_requests(self):\n inst, sock, map = self._makeOneWithMap()\n request1 = DummyRequest()\n request2 = DummyRequest()\n inst.task_class = DummyTaskClass()\n inst.requests = [request1, request2]\n inst.service()\n self.assertEqual(inst.requests, [])\n self.assertTrue(request1.serviced)\n self.assertTrue(request2.serviced)\n self.assertTrue(request1.closed)\n self.assertTrue(request2.closed)", " def test_service_with_request_raises(self):\n inst, sock, map = self._makeOneWithMap()\n inst.adj.expose_tracebacks = False\n inst.server = DummyServer()\n request = DummyRequest()\n inst.requests = [request]\n inst.task_class = DummyTaskClass(ValueError)\n inst.task_class.wrote_header = False\n inst.error_task_class = DummyTaskClass()\n inst.logger = DummyLogger()\n inst.service()\n self.assertTrue(request.serviced)\n self.assertEqual(inst.requests, [])\n self.assertEqual(len(inst.logger.exceptions), 1)\n self.assertTrue(inst.server.trigger_pulled)\n self.assertTrue(inst.last_activity)\n self.assertFalse(inst.will_close)\n self.assertEqual(inst.error_task_class.serviced, True)\n self.assertTrue(request.closed)", " def test_service_with_requests_raises_already_wrote_header(self):\n inst, sock, map = self._makeOneWithMap()\n inst.adj.expose_tracebacks = False\n inst.server = DummyServer()\n request = DummyRequest()\n inst.requests = [request]\n inst.task_class = DummyTaskClass(ValueError)\n inst.error_task_class = DummyTaskClass()\n inst.logger = DummyLogger()\n inst.service()\n self.assertTrue(request.serviced)\n self.assertEqual(inst.requests, [])\n self.assertEqual(len(inst.logger.exceptions), 1)\n self.assertTrue(inst.server.trigger_pulled)\n self.assertTrue(inst.last_activity)\n self.assertTrue(inst.close_when_flushed)\n self.assertEqual(inst.error_task_class.serviced, False)\n self.assertTrue(request.closed)", " def test_service_with_requests_raises_didnt_write_header_expose_tbs(self):\n inst, sock, map = self._makeOneWithMap()\n inst.adj.expose_tracebacks = True\n inst.server = DummyServer()\n request = DummyRequest()\n inst.requests = [request]\n inst.task_class = DummyTaskClass(ValueError)\n inst.task_class.wrote_header = False\n inst.error_task_class = DummyTaskClass()\n inst.logger = DummyLogger()\n inst.service()\n self.assertTrue(request.serviced)\n self.assertFalse(inst.will_close)\n self.assertEqual(inst.requests, [])\n self.assertEqual(len(inst.logger.exceptions), 1)\n self.assertTrue(inst.server.trigger_pulled)\n self.assertTrue(inst.last_activity)\n self.assertEqual(inst.error_task_class.serviced, True)\n self.assertTrue(request.closed)", " def test_service_with_requests_raises_didnt_write_header(self):\n inst, sock, map = self._makeOneWithMap()\n inst.adj.expose_tracebacks = False\n inst.server = DummyServer()\n request = DummyRequest()\n inst.requests = [request]\n inst.task_class = DummyTaskClass(ValueError)\n inst.task_class.wrote_header = False\n inst.logger = DummyLogger()\n inst.service()\n self.assertTrue(request.serviced)\n self.assertEqual(inst.requests, [])\n self.assertEqual(len(inst.logger.exceptions), 1)\n self.assertTrue(inst.server.trigger_pulled)\n self.assertTrue(inst.last_activity)\n self.assertTrue(inst.close_when_flushed)\n self.assertTrue(request.closed)", " def test_service_with_request_raises_disconnect(self):\n from waitress.channel import ClientDisconnected", " inst, sock, map = self._makeOneWithMap()\n inst.adj.expose_tracebacks = False\n inst.server = DummyServer()\n request = DummyRequest()\n inst.requests = [request]\n inst.task_class = DummyTaskClass(ClientDisconnected)\n inst.error_task_class = DummyTaskClass()\n inst.logger = DummyLogger()\n inst.service()\n self.assertTrue(request.serviced)\n self.assertEqual(inst.requests, [])\n self.assertEqual(len(inst.logger.infos), 1)\n self.assertTrue(inst.server.trigger_pulled)\n self.assertTrue(inst.last_activity)\n self.assertFalse(inst.will_close)\n self.assertEqual(inst.error_task_class.serviced, False)\n self.assertTrue(request.closed)", " def test_service_with_request_error_raises_disconnect(self):\n from waitress.channel import ClientDisconnected", " inst, sock, map = self._makeOneWithMap()\n inst.adj.expose_tracebacks = False\n inst.server = DummyServer()\n request = DummyRequest()\n err_request = DummyRequest()\n inst.requests = [request]\n inst.parser_class = lambda x: err_request\n inst.task_class = DummyTaskClass(RuntimeError)\n inst.task_class.wrote_header = False\n inst.error_task_class = DummyTaskClass(ClientDisconnected)\n inst.logger = DummyLogger()\n inst.service()\n self.assertTrue(request.serviced)\n self.assertTrue(err_request.serviced)\n self.assertEqual(inst.requests, [])\n self.assertEqual(len(inst.logger.exceptions), 1)\n self.assertEqual(len(inst.logger.infos), 0)\n self.assertTrue(inst.server.trigger_pulled)\n self.assertTrue(inst.last_activity)\n self.assertFalse(inst.will_close)\n self.assertEqual(inst.task_class.serviced, True)\n self.assertEqual(inst.error_task_class.serviced, True)\n self.assertTrue(request.closed)", " def test_cancel_no_requests(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = ()\n inst.cancel()\n self.assertEqual(inst.requests, [])", " def test_cancel_with_requests(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = [None]\n inst.cancel()\n self.assertEqual(inst.requests, [])", "\nclass DummySock(object):\n blocking = False\n closed = False", " def __init__(self):\n self.sent = b\"\"", " def setblocking(self, *arg):\n self.blocking = True", " def fileno(self):\n return 100", " def getpeername(self):\n return \"127.0.0.1\"", " def getsockopt(self, level, option):\n return 2048", " def close(self):\n self.closed = True", " def send(self, data):\n self.sent += data\n return len(data)", "\nclass DummyLock(object):\n notified = False", " def __init__(self, acquirable=True):\n self.acquirable = acquirable", " def acquire(self, val):\n self.val = val\n self.acquired = True\n return self.acquirable", " def release(self):\n self.released = True", " def notify(self):\n self.notified = True", " def wait(self):\n self.waited = True", " def __exit__(self, type, val, traceback):\n self.acquire(True)", " def __enter__(self):\n pass", "\nclass DummyBuffer(object):\n closed = False", " def __init__(self, data, toraise=None):\n self.data = data\n self.toraise = toraise", " def get(self, *arg):\n if self.toraise:\n raise self.toraise\n data = self.data\n self.data = b\"\"\n return data", " def skip(self, num, x):\n self.skipped = num", " def __len__(self):\n return len(self.data)", " def close(self):\n self.closed = True", "\nclass DummyAdjustments(object):\n outbuf_overflow = 1048576\n outbuf_high_watermark = 1048576\n inbuf_overflow = 512000\n cleanup_interval = 900\n url_scheme = \"http\"\n channel_timeout = 300\n log_socket_errors = True\n recv_bytes = 8192\n send_bytes = 1\n expose_tracebacks = True\n ident = \"waitress\"\n max_request_header_size = 10000", "\nclass DummyServer(object):\n trigger_pulled = False\n adj = DummyAdjustments()", " def __init__(self):\n self.tasks = []\n self.active_channels = {}", " def add_task(self, task):\n self.tasks.append(task)", " def pull_trigger(self):\n self.trigger_pulled = True", "\nclass DummyParser(object):\n version = 1\n data = None\n completed = True\n empty = False\n headers_finished = False\n expect_continue = False\n retval = None\n error = None\n connection_close = False", " def received(self, data):\n self.data = data\n if self.retval is not None:\n return self.retval\n return len(data)", "\nclass DummyRequest(object):\n error = None\n path = \"/\"\n version = \"1.0\"\n closed = False", " def __init__(self):\n self.headers = {}", " def close(self):\n self.closed = True", "\nclass DummyLogger(object):\n def __init__(self):\n self.exceptions = []\n self.infos = []\n self.warnings = []", " def info(self, msg):\n self.infos.append(msg)", " def exception(self, msg):\n self.exceptions.append(msg)", "\nclass DummyError(object):\n code = \"431\"\n reason = \"Bleh\"\n body = \"My body\"", "\nclass DummyTaskClass(object):\n wrote_header = True\n close_on_finish = False\n serviced = False", " def __init__(self, toraise=None):\n self.toraise = toraise", " def __call__(self, channel, request):\n self.request = request\n return self", " def service(self):\n self.serviced = True\n self.request.serviced = True\n if self.toraise:\n raise self.toraise" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "import unittest\nimport io", "\nclass TestHTTPChannel(unittest.TestCase):\n def _makeOne(self, sock, addr, adj, map=None):\n from waitress.channel import HTTPChannel", " server = DummyServer()\n return HTTPChannel(server, sock, addr, adj=adj, map=map)", " def _makeOneWithMap(self, adj=None):\n if adj is None:\n adj = DummyAdjustments()\n sock = DummySock()\n map = {}\n inst = self._makeOne(sock, \"127.0.0.1\", adj, map=map)\n inst.outbuf_lock = DummyLock()\n return inst, sock, map", " def test_ctor(self):\n inst, _, map = self._makeOneWithMap()\n self.assertEqual(inst.addr, \"127.0.0.1\")\n self.assertEqual(inst.sendbuf_len, 2048)\n self.assertEqual(map[100], inst)", " def test_total_outbufs_len_an_outbuf_size_gt_sys_maxint(self):\n from waitress.compat import MAXINT", " inst, _, map = self._makeOneWithMap()", " class DummyBuffer(object):\n chunks = []", " def append(self, data):\n self.chunks.append(data)", " class DummyData(object):\n def __len__(self):\n return MAXINT", " inst.total_outbufs_len = 1\n inst.outbufs = [DummyBuffer()]\n inst.write_soon(DummyData())\n # we are testing that this method does not raise an OverflowError\n # (see https://github.com/Pylons/waitress/issues/47)\n self.assertEqual(inst.total_outbufs_len, MAXINT + 1)", " def test_writable_something_in_outbuf(self):\n inst, sock, map = self._makeOneWithMap()\n inst.total_outbufs_len = 3\n self.assertTrue(inst.writable())", " def test_writable_nothing_in_outbuf(self):\n inst, sock, map = self._makeOneWithMap()\n self.assertFalse(inst.writable())", " def test_writable_nothing_in_outbuf_will_close(self):\n inst, sock, map = self._makeOneWithMap()\n inst.will_close = True\n self.assertTrue(inst.writable())", " def test_handle_write_not_connected(self):\n inst, sock, map = self._makeOneWithMap()\n inst.connected = False\n self.assertFalse(inst.handle_write())", " def test_handle_write_with_requests(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = True\n inst.last_activity = 0\n result = inst.handle_write()\n self.assertEqual(result, None)\n self.assertEqual(inst.last_activity, 0)", " def test_handle_write_no_request_with_outbuf(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = []\n inst.outbufs = [DummyBuffer(b\"abc\")]\n inst.total_outbufs_len = len(inst.outbufs[0])\n inst.last_activity = 0\n result = inst.handle_write()\n self.assertEqual(result, None)\n self.assertNotEqual(inst.last_activity, 0)\n self.assertEqual(sock.sent, b\"abc\")", " def test_handle_write_outbuf_raises_socketerror(self):\n import socket", " inst, sock, map = self._makeOneWithMap()\n inst.requests = []\n outbuf = DummyBuffer(b\"abc\", socket.error)\n inst.outbufs = [outbuf]\n inst.total_outbufs_len = len(outbuf)\n inst.last_activity = 0\n inst.logger = DummyLogger()\n result = inst.handle_write()\n self.assertEqual(result, None)\n self.assertEqual(inst.last_activity, 0)\n self.assertEqual(sock.sent, b\"\")\n self.assertEqual(len(inst.logger.exceptions), 1)\n self.assertTrue(outbuf.closed)", " def test_handle_write_outbuf_raises_othererror(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = []\n outbuf = DummyBuffer(b\"abc\", IOError)\n inst.outbufs = [outbuf]\n inst.total_outbufs_len = len(outbuf)\n inst.last_activity = 0\n inst.logger = DummyLogger()\n result = inst.handle_write()\n self.assertEqual(result, None)\n self.assertEqual(inst.last_activity, 0)\n self.assertEqual(sock.sent, b\"\")\n self.assertEqual(len(inst.logger.exceptions), 1)\n self.assertTrue(outbuf.closed)", " def test_handle_write_no_requests_no_outbuf_will_close(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = []\n outbuf = DummyBuffer(b\"\")\n inst.outbufs = [outbuf]\n inst.will_close = True\n inst.last_activity = 0\n result = inst.handle_write()\n self.assertEqual(result, None)\n self.assertEqual(inst.connected, False)\n self.assertEqual(sock.closed, True)\n self.assertEqual(inst.last_activity, 0)\n self.assertTrue(outbuf.closed)", " def test_handle_write_no_requests_outbuf_gt_send_bytes(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = [True]\n inst.outbufs = [DummyBuffer(b\"abc\")]\n inst.total_outbufs_len = len(inst.outbufs[0])\n inst.adj.send_bytes = 2\n inst.will_close = False\n inst.last_activity = 0\n result = inst.handle_write()\n self.assertEqual(result, None)\n self.assertEqual(inst.will_close, False)\n self.assertTrue(inst.outbuf_lock.acquired)\n self.assertEqual(sock.sent, b\"abc\")", " def test_handle_write_close_when_flushed(self):\n inst, sock, map = self._makeOneWithMap()\n outbuf = DummyBuffer(b\"abc\")\n inst.outbufs = [outbuf]\n inst.total_outbufs_len = len(outbuf)\n inst.will_close = False\n inst.close_when_flushed = True\n inst.last_activity = 0\n result = inst.handle_write()\n self.assertEqual(result, None)\n self.assertEqual(inst.will_close, True)\n self.assertEqual(inst.close_when_flushed, False)\n self.assertEqual(sock.sent, b\"abc\")\n self.assertTrue(outbuf.closed)", " def test_readable_no_requests_not_will_close(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = []\n inst.will_close = False\n self.assertEqual(inst.readable(), True)", " def test_readable_no_requests_will_close(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = []\n inst.will_close = True\n self.assertEqual(inst.readable(), False)", " def test_readable_with_requests(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = True\n self.assertEqual(inst.readable(), False)", " def test_handle_read_no_error(self):\n inst, sock, map = self._makeOneWithMap()\n inst.will_close = False\n inst.recv = lambda *arg: b\"abc\"\n inst.last_activity = 0\n L = []\n inst.received = lambda x: L.append(x)\n result = inst.handle_read()\n self.assertEqual(result, None)\n self.assertNotEqual(inst.last_activity, 0)\n self.assertEqual(L, [b\"abc\"])", " def test_handle_read_error(self):\n import socket", " inst, sock, map = self._makeOneWithMap()\n inst.will_close = False", " def recv(b):\n raise socket.error", " inst.recv = recv\n inst.last_activity = 0\n inst.logger = DummyLogger()\n result = inst.handle_read()\n self.assertEqual(result, None)\n self.assertEqual(inst.last_activity, 0)\n self.assertEqual(len(inst.logger.exceptions), 1)", " def test_write_soon_empty_byte(self):\n inst, sock, map = self._makeOneWithMap()\n wrote = inst.write_soon(b\"\")\n self.assertEqual(wrote, 0)\n self.assertEqual(len(inst.outbufs[0]), 0)", " def test_write_soon_nonempty_byte(self):\n inst, sock, map = self._makeOneWithMap()\n wrote = inst.write_soon(b\"a\")\n self.assertEqual(wrote, 1)\n self.assertEqual(len(inst.outbufs[0]), 1)", " def test_write_soon_filewrapper(self):\n from waitress.buffers import ReadOnlyFileBasedBuffer", " f = io.BytesIO(b\"abc\")\n wrapper = ReadOnlyFileBasedBuffer(f, 8192)\n wrapper.prepare()\n inst, sock, map = self._makeOneWithMap()\n outbufs = inst.outbufs\n orig_outbuf = outbufs[0]\n wrote = inst.write_soon(wrapper)\n self.assertEqual(wrote, 3)\n self.assertEqual(len(outbufs), 3)\n self.assertEqual(outbufs[0], orig_outbuf)\n self.assertEqual(outbufs[1], wrapper)\n self.assertEqual(outbufs[2].__class__.__name__, \"OverflowableBuffer\")", " def test_write_soon_disconnected(self):\n from waitress.channel import ClientDisconnected", " inst, sock, map = self._makeOneWithMap()\n inst.connected = False\n self.assertRaises(ClientDisconnected, lambda: inst.write_soon(b\"stuff\"))", " def test_write_soon_disconnected_while_over_watermark(self):\n from waitress.channel import ClientDisconnected", " inst, sock, map = self._makeOneWithMap()", " def dummy_flush():\n inst.connected = False", " inst._flush_outbufs_below_high_watermark = dummy_flush\n self.assertRaises(ClientDisconnected, lambda: inst.write_soon(b\"stuff\"))", " def test_write_soon_rotates_outbuf_on_overflow(self):\n inst, sock, map = self._makeOneWithMap()\n inst.adj.outbuf_high_watermark = 3\n inst.current_outbuf_count = 4\n wrote = inst.write_soon(b\"xyz\")\n self.assertEqual(wrote, 3)\n self.assertEqual(len(inst.outbufs), 2)\n self.assertEqual(inst.outbufs[0].get(), b\"\")\n self.assertEqual(inst.outbufs[1].get(), b\"xyz\")", " def test_write_soon_waits_on_backpressure(self):\n inst, sock, map = self._makeOneWithMap()\n inst.adj.outbuf_high_watermark = 3\n inst.total_outbufs_len = 4\n inst.current_outbuf_count = 4", " class Lock(DummyLock):\n def wait(self):\n inst.total_outbufs_len = 0\n super(Lock, self).wait()", " inst.outbuf_lock = Lock()\n wrote = inst.write_soon(b\"xyz\")\n self.assertEqual(wrote, 3)\n self.assertEqual(len(inst.outbufs), 2)\n self.assertEqual(inst.outbufs[0].get(), b\"\")\n self.assertEqual(inst.outbufs[1].get(), b\"xyz\")\n self.assertTrue(inst.outbuf_lock.waited)", " def test_handle_write_notify_after_flush(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = [True]\n inst.outbufs = [DummyBuffer(b\"abc\")]\n inst.total_outbufs_len = len(inst.outbufs[0])\n inst.adj.send_bytes = 1\n inst.adj.outbuf_high_watermark = 5\n inst.will_close = False\n inst.last_activity = 0\n result = inst.handle_write()\n self.assertEqual(result, None)\n self.assertEqual(inst.will_close, False)\n self.assertTrue(inst.outbuf_lock.acquired)\n self.assertTrue(inst.outbuf_lock.notified)\n self.assertEqual(sock.sent, b\"abc\")", " def test_handle_write_no_notify_after_flush(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = [True]\n inst.outbufs = [DummyBuffer(b\"abc\")]\n inst.total_outbufs_len = len(inst.outbufs[0])\n inst.adj.send_bytes = 1\n inst.adj.outbuf_high_watermark = 2\n sock.send = lambda x: False\n inst.will_close = False\n inst.last_activity = 0\n result = inst.handle_write()\n self.assertEqual(result, None)\n self.assertEqual(inst.will_close, False)\n self.assertTrue(inst.outbuf_lock.acquired)\n self.assertFalse(inst.outbuf_lock.notified)\n self.assertEqual(sock.sent, b\"\")", " def test__flush_some_empty_outbuf(self):\n inst, sock, map = self._makeOneWithMap()\n result = inst._flush_some()\n self.assertEqual(result, False)", " def test__flush_some_full_outbuf_socket_returns_nonzero(self):\n inst, sock, map = self._makeOneWithMap()\n inst.outbufs[0].append(b\"abc\")\n inst.total_outbufs_len = sum(len(x) for x in inst.outbufs)\n result = inst._flush_some()\n self.assertEqual(result, True)", " def test__flush_some_full_outbuf_socket_returns_zero(self):\n inst, sock, map = self._makeOneWithMap()\n sock.send = lambda x: False\n inst.outbufs[0].append(b\"abc\")\n inst.total_outbufs_len = sum(len(x) for x in inst.outbufs)\n result = inst._flush_some()\n self.assertEqual(result, False)", " def test_flush_some_multiple_buffers_first_empty(self):\n inst, sock, map = self._makeOneWithMap()\n sock.send = lambda x: len(x)\n buffer = DummyBuffer(b\"abc\")\n inst.outbufs.append(buffer)\n inst.total_outbufs_len = sum(len(x) for x in inst.outbufs)\n result = inst._flush_some()\n self.assertEqual(result, True)\n self.assertEqual(buffer.skipped, 3)\n self.assertEqual(inst.outbufs, [buffer])", " def test_flush_some_multiple_buffers_close_raises(self):\n inst, sock, map = self._makeOneWithMap()\n sock.send = lambda x: len(x)\n buffer = DummyBuffer(b\"abc\")\n inst.outbufs.append(buffer)\n inst.total_outbufs_len = sum(len(x) for x in inst.outbufs)\n inst.logger = DummyLogger()", " def doraise():\n raise NotImplementedError", " inst.outbufs[0].close = doraise\n result = inst._flush_some()\n self.assertEqual(result, True)\n self.assertEqual(buffer.skipped, 3)\n self.assertEqual(inst.outbufs, [buffer])\n self.assertEqual(len(inst.logger.exceptions), 1)", " def test__flush_some_outbuf_len_gt_sys_maxint(self):\n from waitress.compat import MAXINT", " inst, sock, map = self._makeOneWithMap()", " class DummyHugeOutbuffer(object):\n def __init__(self):\n self.length = MAXINT + 1", " def __len__(self):\n return self.length", " def get(self, numbytes):\n self.length = 0\n return b\"123\"", " buf = DummyHugeOutbuffer()\n inst.outbufs = [buf]\n inst.send = lambda *arg: 0\n result = inst._flush_some()\n # we are testing that _flush_some doesn't raise an OverflowError\n # when one of its outbufs has a __len__ that returns gt sys.maxint\n self.assertEqual(result, False)", " def test_handle_close(self):\n inst, sock, map = self._makeOneWithMap()\n inst.handle_close()\n self.assertEqual(inst.connected, False)\n self.assertEqual(sock.closed, True)", " def test_handle_close_outbuf_raises_on_close(self):\n inst, sock, map = self._makeOneWithMap()", " def doraise():\n raise NotImplementedError", " inst.outbufs[0].close = doraise\n inst.logger = DummyLogger()\n inst.handle_close()\n self.assertEqual(inst.connected, False)\n self.assertEqual(sock.closed, True)\n self.assertEqual(len(inst.logger.exceptions), 1)", " def test_add_channel(self):\n inst, sock, map = self._makeOneWithMap()\n fileno = inst._fileno\n inst.add_channel(map)\n self.assertEqual(map[fileno], inst)\n self.assertEqual(inst.server.active_channels[fileno], inst)", " def test_del_channel(self):\n inst, sock, map = self._makeOneWithMap()\n fileno = inst._fileno\n inst.server.active_channels[fileno] = True\n inst.del_channel(map)\n self.assertEqual(map.get(fileno), None)\n self.assertEqual(inst.server.active_channels.get(fileno), None)", " def test_received(self):\n inst, sock, map = self._makeOneWithMap()\n inst.server = DummyServer()", " inst.received(b\"GET / HTTP/1.1\\r\\n\\r\\n\")", " self.assertEqual(inst.server.tasks, [inst])\n self.assertTrue(inst.requests)", " def test_received_no_chunk(self):\n inst, sock, map = self._makeOneWithMap()\n self.assertEqual(inst.received(b\"\"), False)", " def test_received_preq_not_completed(self):\n inst, sock, map = self._makeOneWithMap()\n inst.server = DummyServer()\n preq = DummyParser()\n inst.request = preq\n preq.completed = False\n preq.empty = True", " inst.received(b\"GET / HTTP/1.1\\r\\n\\r\\n\")", " self.assertEqual(inst.requests, ())\n self.assertEqual(inst.server.tasks, [])", " def test_received_preq_completed_empty(self):\n inst, sock, map = self._makeOneWithMap()\n inst.server = DummyServer()\n preq = DummyParser()\n inst.request = preq\n preq.completed = True\n preq.empty = True", " inst.received(b\"GET / HTTP/1.1\\r\\n\\r\\n\")", " self.assertEqual(inst.request, None)\n self.assertEqual(inst.server.tasks, [])", " def test_received_preq_error(self):\n inst, sock, map = self._makeOneWithMap()\n inst.server = DummyServer()\n preq = DummyParser()\n inst.request = preq\n preq.completed = True\n preq.error = True", " inst.received(b\"GET / HTTP/1.1\\r\\n\\r\\n\")", " self.assertEqual(inst.request, None)\n self.assertEqual(len(inst.server.tasks), 1)\n self.assertTrue(inst.requests)", " def test_received_preq_completed_connection_close(self):\n inst, sock, map = self._makeOneWithMap()\n inst.server = DummyServer()\n preq = DummyParser()\n inst.request = preq\n preq.completed = True\n preq.empty = True\n preq.connection_close = True", " inst.received(b\"GET / HTTP/1.1\\r\\n\\r\\n\" + b\"a\" * 50000)", " self.assertEqual(inst.request, None)\n self.assertEqual(inst.server.tasks, [])", "", "\n def test_received_headers_finished_expect_continue_false(self):\n inst, sock, map = self._makeOneWithMap()\n inst.server = DummyServer()\n preq = DummyParser()\n inst.request = preq\n preq.expect_continue = False\n preq.headers_finished = True\n preq.completed = False\n preq.empty = False\n preq.retval = 1", " inst.received(b\"GET / HTTP/1.1\\r\\n\\r\\n\")", " self.assertEqual(inst.request, preq)\n self.assertEqual(inst.server.tasks, [])\n self.assertEqual(inst.outbufs[0].get(100), b\"\")", " def test_received_headers_finished_expect_continue_true(self):\n inst, sock, map = self._makeOneWithMap()\n inst.server = DummyServer()\n preq = DummyParser()\n inst.request = preq\n preq.expect_continue = True\n preq.headers_finished = True\n preq.completed = False\n preq.empty = False", " inst.received(b\"GET / HTTP/1.1\\r\\n\\r\\n\")", " self.assertEqual(inst.request, preq)\n self.assertEqual(inst.server.tasks, [])\n self.assertEqual(sock.sent, b\"HTTP/1.1 100 Continue\\r\\n\\r\\n\")\n self.assertEqual(inst.sent_continue, True)\n self.assertEqual(preq.completed, False)", " def test_received_headers_finished_expect_continue_true_sent_true(self):\n inst, sock, map = self._makeOneWithMap()\n inst.server = DummyServer()\n preq = DummyParser()\n inst.request = preq\n preq.expect_continue = True\n preq.headers_finished = True\n preq.completed = False\n preq.empty = False\n inst.sent_continue = True", " inst.received(b\"GET / HTTP/1.1\\r\\n\\r\\n\")", " self.assertEqual(inst.request, preq)\n self.assertEqual(inst.server.tasks, [])\n self.assertEqual(sock.sent, b\"\")\n self.assertEqual(inst.sent_continue, True)\n self.assertEqual(preq.completed, False)", " def test_service_no_requests(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = []\n inst.service()\n self.assertEqual(inst.requests, [])\n self.assertTrue(inst.server.trigger_pulled)\n self.assertTrue(inst.last_activity)", " def test_service_with_one_request(self):\n inst, sock, map = self._makeOneWithMap()\n request = DummyRequest()\n inst.task_class = DummyTaskClass()\n inst.requests = [request]\n inst.service()\n self.assertEqual(inst.requests, [])\n self.assertTrue(request.serviced)\n self.assertTrue(request.closed)", " def test_service_with_one_error_request(self):\n inst, sock, map = self._makeOneWithMap()\n request = DummyRequest()\n request.error = DummyError()\n inst.error_task_class = DummyTaskClass()\n inst.requests = [request]\n inst.service()\n self.assertEqual(inst.requests, [])\n self.assertTrue(request.serviced)\n self.assertTrue(request.closed)", " def test_service_with_multiple_requests(self):\n inst, sock, map = self._makeOneWithMap()\n request1 = DummyRequest()\n request2 = DummyRequest()\n inst.task_class = DummyTaskClass()\n inst.requests = [request1, request2]\n inst.service()\n self.assertEqual(inst.requests, [])\n self.assertTrue(request1.serviced)\n self.assertTrue(request2.serviced)\n self.assertTrue(request1.closed)\n self.assertTrue(request2.closed)", " def test_service_with_request_raises(self):\n inst, sock, map = self._makeOneWithMap()\n inst.adj.expose_tracebacks = False\n inst.server = DummyServer()\n request = DummyRequest()\n inst.requests = [request]\n inst.task_class = DummyTaskClass(ValueError)\n inst.task_class.wrote_header = False\n inst.error_task_class = DummyTaskClass()\n inst.logger = DummyLogger()\n inst.service()\n self.assertTrue(request.serviced)\n self.assertEqual(inst.requests, [])\n self.assertEqual(len(inst.logger.exceptions), 1)\n self.assertTrue(inst.server.trigger_pulled)\n self.assertTrue(inst.last_activity)\n self.assertFalse(inst.will_close)\n self.assertEqual(inst.error_task_class.serviced, True)\n self.assertTrue(request.closed)", " def test_service_with_requests_raises_already_wrote_header(self):\n inst, sock, map = self._makeOneWithMap()\n inst.adj.expose_tracebacks = False\n inst.server = DummyServer()\n request = DummyRequest()\n inst.requests = [request]\n inst.task_class = DummyTaskClass(ValueError)\n inst.error_task_class = DummyTaskClass()\n inst.logger = DummyLogger()\n inst.service()\n self.assertTrue(request.serviced)\n self.assertEqual(inst.requests, [])\n self.assertEqual(len(inst.logger.exceptions), 1)\n self.assertTrue(inst.server.trigger_pulled)\n self.assertTrue(inst.last_activity)\n self.assertTrue(inst.close_when_flushed)\n self.assertEqual(inst.error_task_class.serviced, False)\n self.assertTrue(request.closed)", " def test_service_with_requests_raises_didnt_write_header_expose_tbs(self):\n inst, sock, map = self._makeOneWithMap()\n inst.adj.expose_tracebacks = True\n inst.server = DummyServer()\n request = DummyRequest()\n inst.requests = [request]\n inst.task_class = DummyTaskClass(ValueError)\n inst.task_class.wrote_header = False\n inst.error_task_class = DummyTaskClass()\n inst.logger = DummyLogger()\n inst.service()\n self.assertTrue(request.serviced)\n self.assertFalse(inst.will_close)\n self.assertEqual(inst.requests, [])\n self.assertEqual(len(inst.logger.exceptions), 1)\n self.assertTrue(inst.server.trigger_pulled)\n self.assertTrue(inst.last_activity)\n self.assertEqual(inst.error_task_class.serviced, True)\n self.assertTrue(request.closed)", " def test_service_with_requests_raises_didnt_write_header(self):\n inst, sock, map = self._makeOneWithMap()\n inst.adj.expose_tracebacks = False\n inst.server = DummyServer()\n request = DummyRequest()\n inst.requests = [request]\n inst.task_class = DummyTaskClass(ValueError)\n inst.task_class.wrote_header = False\n inst.logger = DummyLogger()\n inst.service()\n self.assertTrue(request.serviced)\n self.assertEqual(inst.requests, [])\n self.assertEqual(len(inst.logger.exceptions), 1)\n self.assertTrue(inst.server.trigger_pulled)\n self.assertTrue(inst.last_activity)\n self.assertTrue(inst.close_when_flushed)\n self.assertTrue(request.closed)", " def test_service_with_request_raises_disconnect(self):\n from waitress.channel import ClientDisconnected", " inst, sock, map = self._makeOneWithMap()\n inst.adj.expose_tracebacks = False\n inst.server = DummyServer()\n request = DummyRequest()\n inst.requests = [request]\n inst.task_class = DummyTaskClass(ClientDisconnected)\n inst.error_task_class = DummyTaskClass()\n inst.logger = DummyLogger()\n inst.service()\n self.assertTrue(request.serviced)\n self.assertEqual(inst.requests, [])\n self.assertEqual(len(inst.logger.infos), 1)\n self.assertTrue(inst.server.trigger_pulled)\n self.assertTrue(inst.last_activity)\n self.assertFalse(inst.will_close)\n self.assertEqual(inst.error_task_class.serviced, False)\n self.assertTrue(request.closed)", " def test_service_with_request_error_raises_disconnect(self):\n from waitress.channel import ClientDisconnected", " inst, sock, map = self._makeOneWithMap()\n inst.adj.expose_tracebacks = False\n inst.server = DummyServer()\n request = DummyRequest()\n err_request = DummyRequest()\n inst.requests = [request]\n inst.parser_class = lambda x: err_request\n inst.task_class = DummyTaskClass(RuntimeError)\n inst.task_class.wrote_header = False\n inst.error_task_class = DummyTaskClass(ClientDisconnected)\n inst.logger = DummyLogger()\n inst.service()\n self.assertTrue(request.serviced)\n self.assertTrue(err_request.serviced)\n self.assertEqual(inst.requests, [])\n self.assertEqual(len(inst.logger.exceptions), 1)\n self.assertEqual(len(inst.logger.infos), 0)\n self.assertTrue(inst.server.trigger_pulled)\n self.assertTrue(inst.last_activity)\n self.assertFalse(inst.will_close)\n self.assertEqual(inst.task_class.serviced, True)\n self.assertEqual(inst.error_task_class.serviced, True)\n self.assertTrue(request.closed)", " def test_cancel_no_requests(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = ()\n inst.cancel()\n self.assertEqual(inst.requests, [])", " def test_cancel_with_requests(self):\n inst, sock, map = self._makeOneWithMap()\n inst.requests = [None]\n inst.cancel()\n self.assertEqual(inst.requests, [])", "\nclass DummySock(object):\n blocking = False\n closed = False", " def __init__(self):\n self.sent = b\"\"", " def setblocking(self, *arg):\n self.blocking = True", " def fileno(self):\n return 100", " def getpeername(self):\n return \"127.0.0.1\"", " def getsockopt(self, level, option):\n return 2048", " def close(self):\n self.closed = True", " def send(self, data):\n self.sent += data\n return len(data)", "\nclass DummyLock(object):\n notified = False", " def __init__(self, acquirable=True):\n self.acquirable = acquirable", " def acquire(self, val):\n self.val = val\n self.acquired = True\n return self.acquirable", " def release(self):\n self.released = True", " def notify(self):\n self.notified = True", " def wait(self):\n self.waited = True", " def __exit__(self, type, val, traceback):\n self.acquire(True)", " def __enter__(self):\n pass", "\nclass DummyBuffer(object):\n closed = False", " def __init__(self, data, toraise=None):\n self.data = data\n self.toraise = toraise", " def get(self, *arg):\n if self.toraise:\n raise self.toraise\n data = self.data\n self.data = b\"\"\n return data", " def skip(self, num, x):\n self.skipped = num", " def __len__(self):\n return len(self.data)", " def close(self):\n self.closed = True", "\nclass DummyAdjustments(object):\n outbuf_overflow = 1048576\n outbuf_high_watermark = 1048576\n inbuf_overflow = 512000\n cleanup_interval = 900\n url_scheme = \"http\"\n channel_timeout = 300\n log_socket_errors = True\n recv_bytes = 8192\n send_bytes = 1\n expose_tracebacks = True\n ident = \"waitress\"\n max_request_header_size = 10000", "\nclass DummyServer(object):\n trigger_pulled = False\n adj = DummyAdjustments()", " def __init__(self):\n self.tasks = []\n self.active_channels = {}", " def add_task(self, task):\n self.tasks.append(task)", " def pull_trigger(self):\n self.trigger_pulled = True", "\nclass DummyParser(object):\n version = 1\n data = None\n completed = True\n empty = False\n headers_finished = False\n expect_continue = False\n retval = None\n error = None\n connection_close = False", " def received(self, data):\n self.data = data\n if self.retval is not None:\n return self.retval\n return len(data)", "\nclass DummyRequest(object):\n error = None\n path = \"/\"\n version = \"1.0\"\n closed = False", " def __init__(self):\n self.headers = {}", " def close(self):\n self.closed = True", "\nclass DummyLogger(object):\n def __init__(self):\n self.exceptions = []\n self.infos = []\n self.warnings = []", " def info(self, msg):\n self.infos.append(msg)", " def exception(self, msg):\n self.exceptions.append(msg)", "\nclass DummyError(object):\n code = \"431\"\n reason = \"Bleh\"\n body = \"My body\"", "\nclass DummyTaskClass(object):\n wrote_header = True\n close_on_finish = False\n serviced = False", " def __init__(self, toraise=None):\n self.toraise = toraise", " def __call__(self, channel, request):\n self.request = request\n return self", " def service(self):\n self.serviced = True\n self.request.serviced = True\n if self.toraise:\n raise self.toraise" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "import errno\nimport logging\nimport multiprocessing\nimport os\nimport signal\nimport socket\nimport string\nimport subprocess\nimport sys\nimport time\nimport unittest\nfrom waitress import server\nfrom waitress.compat import httplib, tobytes\nfrom waitress.utilities import cleanup_unix_socket", "dn = os.path.dirname\nhere = dn(__file__)", "\nclass NullHandler(logging.Handler): # pragma: no cover\n \"\"\"A logging handler that swallows all emitted messages.\n \"\"\"", " def emit(self, record):\n pass", "\ndef start_server(app, svr, queue, **kwargs): # pragma: no cover\n \"\"\"Run a fixture application.\n \"\"\"\n logging.getLogger(\"waitress\").addHandler(NullHandler())\n try_register_coverage()\n svr(app, queue, **kwargs).run()", "\ndef try_register_coverage(): # pragma: no cover\n # Hack around multiprocessing exiting early and not triggering coverage's\n # atexit handler by always registering a signal handler", " if \"COVERAGE_PROCESS_START\" in os.environ:\n def sigterm(*args):\n sys.exit(0)", " signal.signal(signal.SIGTERM, sigterm)", "\nclass FixtureTcpWSGIServer(server.TcpWSGIServer):\n \"\"\"A version of TcpWSGIServer that relays back what it's bound to.\n \"\"\"", " family = socket.AF_INET # Testing", " def __init__(self, application, queue, **kw): # pragma: no cover\n # Coverage doesn't see this as it's ran in a separate process.\n kw[\"port\"] = 0 # Bind to any available port.\n super(FixtureTcpWSGIServer, self).__init__(application, **kw)\n host, port = self.socket.getsockname()\n if os.name == \"nt\":\n host = \"127.0.0.1\"\n queue.put((host, port))", "\nclass SubprocessTests(object):", " # For nose: all tests may be ran in separate processes.\n _multiprocess_can_split_ = True", " exe = sys.executable", " server = None", " def start_subprocess(self, target, **kw):\n # Spawn a server process.\n self.queue = multiprocessing.Queue()", " if \"COVERAGE_RCFILE\" in os.environ:\n os.environ[\"COVERAGE_PROCESS_START\"] = os.environ[\"COVERAGE_RCFILE\"]", " self.proc = multiprocessing.Process(\n target=start_server, args=(target, self.server, self.queue), kwargs=kw,\n )\n self.proc.start()", " if self.proc.exitcode is not None: # pragma: no cover\n raise RuntimeError(\"%s didn't start\" % str(target))\n # Get the socket the server is listening on.\n self.bound_to = self.queue.get(timeout=5)\n self.sock = self.create_socket()", " def stop_subprocess(self):\n if self.proc.exitcode is None:\n self.proc.terminate()\n self.sock.close()\n # This give us one FD back ...\n self.queue.close()\n self.proc.join()", " def assertline(self, line, status, reason, version):\n v, s, r = (x.strip() for x in line.split(None, 2))\n self.assertEqual(s, tobytes(status))\n self.assertEqual(r, tobytes(reason))\n self.assertEqual(v, tobytes(version))", " def create_socket(self):\n return socket.socket(self.server.family, socket.SOCK_STREAM)", " def connect(self):\n self.sock.connect(self.bound_to)", " def make_http_connection(self):\n raise NotImplementedError # pragma: no cover", " def send_check_error(self, to_send):\n self.sock.send(to_send)", "\nclass TcpTests(SubprocessTests):", " server = FixtureTcpWSGIServer", " def make_http_connection(self):\n return httplib.HTTPConnection(*self.bound_to)", "\nclass SleepyThreadTests(TcpTests, unittest.TestCase):\n # test that sleepy thread doesnt block other requests", " def setUp(self):\n from waitress.tests.fixtureapps import sleepy", " self.start_subprocess(sleepy.app)", " def tearDown(self):\n self.stop_subprocess()", " def test_it(self):\n getline = os.path.join(here, \"fixtureapps\", \"getline.py\")\n cmds = (\n [self.exe, getline, \"http://%s:%d/sleepy\" % self.bound_to],\n [self.exe, getline, \"http://%s:%d/\" % self.bound_to],\n )\n r, w = os.pipe()\n procs = []\n for cmd in cmds:\n procs.append(subprocess.Popen(cmd, stdout=w))\n time.sleep(3)\n for proc in procs:\n if proc.returncode is not None: # pragma: no cover\n proc.terminate()\n proc.wait()\n # the notsleepy response should always be first returned (it sleeps\n # for 2 seconds, then returns; the notsleepy response should be\n # processed in the meantime)\n result = os.read(r, 10000)\n os.close(r)\n os.close(w)\n self.assertEqual(result, b\"notsleepy returnedsleepy returned\")", "\nclass EchoTests(object):\n def setUp(self):\n from waitress.tests.fixtureapps import echo", " self.start_subprocess(\n echo.app,\n trusted_proxy=\"*\",\n trusted_proxy_count=1,\n trusted_proxy_headers={\"x-forwarded-for\", \"x-forwarded-proto\"},\n clear_untrusted_proxy_headers=True,\n )", " def tearDown(self):\n self.stop_subprocess()", " def _read_echo(self, fp):\n from waitress.tests.fixtureapps import echo", " line, headers, body = read_http(fp)\n return line, headers, echo.parse_response(body)", " def test_date_and_server(self):", " to_send = \"GET / HTTP/1.0\\n\" \"Content-Length: 0\\n\\n\"", " to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, echo = self._read_echo(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(headers.get(\"server\"), \"waitress\")\n self.assertTrue(headers.get(\"date\"))", " def test_bad_host_header(self):\n # https://corte.si/posts/code/pathod/pythonservers/index.html", " to_send = \"GET / HTTP/1.0\\n\" \" Host: 0\\n\\n\"", " to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"400\", \"Bad Request\", \"HTTP/1.0\")\n self.assertEqual(headers.get(\"server\"), \"waitress\")\n self.assertTrue(headers.get(\"date\"))", " def test_send_with_body(self):", " to_send = \"GET / HTTP/1.0\\n\" \"Content-Length: 5\\n\\n\"", " to_send += \"hello\"\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, echo = self._read_echo(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(echo.content_length, \"5\")\n self.assertEqual(echo.body, b\"hello\")", " def test_send_empty_body(self):", " to_send = \"GET / HTTP/1.0\\n\" \"Content-Length: 0\\n\\n\"", " to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, echo = self._read_echo(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(echo.content_length, \"0\")\n self.assertEqual(echo.body, b\"\")", " def test_multiple_requests_with_body(self):\n orig_sock = self.sock\n for x in range(3):\n self.sock = self.create_socket()\n self.test_send_with_body()\n self.sock.close()\n self.sock = orig_sock", " def test_multiple_requests_without_body(self):\n orig_sock = self.sock\n for x in range(3):\n self.sock = self.create_socket()\n self.test_send_empty_body()\n self.sock.close()\n self.sock = orig_sock", " def test_without_crlf(self):", " data = \"Echo\\nthis\\r\\nplease\"", " s = tobytes(", " \"GET / HTTP/1.0\\n\"\n \"Connection: close\\n\"\n \"Content-Length: %d\\n\"\n \"\\n\"", " \"%s\" % (len(data), data)\n )\n self.connect()\n self.sock.send(s)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, echo = self._read_echo(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(int(echo.content_length), len(data))\n self.assertEqual(len(echo.body), len(data))\n self.assertEqual(echo.body, tobytes(data))", " def test_large_body(self):\n # 1024 characters.\n body = \"This string has 32 characters.\\r\\n\" * 32\n s = tobytes(", " \"GET / HTTP/1.0\\n\" \"Content-Length: %d\\n\" \"\\n\" \"%s\" % (len(body), body)", " )\n self.connect()\n self.sock.send(s)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, echo = self._read_echo(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(echo.content_length, \"1024\")\n self.assertEqual(echo.body, tobytes(body))", " def test_many_clients(self):\n conns = []\n for n in range(50):\n h = self.make_http_connection()\n h.request(\"GET\", \"/\", headers={\"Accept\": \"text/plain\"})\n conns.append(h)\n responses = []\n for h in conns:\n response = h.getresponse()\n self.assertEqual(response.status, 200)\n responses.append(response)\n for response in responses:\n response.read()\n for h in conns:\n h.close()", " def test_chunking_request_without_content(self):", " header = tobytes(\"GET / HTTP/1.1\\n\" \"Transfer-Encoding: chunked\\n\\n\")", " self.connect()\n self.sock.send(header)\n self.sock.send(b\"0\\r\\n\\r\\n\")\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, echo = self._read_echo(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n self.assertEqual(echo.body, b\"\")\n self.assertEqual(echo.content_length, \"0\")\n self.assertFalse(\"transfer-encoding\" in headers)", " def test_chunking_request_with_content(self):\n control_line = b\"20;\\r\\n\" # 20 hex = 32 dec\n s = b\"This string has 32 characters.\\r\\n\"\n expected = s * 12", " header = tobytes(\"GET / HTTP/1.1\\n\" \"Transfer-Encoding: chunked\\n\\n\")", " self.connect()\n self.sock.send(header)\n fp = self.sock.makefile(\"rb\", 0)\n for n in range(12):\n self.sock.send(control_line)\n self.sock.send(s)", "", " self.sock.send(b\"0\\r\\n\\r\\n\")\n line, headers, echo = self._read_echo(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n self.assertEqual(echo.body, expected)\n self.assertEqual(echo.content_length, str(len(expected)))\n self.assertFalse(\"transfer-encoding\" in headers)", " def test_broken_chunked_encoding(self):\n control_line = \"20;\\r\\n\" # 20 hex = 32 dec\n s = \"This string has 32 characters.\\r\\n\"", " to_send = \"GET / HTTP/1.1\\nTransfer-Encoding: chunked\\n\\n\"", " to_send += control_line + s\n # garbage in input", " to_send += \"GET / HTTP/1.1\\nTransfer-Encoding: chunked\\n\\n\"\n to_send += control_line + s", " to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n # receiver caught garbage and turned it into a 400\n self.assertline(line, \"400\", \"Bad Request\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))", "", " self.assertEqual(", " sorted(headers.keys()), [\"content-length\", \"content-type\", \"date\", \"server\"]", " )\n self.assertEqual(headers[\"content-type\"], \"text/plain\")\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_keepalive_http_10(self):\n # Handling of Keep-Alive within HTTP 1.0\n data = \"Default: Don't keep me alive\"\n s = tobytes(", " \"GET / HTTP/1.0\\n\" \"Content-Length: %d\\n\" \"\\n\" \"%s\" % (len(data), data)", " )\n self.connect()\n self.sock.send(s)\n response = httplib.HTTPResponse(self.sock)\n response.begin()\n self.assertEqual(int(response.status), 200)\n connection = response.getheader(\"Connection\", \"\")\n # We sent no Connection: Keep-Alive header\n # Connection: close (or no header) is default.\n self.assertTrue(connection != \"Keep-Alive\")", " def test_keepalive_http10_explicit(self):\n # If header Connection: Keep-Alive is explicitly sent,\n # we want to keept the connection open, we also need to return\n # the corresponding header\n data = \"Keep me alive\"\n s = tobytes(", " \"GET / HTTP/1.0\\n\"\n \"Connection: Keep-Alive\\n\"\n \"Content-Length: %d\\n\"\n \"\\n\"", " \"%s\" % (len(data), data)\n )\n self.connect()\n self.sock.send(s)\n response = httplib.HTTPResponse(self.sock)\n response.begin()\n self.assertEqual(int(response.status), 200)\n connection = response.getheader(\"Connection\", \"\")\n self.assertEqual(connection, \"Keep-Alive\")", " def test_keepalive_http_11(self):\n # Handling of Keep-Alive within HTTP 1.1", " # All connections are kept alive, unless stated otherwise\n data = \"Default: Keep me alive\"\n s = tobytes(", " \"GET / HTTP/1.1\\n\" \"Content-Length: %d\\n\" \"\\n\" \"%s\" % (len(data), data)", " )\n self.connect()\n self.sock.send(s)\n response = httplib.HTTPResponse(self.sock)\n response.begin()\n self.assertEqual(int(response.status), 200)\n self.assertTrue(response.getheader(\"connection\") != \"close\")", " def test_keepalive_http11_explicit(self):\n # Explicitly set keep-alive\n data = \"Default: Keep me alive\"\n s = tobytes(", " \"GET / HTTP/1.1\\n\"\n \"Connection: keep-alive\\n\"\n \"Content-Length: %d\\n\"\n \"\\n\"", " \"%s\" % (len(data), data)\n )\n self.connect()\n self.sock.send(s)\n response = httplib.HTTPResponse(self.sock)\n response.begin()\n self.assertEqual(int(response.status), 200)\n self.assertTrue(response.getheader(\"connection\") != \"close\")", " def test_keepalive_http11_connclose(self):\n # specifying Connection: close explicitly\n data = \"Don't keep me alive\"\n s = tobytes(", " \"GET / HTTP/1.1\\n\"\n \"Connection: close\\n\"\n \"Content-Length: %d\\n\"\n \"\\n\"", " \"%s\" % (len(data), data)\n )\n self.connect()\n self.sock.send(s)\n response = httplib.HTTPResponse(self.sock)\n response.begin()\n self.assertEqual(int(response.status), 200)\n self.assertEqual(response.getheader(\"connection\"), \"close\")", " def test_proxy_headers(self):\n to_send = (", " \"GET / HTTP/1.0\\n\"\n \"Content-Length: 0\\n\"\n \"Host: www.google.com:8080\\n\"\n \"X-Forwarded-For: 192.168.1.1\\n\"\n \"X-Forwarded-Proto: https\\n\"\n \"X-Forwarded-Port: 5000\\n\\n\"", " )\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, echo = self._read_echo(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(headers.get(\"server\"), \"waitress\")\n self.assertTrue(headers.get(\"date\"))\n self.assertIsNone(echo.headers.get(\"X_FORWARDED_PORT\"))\n self.assertEqual(echo.headers[\"HOST\"], \"www.google.com:8080\")\n self.assertEqual(echo.scheme, \"https\")\n self.assertEqual(echo.remote_addr, \"192.168.1.1\")\n self.assertEqual(echo.remote_host, \"192.168.1.1\")", "\nclass PipeliningTests(object):\n def setUp(self):\n from waitress.tests.fixtureapps import echo", " self.start_subprocess(echo.app_body_only)", " def tearDown(self):\n self.stop_subprocess()", " def test_pipelining(self):\n s = (\n \"GET / HTTP/1.0\\r\\n\"\n \"Connection: %s\\r\\n\"\n \"Content-Length: %d\\r\\n\"\n \"\\r\\n\"\n \"%s\"\n )\n to_send = b\"\"\n count = 25\n for n in range(count):\n body = \"Response #%d\\r\\n\" % (n + 1)\n if n + 1 < count:\n conn = \"keep-alive\"\n else:\n conn = \"close\"\n to_send += tobytes(s % (conn, len(body), body))", " self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n for n in range(count):\n expect_body = tobytes(\"Response #%d\\r\\n\" % (n + 1))\n line = fp.readline() # status line\n version, status, reason = (x.strip() for x in line.split(None, 2))\n headers = parse_headers(fp)\n length = int(headers.get(\"content-length\")) or None\n response_body = fp.read(length)\n self.assertEqual(int(status), 200)\n self.assertEqual(length, len(response_body))\n self.assertEqual(response_body, expect_body)", "\nclass ExpectContinueTests(object):\n def setUp(self):\n from waitress.tests.fixtureapps import echo", " self.start_subprocess(echo.app_body_only)", " def tearDown(self):\n self.stop_subprocess()", " def test_expect_continue(self):\n # specifying Connection: close explicitly\n data = \"I have expectations\"\n to_send = tobytes(", " \"GET / HTTP/1.1\\n\"\n \"Connection: close\\n\"\n \"Content-Length: %d\\n\"\n \"Expect: 100-continue\\n\"\n \"\\n\"", " \"%s\" % (len(data), data)\n )\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line = fp.readline() # continue status line\n version, status, reason = (x.strip() for x in line.split(None, 2))\n self.assertEqual(int(status), 100)\n self.assertEqual(reason, b\"Continue\")\n self.assertEqual(version, b\"HTTP/1.1\")\n fp.readline() # blank line\n line = fp.readline() # next status line\n version, status, reason = (x.strip() for x in line.split(None, 2))\n headers = parse_headers(fp)\n length = int(headers.get(\"content-length\")) or None\n response_body = fp.read(length)\n self.assertEqual(int(status), 200)\n self.assertEqual(length, len(response_body))\n self.assertEqual(response_body, tobytes(data))", "\nclass BadContentLengthTests(object):\n def setUp(self):\n from waitress.tests.fixtureapps import badcl", " self.start_subprocess(badcl.app)", " def tearDown(self):\n self.stop_subprocess()", " def test_short_body(self):\n # check to see if server closes connection when body is too short\n # for cl header\n to_send = tobytes(", " \"GET /short_body HTTP/1.0\\n\"\n \"Connection: Keep-Alive\\n\"\n \"Content-Length: 0\\n\"\n \"\\n\"", " )\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line = fp.readline() # status line\n version, status, reason = (x.strip() for x in line.split(None, 2))\n headers = parse_headers(fp)\n content_length = int(headers.get(\"content-length\"))\n response_body = fp.read(content_length)\n self.assertEqual(int(status), 200)\n self.assertNotEqual(content_length, len(response_body))\n self.assertEqual(len(response_body), content_length - 1)\n self.assertEqual(response_body, tobytes(\"abcdefghi\"))\n # remote closed connection (despite keepalive header); not sure why\n # first send succeeds\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_long_body(self):\n # check server doesnt close connection when body is too short\n # for cl header\n to_send = tobytes(", " \"GET /long_body HTTP/1.0\\n\"\n \"Connection: Keep-Alive\\n\"\n \"Content-Length: 0\\n\"\n \"\\n\"", " )\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line = fp.readline() # status line\n version, status, reason = (x.strip() for x in line.split(None, 2))\n headers = parse_headers(fp)\n content_length = int(headers.get(\"content-length\")) or None\n response_body = fp.read(content_length)\n self.assertEqual(int(status), 200)\n self.assertEqual(content_length, len(response_body))\n self.assertEqual(response_body, tobytes(\"abcdefgh\"))\n # remote does not close connection (keepalive header)\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line = fp.readline() # status line\n version, status, reason = (x.strip() for x in line.split(None, 2))\n headers = parse_headers(fp)\n content_length = int(headers.get(\"content-length\")) or None\n response_body = fp.read(content_length)\n self.assertEqual(int(status), 200)", "\nclass NoContentLengthTests(object):\n def setUp(self):\n from waitress.tests.fixtureapps import nocl", " self.start_subprocess(nocl.app)", " def tearDown(self):\n self.stop_subprocess()", " def test_http10_generator(self):\n body = string.ascii_letters\n to_send = (", " \"GET / HTTP/1.0\\n\"\n \"Connection: Keep-Alive\\n\"\n \"Content-Length: %d\\n\\n\" % len(body)", " )\n to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(headers.get(\"content-length\"), None)\n self.assertEqual(headers.get(\"connection\"), \"close\")\n self.assertEqual(response_body, tobytes(body))\n # remote closed connection (despite keepalive header), because\n # generators cannot have a content-length divined\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_http10_list(self):\n body = string.ascii_letters\n to_send = (", " \"GET /list HTTP/1.0\\n\"\n \"Connection: Keep-Alive\\n\"\n \"Content-Length: %d\\n\\n\" % len(body)", " )\n to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(headers[\"content-length\"], str(len(body)))\n self.assertEqual(headers.get(\"connection\"), \"Keep-Alive\")\n self.assertEqual(response_body, tobytes(body))\n # remote keeps connection open because it divined the content length\n # from a length-1 list\n self.sock.send(to_send)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")", " def test_http10_listlentwo(self):\n body = string.ascii_letters\n to_send = (", " \"GET /list_lentwo HTTP/1.0\\n\"\n \"Connection: Keep-Alive\\n\"\n \"Content-Length: %d\\n\\n\" % len(body)", " )\n to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(headers.get(\"content-length\"), None)\n self.assertEqual(headers.get(\"connection\"), \"close\")\n self.assertEqual(response_body, tobytes(body))\n # remote closed connection (despite keepalive header), because\n # lists of length > 1 cannot have their content length divined\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_http11_generator(self):\n body = string.ascii_letters", " to_send = \"GET / HTTP/1.1\\n\" \"Content-Length: %s\\n\\n\" % len(body)", " to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\")\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n expected = b\"\"\n for chunk in chunks(body, 10):\n expected += tobytes(\n \"%s\\r\\n%s\\r\\n\" % (str(hex(len(chunk))[2:].upper()), chunk)\n )\n expected += b\"0\\r\\n\\r\\n\"\n self.assertEqual(response_body, expected)\n # connection is always closed at the end of a chunked response\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_http11_list(self):\n body = string.ascii_letters", " to_send = \"GET /list HTTP/1.1\\n\" \"Content-Length: %d\\n\\n\" % len(body)", " to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n self.assertEqual(headers[\"content-length\"], str(len(body)))\n self.assertEqual(response_body, tobytes(body))\n # remote keeps connection open because it divined the content length\n # from a length-1 list\n self.sock.send(to_send)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")", " def test_http11_listlentwo(self):\n body = string.ascii_letters", " to_send = \"GET /list_lentwo HTTP/1.1\\n\" \"Content-Length: %s\\n\\n\" % len(body)", " to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\")\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n expected = b\"\"\n for chunk in (body[0], body[1:]):\n expected += tobytes(\n \"%s\\r\\n%s\\r\\n\" % (str(hex(len(chunk))[2:].upper()), chunk)\n )\n expected += b\"0\\r\\n\\r\\n\"\n self.assertEqual(response_body, expected)\n # connection is always closed at the end of a chunked response\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", "\nclass WriteCallbackTests(object):\n def setUp(self):\n from waitress.tests.fixtureapps import writecb", " self.start_subprocess(writecb.app)", " def tearDown(self):\n self.stop_subprocess()", " def test_short_body(self):\n # check to see if server closes connection when body is too short\n # for cl header\n to_send = tobytes(", " \"GET /short_body HTTP/1.0\\n\"\n \"Connection: Keep-Alive\\n\"\n \"Content-Length: 0\\n\"\n \"\\n\"", " )\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n # server trusts the content-length header (5)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, 9)\n self.assertNotEqual(cl, len(response_body))\n self.assertEqual(len(response_body), cl - 1)\n self.assertEqual(response_body, tobytes(\"abcdefgh\"))\n # remote closed connection (despite keepalive header)\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_long_body(self):\n # check server doesnt close connection when body is too long\n # for cl header\n to_send = tobytes(", " \"GET /long_body HTTP/1.0\\n\"\n \"Connection: Keep-Alive\\n\"\n \"Content-Length: 0\\n\"\n \"\\n\"", " )\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n content_length = int(headers.get(\"content-length\")) or None\n self.assertEqual(content_length, 9)\n self.assertEqual(content_length, len(response_body))\n self.assertEqual(response_body, tobytes(\"abcdefghi\"))\n # remote does not close connection (keepalive header)\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")", " def test_equal_body(self):\n # check server doesnt close connection when body is equal to\n # cl header\n to_send = tobytes(", " \"GET /equal_body HTTP/1.0\\n\"\n \"Connection: Keep-Alive\\n\"\n \"Content-Length: 0\\n\"\n \"\\n\"", " )\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n content_length = int(headers.get(\"content-length\")) or None\n self.assertEqual(content_length, 9)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(content_length, len(response_body))\n self.assertEqual(response_body, tobytes(\"abcdefghi\"))\n # remote does not close connection (keepalive header)\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")", " def test_no_content_length(self):\n # wtf happens when there's no content-length\n to_send = tobytes(", " \"GET /no_content_length HTTP/1.0\\n\"\n \"Connection: Keep-Alive\\n\"\n \"Content-Length: 0\\n\"\n \"\\n\"", " )\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line = fp.readline() # status line\n line, headers, response_body = read_http(fp)\n content_length = headers.get(\"content-length\")\n self.assertEqual(content_length, None)\n self.assertEqual(response_body, tobytes(\"abcdefghi\"))\n # remote closed connection (despite keepalive header)\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", "\nclass TooLargeTests(object):", " toobig = 1050", " def setUp(self):\n from waitress.tests.fixtureapps import toolarge", " self.start_subprocess(\n toolarge.app, max_request_header_size=1000, max_request_body_size=1000\n )", " def tearDown(self):\n self.stop_subprocess()", " def test_request_body_too_large_with_wrong_cl_http10(self):\n body = \"a\" * self.toobig", " to_send = \"GET / HTTP/1.0\\n\" \"Content-Length: 5\\n\\n\"", " to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\")\n # first request succeeds (content-length 5)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # server trusts the content-length header; no pipelining,\n # so request fulfilled, extra bytes are thrown away\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_request_body_too_large_with_wrong_cl_http10_keepalive(self):\n body = \"a\" * self.toobig", " to_send = \"GET / HTTP/1.0\\n\" \"Content-Length: 5\\n\" \"Connection: Keep-Alive\\n\\n\"", " to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\")\n # first request succeeds (content-length 5)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"431\", \"Request Header Fields Too Large\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_request_body_too_large_with_no_cl_http10(self):\n body = \"a\" * self.toobig", " to_send = \"GET / HTTP/1.0\\n\\n\"", " to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # extra bytes are thrown away (no pipelining), connection closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_request_body_too_large_with_no_cl_http10_keepalive(self):\n body = \"a\" * self.toobig", " to_send = \"GET / HTTP/1.0\\nConnection: Keep-Alive\\n\\n\"", " to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n # server trusts the content-length header (assumed zero)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n line, headers, response_body = read_http(fp)\n # next response overruns because the extra data appears to be\n # header data\n self.assertline(line, \"431\", \"Request Header Fields Too Large\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_request_body_too_large_with_wrong_cl_http11(self):\n body = \"a\" * self.toobig", " to_send = \"GET / HTTP/1.1\\n\" \"Content-Length: 5\\n\\n\"", " to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\")\n # first request succeeds (content-length 5)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # second response is an error response\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"431\", \"Request Header Fields Too Large\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_request_body_too_large_with_wrong_cl_http11_connclose(self):\n body = \"a\" * self.toobig", " to_send = \"GET / HTTP/1.1\\nContent-Length: 5\\nConnection: close\\n\\n\"", " to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n # server trusts the content-length header (5)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_request_body_too_large_with_no_cl_http11(self):\n body = \"a\" * self.toobig", " to_send = \"GET / HTTP/1.1\\n\\n\"", " to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\")\n # server trusts the content-length header (assumed 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # server assumes pipelined requests due to http/1.1, and the first\n # request was assumed c-l 0 because it had no content-length header,\n # so entire body looks like the header of the subsequent request\n # second response is an error response\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"431\", \"Request Header Fields Too Large\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_request_body_too_large_with_no_cl_http11_connclose(self):\n body = \"a\" * self.toobig", " to_send = \"GET / HTTP/1.1\\nConnection: close\\n\\n\"", " to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n # server trusts the content-length header (assumed 0)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_request_body_too_large_chunked_encoding(self):\n control_line = \"20;\\r\\n\" # 20 hex = 32 dec\n s = \"This string has 32 characters.\\r\\n\"", " to_send = \"GET / HTTP/1.1\\nTransfer-Encoding: chunked\\n\\n\"", " repeat = control_line + s\n to_send += repeat * ((self.toobig // len(repeat)) + 1)\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n # body bytes counter caught a max_request_body_size overrun\n self.assertline(line, \"413\", \"Request Entity Too Large\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n self.assertEqual(headers[\"content-type\"], \"text/plain\")\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", "\nclass InternalServerErrorTests(object):\n def setUp(self):\n from waitress.tests.fixtureapps import error", " self.start_subprocess(error.app, expose_tracebacks=True)", " def tearDown(self):\n self.stop_subprocess()", " def test_before_start_response_http_10(self):", " to_send = \"GET /before_start_response HTTP/1.0\\n\\n\"", " to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"500\", \"Internal Server Error\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n self.assertTrue(response_body.startswith(b\"Internal Server Error\"))\n self.assertEqual(headers[\"connection\"], \"close\")\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_before_start_response_http_11(self):", " to_send = \"GET /before_start_response HTTP/1.1\\n\\n\"", " to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"500\", \"Internal Server Error\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n self.assertTrue(response_body.startswith(b\"Internal Server Error\"))\n self.assertEqual(", " sorted(headers.keys()), [\"content-length\", \"content-type\", \"date\", \"server\"]", " )\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_before_start_response_http_11_close(self):\n to_send = tobytes(", " \"GET /before_start_response HTTP/1.1\\n\" \"Connection: close\\n\\n\"", " )\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"500\", \"Internal Server Error\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n self.assertTrue(response_body.startswith(b\"Internal Server Error\"))\n self.assertEqual(\n sorted(headers.keys()),\n [\"connection\", \"content-length\", \"content-type\", \"date\", \"server\"],\n )\n self.assertEqual(headers[\"connection\"], \"close\")\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_after_start_response_http10(self):", " to_send = \"GET /after_start_response HTTP/1.0\\n\\n\"", " to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"500\", \"Internal Server Error\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n self.assertTrue(response_body.startswith(b\"Internal Server Error\"))\n self.assertEqual(\n sorted(headers.keys()),\n [\"connection\", \"content-length\", \"content-type\", \"date\", \"server\"],\n )\n self.assertEqual(headers[\"connection\"], \"close\")\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_after_start_response_http11(self):", " to_send = \"GET /after_start_response HTTP/1.1\\n\\n\"", " to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"500\", \"Internal Server Error\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n self.assertTrue(response_body.startswith(b\"Internal Server Error\"))\n self.assertEqual(", " sorted(headers.keys()), [\"content-length\", \"content-type\", \"date\", \"server\"]", " )\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_after_start_response_http11_close(self):\n to_send = tobytes(", " \"GET /after_start_response HTTP/1.1\\n\" \"Connection: close\\n\\n\"", " )\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"500\", \"Internal Server Error\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n self.assertTrue(response_body.startswith(b\"Internal Server Error\"))\n self.assertEqual(\n sorted(headers.keys()),\n [\"connection\", \"content-length\", \"content-type\", \"date\", \"server\"],\n )\n self.assertEqual(headers[\"connection\"], \"close\")\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_after_write_cb(self):", " to_send = \"GET /after_write_cb HTTP/1.1\\n\\n\"", " to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n self.assertEqual(response_body, b\"\")\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_in_generator(self):", " to_send = \"GET /in_generator HTTP/1.1\\n\\n\"", " to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n self.assertEqual(response_body, b\"\")\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", "\nclass FileWrapperTests(object):\n def setUp(self):\n from waitress.tests.fixtureapps import filewrapper", " self.start_subprocess(filewrapper.app)", " def tearDown(self):\n self.stop_subprocess()", " def test_filelike_http11(self):", " to_send = \"GET /filelike HTTP/1.1\\n\\n\"", " to_send = tobytes(to_send)", " self.connect()", " for t in range(0, 2):\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has not been closed", " def test_filelike_nocl_http11(self):", " to_send = \"GET /filelike_nocl HTTP/1.1\\n\\n\"", " to_send = tobytes(to_send)", " self.connect()", " for t in range(0, 2):\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has not been closed", " def test_filelike_shortcl_http11(self):", " to_send = \"GET /filelike_shortcl HTTP/1.1\\n\\n\"", " to_send = tobytes(to_send)", " self.connect()", " for t in range(0, 2):\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, 1)\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\" in response_body)\n # connection has not been closed", " def test_filelike_longcl_http11(self):", " to_send = \"GET /filelike_longcl HTTP/1.1\\n\\n\"", " to_send = tobytes(to_send)", " self.connect()", " for t in range(0, 2):\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has not been closed", " def test_notfilelike_http11(self):", " to_send = \"GET /notfilelike HTTP/1.1\\n\\n\"", " to_send = tobytes(to_send)", " self.connect()", " for t in range(0, 2):\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has not been closed", " def test_notfilelike_iobase_http11(self):", " to_send = \"GET /notfilelike_iobase HTTP/1.1\\n\\n\"", " to_send = tobytes(to_send)", " self.connect()", " for t in range(0, 2):\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has not been closed", " def test_notfilelike_nocl_http11(self):", " to_send = \"GET /notfilelike_nocl HTTP/1.1\\n\\n\"", " to_send = tobytes(to_send)", " self.connect()", " self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has been closed (no content-length)\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_notfilelike_shortcl_http11(self):", " to_send = \"GET /notfilelike_shortcl HTTP/1.1\\n\\n\"", " to_send = tobytes(to_send)", " self.connect()", " for t in range(0, 2):\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, 1)\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\" in response_body)\n # connection has not been closed", " def test_notfilelike_longcl_http11(self):", " to_send = \"GET /notfilelike_longcl HTTP/1.1\\n\\n\"", " to_send = tobytes(to_send)", " self.connect()", " self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body) + 10)\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_filelike_http10(self):", " to_send = \"GET /filelike HTTP/1.0\\n\\n\"", " to_send = tobytes(to_send)", " self.connect()", " self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_filelike_nocl_http10(self):", " to_send = \"GET /filelike_nocl HTTP/1.0\\n\\n\"", " to_send = tobytes(to_send)", " self.connect()", " self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_notfilelike_http10(self):", " to_send = \"GET /notfilelike HTTP/1.0\\n\\n\"", " to_send = tobytes(to_send)", " self.connect()", " self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_notfilelike_nocl_http10(self):", " to_send = \"GET /notfilelike_nocl HTTP/1.0\\n\\n\"", " to_send = tobytes(to_send)", " self.connect()", " self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has been closed (no content-length)\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", "\nclass TcpEchoTests(EchoTests, TcpTests, unittest.TestCase):\n pass", "\nclass TcpPipeliningTests(PipeliningTests, TcpTests, unittest.TestCase):\n pass", "\nclass TcpExpectContinueTests(ExpectContinueTests, TcpTests, unittest.TestCase):\n pass", "\nclass TcpBadContentLengthTests(BadContentLengthTests, TcpTests, unittest.TestCase):\n pass", "\nclass TcpNoContentLengthTests(NoContentLengthTests, TcpTests, unittest.TestCase):\n pass", "\nclass TcpWriteCallbackTests(WriteCallbackTests, TcpTests, unittest.TestCase):\n pass", "\nclass TcpTooLargeTests(TooLargeTests, TcpTests, unittest.TestCase):\n pass", "\nclass TcpInternalServerErrorTests(\n InternalServerErrorTests, TcpTests, unittest.TestCase\n):\n pass", "\nclass TcpFileWrapperTests(FileWrapperTests, TcpTests, unittest.TestCase):\n pass", "\nif hasattr(socket, \"AF_UNIX\"):", " class FixtureUnixWSGIServer(server.UnixWSGIServer):\n \"\"\"A version of UnixWSGIServer that relays back what it's bound to.\n \"\"\"", " family = socket.AF_UNIX # Testing", " def __init__(self, application, queue, **kw): # pragma: no cover\n # Coverage doesn't see this as it's ran in a separate process.\n # To permit parallel testing, use a PID-dependent socket.\n kw[\"unix_socket\"] = \"/tmp/waitress.test-%d.sock\" % os.getpid()\n super(FixtureUnixWSGIServer, self).__init__(application, **kw)\n queue.put(self.socket.getsockname())", " class UnixTests(SubprocessTests):", " server = FixtureUnixWSGIServer", " def make_http_connection(self):\n return UnixHTTPConnection(self.bound_to)", " def stop_subprocess(self):\n super(UnixTests, self).stop_subprocess()\n cleanup_unix_socket(self.bound_to)", " def send_check_error(self, to_send):\n # Unlike inet domain sockets, Unix domain sockets can trigger a\n # 'Broken pipe' error when the socket it closed.\n try:\n self.sock.send(to_send)\n except socket.error as exc:\n self.assertEqual(get_errno(exc), errno.EPIPE)", " class UnixEchoTests(EchoTests, UnixTests, unittest.TestCase):\n pass", " class UnixPipeliningTests(PipeliningTests, UnixTests, unittest.TestCase):\n pass", " class UnixExpectContinueTests(ExpectContinueTests, UnixTests, unittest.TestCase):\n pass", " class UnixBadContentLengthTests(\n BadContentLengthTests, UnixTests, unittest.TestCase\n ):\n pass", " class UnixNoContentLengthTests(NoContentLengthTests, UnixTests, unittest.TestCase):\n pass", " class UnixWriteCallbackTests(WriteCallbackTests, UnixTests, unittest.TestCase):\n pass", " class UnixTooLargeTests(TooLargeTests, UnixTests, unittest.TestCase):\n pass", " class UnixInternalServerErrorTests(\n InternalServerErrorTests, UnixTests, unittest.TestCase\n ):\n pass", " class UnixFileWrapperTests(FileWrapperTests, UnixTests, unittest.TestCase):\n pass", "\ndef parse_headers(fp):\n \"\"\"Parses only RFC2822 headers from a file pointer.\n \"\"\"\n headers = {}\n while True:\n line = fp.readline()\n if line in (b\"\\r\\n\", b\"\\n\", b\"\"):\n break\n line = line.decode(\"iso-8859-1\")\n name, value = line.strip().split(\":\", 1)\n headers[name.lower().strip()] = value.lower().strip()\n return headers", "\nclass UnixHTTPConnection(httplib.HTTPConnection):\n \"\"\"Patched version of HTTPConnection that uses Unix domain sockets.\n \"\"\"", " def __init__(self, path):\n httplib.HTTPConnection.__init__(self, \"localhost\")\n self.path = path", " def connect(self):\n sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n sock.connect(self.path)\n self.sock = sock", "\nclass ConnectionClosed(Exception):\n pass", "\n# stolen from gevent\ndef read_http(fp): # pragma: no cover\n try:\n response_line = fp.readline()\n except socket.error as exc:\n fp.close()\n # errno 104 is ENOTRECOVERABLE, In WinSock 10054 is ECONNRESET\n if get_errno(exc) in (errno.ECONNABORTED, errno.ECONNRESET, 104, 10054):\n raise ConnectionClosed\n raise\n if not response_line:\n raise ConnectionClosed", " header_lines = []\n while True:\n line = fp.readline()", " if line in (b\"\\r\\n\", b\"\\n\", b\"\"):", " break\n else:\n header_lines.append(line)\n headers = dict()\n for x in header_lines:\n x = x.strip()\n if not x:\n continue\n key, value = x.split(b\": \", 1)\n key = key.decode(\"iso-8859-1\").lower()\n value = value.decode(\"iso-8859-1\")\n assert key not in headers, \"%s header duplicated\" % key\n headers[key] = value", " if \"content-length\" in headers:\n num = int(headers[\"content-length\"])\n body = b\"\"\n left = num\n while left > 0:\n data = fp.read(left)\n if not data:\n break\n body += data\n left -= len(data)\n else:\n # read until EOF\n body = fp.read()", " return response_line, headers, body", "\n# stolen from gevent\ndef get_errno(exc): # pragma: no cover\n \"\"\" Get the error code out of socket.error objects.\n socket.error in <2.5 does not have errno attribute\n socket.error in 3.x does not allow indexing access\n e.args[0] works for all.\n There are cases when args[0] is not errno.\n i.e. http://bugs.python.org/issue6471\n Maybe there are cases when errno is set, but it is not the first argument?\n \"\"\"\n try:\n if exc.errno is not None:\n return exc.errno\n except AttributeError:\n pass\n try:\n return exc.args[0]\n except IndexError:\n return None", "\ndef chunks(l, n):\n \"\"\" Yield successive n-sized chunks from l.\n \"\"\"\n for i in range(0, len(l), n):\n yield l[i : i + n]" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "import errno\nimport logging\nimport multiprocessing\nimport os\nimport signal\nimport socket\nimport string\nimport subprocess\nimport sys\nimport time\nimport unittest\nfrom waitress import server\nfrom waitress.compat import httplib, tobytes\nfrom waitress.utilities import cleanup_unix_socket", "dn = os.path.dirname\nhere = dn(__file__)", "\nclass NullHandler(logging.Handler): # pragma: no cover\n \"\"\"A logging handler that swallows all emitted messages.\n \"\"\"", " def emit(self, record):\n pass", "\ndef start_server(app, svr, queue, **kwargs): # pragma: no cover\n \"\"\"Run a fixture application.\n \"\"\"\n logging.getLogger(\"waitress\").addHandler(NullHandler())\n try_register_coverage()\n svr(app, queue, **kwargs).run()", "\ndef try_register_coverage(): # pragma: no cover\n # Hack around multiprocessing exiting early and not triggering coverage's\n # atexit handler by always registering a signal handler", " if \"COVERAGE_PROCESS_START\" in os.environ:\n def sigterm(*args):\n sys.exit(0)", " signal.signal(signal.SIGTERM, sigterm)", "\nclass FixtureTcpWSGIServer(server.TcpWSGIServer):\n \"\"\"A version of TcpWSGIServer that relays back what it's bound to.\n \"\"\"", " family = socket.AF_INET # Testing", " def __init__(self, application, queue, **kw): # pragma: no cover\n # Coverage doesn't see this as it's ran in a separate process.\n kw[\"port\"] = 0 # Bind to any available port.\n super(FixtureTcpWSGIServer, self).__init__(application, **kw)\n host, port = self.socket.getsockname()\n if os.name == \"nt\":\n host = \"127.0.0.1\"\n queue.put((host, port))", "\nclass SubprocessTests(object):", " # For nose: all tests may be ran in separate processes.\n _multiprocess_can_split_ = True", " exe = sys.executable", " server = None", " def start_subprocess(self, target, **kw):\n # Spawn a server process.\n self.queue = multiprocessing.Queue()", " if \"COVERAGE_RCFILE\" in os.environ:\n os.environ[\"COVERAGE_PROCESS_START\"] = os.environ[\"COVERAGE_RCFILE\"]", " self.proc = multiprocessing.Process(\n target=start_server, args=(target, self.server, self.queue), kwargs=kw,\n )\n self.proc.start()", " if self.proc.exitcode is not None: # pragma: no cover\n raise RuntimeError(\"%s didn't start\" % str(target))\n # Get the socket the server is listening on.\n self.bound_to = self.queue.get(timeout=5)\n self.sock = self.create_socket()", " def stop_subprocess(self):\n if self.proc.exitcode is None:\n self.proc.terminate()\n self.sock.close()\n # This give us one FD back ...\n self.queue.close()\n self.proc.join()", " def assertline(self, line, status, reason, version):\n v, s, r = (x.strip() for x in line.split(None, 2))\n self.assertEqual(s, tobytes(status))\n self.assertEqual(r, tobytes(reason))\n self.assertEqual(v, tobytes(version))", " def create_socket(self):\n return socket.socket(self.server.family, socket.SOCK_STREAM)", " def connect(self):\n self.sock.connect(self.bound_to)", " def make_http_connection(self):\n raise NotImplementedError # pragma: no cover", " def send_check_error(self, to_send):\n self.sock.send(to_send)", "\nclass TcpTests(SubprocessTests):", " server = FixtureTcpWSGIServer", " def make_http_connection(self):\n return httplib.HTTPConnection(*self.bound_to)", "\nclass SleepyThreadTests(TcpTests, unittest.TestCase):\n # test that sleepy thread doesnt block other requests", " def setUp(self):\n from waitress.tests.fixtureapps import sleepy", " self.start_subprocess(sleepy.app)", " def tearDown(self):\n self.stop_subprocess()", " def test_it(self):\n getline = os.path.join(here, \"fixtureapps\", \"getline.py\")\n cmds = (\n [self.exe, getline, \"http://%s:%d/sleepy\" % self.bound_to],\n [self.exe, getline, \"http://%s:%d/\" % self.bound_to],\n )\n r, w = os.pipe()\n procs = []\n for cmd in cmds:\n procs.append(subprocess.Popen(cmd, stdout=w))\n time.sleep(3)\n for proc in procs:\n if proc.returncode is not None: # pragma: no cover\n proc.terminate()\n proc.wait()\n # the notsleepy response should always be first returned (it sleeps\n # for 2 seconds, then returns; the notsleepy response should be\n # processed in the meantime)\n result = os.read(r, 10000)\n os.close(r)\n os.close(w)\n self.assertEqual(result, b\"notsleepy returnedsleepy returned\")", "\nclass EchoTests(object):\n def setUp(self):\n from waitress.tests.fixtureapps import echo", " self.start_subprocess(\n echo.app,\n trusted_proxy=\"*\",\n trusted_proxy_count=1,\n trusted_proxy_headers={\"x-forwarded-for\", \"x-forwarded-proto\"},\n clear_untrusted_proxy_headers=True,\n )", " def tearDown(self):\n self.stop_subprocess()", " def _read_echo(self, fp):\n from waitress.tests.fixtureapps import echo", " line, headers, body = read_http(fp)\n return line, headers, echo.parse_response(body)", " def test_date_and_server(self):", " to_send = \"GET / HTTP/1.0\\r\\nContent-Length: 0\\r\\n\\r\\n\"", " to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, echo = self._read_echo(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(headers.get(\"server\"), \"waitress\")\n self.assertTrue(headers.get(\"date\"))", " def test_bad_host_header(self):\n # https://corte.si/posts/code/pathod/pythonservers/index.html", " to_send = \"GET / HTTP/1.0\\r\\n Host: 0\\r\\n\\r\\n\"", " to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"400\", \"Bad Request\", \"HTTP/1.0\")\n self.assertEqual(headers.get(\"server\"), \"waitress\")\n self.assertTrue(headers.get(\"date\"))", " def test_send_with_body(self):", " to_send = \"GET / HTTP/1.0\\r\\nContent-Length: 5\\r\\n\\r\\n\"", " to_send += \"hello\"\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, echo = self._read_echo(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(echo.content_length, \"5\")\n self.assertEqual(echo.body, b\"hello\")", " def test_send_empty_body(self):", " to_send = \"GET / HTTP/1.0\\r\\nContent-Length: 0\\r\\n\\r\\n\"", " to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, echo = self._read_echo(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(echo.content_length, \"0\")\n self.assertEqual(echo.body, b\"\")", " def test_multiple_requests_with_body(self):\n orig_sock = self.sock\n for x in range(3):\n self.sock = self.create_socket()\n self.test_send_with_body()\n self.sock.close()\n self.sock = orig_sock", " def test_multiple_requests_without_body(self):\n orig_sock = self.sock\n for x in range(3):\n self.sock = self.create_socket()\n self.test_send_empty_body()\n self.sock.close()\n self.sock = orig_sock", " def test_without_crlf(self):", " data = \"Echo\\r\\nthis\\r\\nplease\"", " s = tobytes(", " \"GET / HTTP/1.0\\r\\n\"\n \"Connection: close\\r\\n\"\n \"Content-Length: %d\\r\\n\"\n \"\\r\\n\"", " \"%s\" % (len(data), data)\n )\n self.connect()\n self.sock.send(s)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, echo = self._read_echo(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(int(echo.content_length), len(data))\n self.assertEqual(len(echo.body), len(data))\n self.assertEqual(echo.body, tobytes(data))", " def test_large_body(self):\n # 1024 characters.\n body = \"This string has 32 characters.\\r\\n\" * 32\n s = tobytes(", " \"GET / HTTP/1.0\\r\\nContent-Length: %d\\r\\n\\r\\n%s\" % (len(body), body)", " )\n self.connect()\n self.sock.send(s)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, echo = self._read_echo(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(echo.content_length, \"1024\")\n self.assertEqual(echo.body, tobytes(body))", " def test_many_clients(self):\n conns = []\n for n in range(50):\n h = self.make_http_connection()\n h.request(\"GET\", \"/\", headers={\"Accept\": \"text/plain\"})\n conns.append(h)\n responses = []\n for h in conns:\n response = h.getresponse()\n self.assertEqual(response.status, 200)\n responses.append(response)\n for response in responses:\n response.read()\n for h in conns:\n h.close()", " def test_chunking_request_without_content(self):", " header = tobytes(\"GET / HTTP/1.1\\r\\nTransfer-Encoding: chunked\\r\\n\\r\\n\")", " self.connect()\n self.sock.send(header)\n self.sock.send(b\"0\\r\\n\\r\\n\")\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, echo = self._read_echo(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n self.assertEqual(echo.body, b\"\")\n self.assertEqual(echo.content_length, \"0\")\n self.assertFalse(\"transfer-encoding\" in headers)", " def test_chunking_request_with_content(self):\n control_line = b\"20;\\r\\n\" # 20 hex = 32 dec\n s = b\"This string has 32 characters.\\r\\n\"\n expected = s * 12", " header = tobytes(\"GET / HTTP/1.1\\r\\nTransfer-Encoding: chunked\\r\\n\\r\\n\")", " self.connect()\n self.sock.send(header)\n fp = self.sock.makefile(\"rb\", 0)\n for n in range(12):\n self.sock.send(control_line)\n self.sock.send(s)", " self.sock.send(b\"\\r\\n\") # End the chunk", " self.sock.send(b\"0\\r\\n\\r\\n\")\n line, headers, echo = self._read_echo(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n self.assertEqual(echo.body, expected)\n self.assertEqual(echo.content_length, str(len(expected)))\n self.assertFalse(\"transfer-encoding\" in headers)", " def test_broken_chunked_encoding(self):\n control_line = \"20;\\r\\n\" # 20 hex = 32 dec\n s = \"This string has 32 characters.\\r\\n\"", " to_send = \"GET / HTTP/1.1\\r\\nTransfer-Encoding: chunked\\r\\n\\r\\n\"\n to_send += control_line + s + \"\\r\\n\"\n # garbage in input\n to_send += \"garbage\\r\\n\"\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n # receiver caught garbage and turned it into a 400\n self.assertline(line, \"400\", \"Bad Request\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n self.assertEqual(\n sorted(headers.keys()), [\"connection\", \"content-length\", \"content-type\", \"date\", \"server\"]\n )\n self.assertEqual(headers[\"content-type\"], \"text/plain\")\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_broken_chunked_encoding_missing_chunk_end(self):\n control_line = \"20;\\r\\n\" # 20 hex = 32 dec\n s = \"This string has 32 characters.\\r\\n\"\n to_send = \"GET / HTTP/1.1\\r\\nTransfer-Encoding: chunked\\r\\n\\r\\n\"", " to_send += control_line + s\n # garbage in input", " to_send += \"garbage\"", " to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n # receiver caught garbage and turned it into a 400\n self.assertline(line, \"400\", \"Bad Request\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))", " self.assertTrue(b\"Chunk not properly terminated\" in response_body)", " self.assertEqual(", " sorted(headers.keys()), [\"connection\", \"content-length\", \"content-type\", \"date\", \"server\"]", " )\n self.assertEqual(headers[\"content-type\"], \"text/plain\")\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_keepalive_http_10(self):\n # Handling of Keep-Alive within HTTP 1.0\n data = \"Default: Don't keep me alive\"\n s = tobytes(", " \"GET / HTTP/1.0\\r\\nContent-Length: %d\\r\\n\\r\\n%s\" % (len(data), data)", " )\n self.connect()\n self.sock.send(s)\n response = httplib.HTTPResponse(self.sock)\n response.begin()\n self.assertEqual(int(response.status), 200)\n connection = response.getheader(\"Connection\", \"\")\n # We sent no Connection: Keep-Alive header\n # Connection: close (or no header) is default.\n self.assertTrue(connection != \"Keep-Alive\")", " def test_keepalive_http10_explicit(self):\n # If header Connection: Keep-Alive is explicitly sent,\n # we want to keept the connection open, we also need to return\n # the corresponding header\n data = \"Keep me alive\"\n s = tobytes(", " \"GET / HTTP/1.0\\r\\n\"\n \"Connection: Keep-Alive\\r\\n\"\n \"Content-Length: %d\\r\\n\"\n \"\\r\\n\"", " \"%s\" % (len(data), data)\n )\n self.connect()\n self.sock.send(s)\n response = httplib.HTTPResponse(self.sock)\n response.begin()\n self.assertEqual(int(response.status), 200)\n connection = response.getheader(\"Connection\", \"\")\n self.assertEqual(connection, \"Keep-Alive\")", " def test_keepalive_http_11(self):\n # Handling of Keep-Alive within HTTP 1.1", " # All connections are kept alive, unless stated otherwise\n data = \"Default: Keep me alive\"\n s = tobytes(", " \"GET / HTTP/1.1\\r\\nContent-Length: %d\\r\\n\\r\\n%s\" % (len(data), data)", " )\n self.connect()\n self.sock.send(s)\n response = httplib.HTTPResponse(self.sock)\n response.begin()\n self.assertEqual(int(response.status), 200)\n self.assertTrue(response.getheader(\"connection\") != \"close\")", " def test_keepalive_http11_explicit(self):\n # Explicitly set keep-alive\n data = \"Default: Keep me alive\"\n s = tobytes(", " \"GET / HTTP/1.1\\r\\n\"\n \"Connection: keep-alive\\r\\n\"\n \"Content-Length: %d\\r\\n\"\n \"\\r\\n\"", " \"%s\" % (len(data), data)\n )\n self.connect()\n self.sock.send(s)\n response = httplib.HTTPResponse(self.sock)\n response.begin()\n self.assertEqual(int(response.status), 200)\n self.assertTrue(response.getheader(\"connection\") != \"close\")", " def test_keepalive_http11_connclose(self):\n # specifying Connection: close explicitly\n data = \"Don't keep me alive\"\n s = tobytes(", " \"GET / HTTP/1.1\\r\\n\"\n \"Connection: close\\r\\n\"\n \"Content-Length: %d\\r\\n\"\n \"\\r\\n\"", " \"%s\" % (len(data), data)\n )\n self.connect()\n self.sock.send(s)\n response = httplib.HTTPResponse(self.sock)\n response.begin()\n self.assertEqual(int(response.status), 200)\n self.assertEqual(response.getheader(\"connection\"), \"close\")", " def test_proxy_headers(self):\n to_send = (", " \"GET / HTTP/1.0\\r\\n\"\n \"Content-Length: 0\\r\\n\"\n \"Host: www.google.com:8080\\r\\n\"\n \"X-Forwarded-For: 192.168.1.1\\r\\n\"\n \"X-Forwarded-Proto: https\\r\\n\"\n \"X-Forwarded-Port: 5000\\r\\n\\r\\n\"", " )\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, echo = self._read_echo(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(headers.get(\"server\"), \"waitress\")\n self.assertTrue(headers.get(\"date\"))\n self.assertIsNone(echo.headers.get(\"X_FORWARDED_PORT\"))\n self.assertEqual(echo.headers[\"HOST\"], \"www.google.com:8080\")\n self.assertEqual(echo.scheme, \"https\")\n self.assertEqual(echo.remote_addr, \"192.168.1.1\")\n self.assertEqual(echo.remote_host, \"192.168.1.1\")", "\nclass PipeliningTests(object):\n def setUp(self):\n from waitress.tests.fixtureapps import echo", " self.start_subprocess(echo.app_body_only)", " def tearDown(self):\n self.stop_subprocess()", " def test_pipelining(self):\n s = (\n \"GET / HTTP/1.0\\r\\n\"\n \"Connection: %s\\r\\n\"\n \"Content-Length: %d\\r\\n\"\n \"\\r\\n\"\n \"%s\"\n )\n to_send = b\"\"\n count = 25\n for n in range(count):\n body = \"Response #%d\\r\\n\" % (n + 1)\n if n + 1 < count:\n conn = \"keep-alive\"\n else:\n conn = \"close\"\n to_send += tobytes(s % (conn, len(body), body))", " self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n for n in range(count):\n expect_body = tobytes(\"Response #%d\\r\\n\" % (n + 1))\n line = fp.readline() # status line\n version, status, reason = (x.strip() for x in line.split(None, 2))\n headers = parse_headers(fp)\n length = int(headers.get(\"content-length\")) or None\n response_body = fp.read(length)\n self.assertEqual(int(status), 200)\n self.assertEqual(length, len(response_body))\n self.assertEqual(response_body, expect_body)", "\nclass ExpectContinueTests(object):\n def setUp(self):\n from waitress.tests.fixtureapps import echo", " self.start_subprocess(echo.app_body_only)", " def tearDown(self):\n self.stop_subprocess()", " def test_expect_continue(self):\n # specifying Connection: close explicitly\n data = \"I have expectations\"\n to_send = tobytes(", " \"GET / HTTP/1.1\\r\\n\"\n \"Connection: close\\r\\n\"\n \"Content-Length: %d\\r\\n\"\n \"Expect: 100-continue\\r\\n\"\n \"\\r\\n\"", " \"%s\" % (len(data), data)\n )\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line = fp.readline() # continue status line\n version, status, reason = (x.strip() for x in line.split(None, 2))\n self.assertEqual(int(status), 100)\n self.assertEqual(reason, b\"Continue\")\n self.assertEqual(version, b\"HTTP/1.1\")\n fp.readline() # blank line\n line = fp.readline() # next status line\n version, status, reason = (x.strip() for x in line.split(None, 2))\n headers = parse_headers(fp)\n length = int(headers.get(\"content-length\")) or None\n response_body = fp.read(length)\n self.assertEqual(int(status), 200)\n self.assertEqual(length, len(response_body))\n self.assertEqual(response_body, tobytes(data))", "\nclass BadContentLengthTests(object):\n def setUp(self):\n from waitress.tests.fixtureapps import badcl", " self.start_subprocess(badcl.app)", " def tearDown(self):\n self.stop_subprocess()", " def test_short_body(self):\n # check to see if server closes connection when body is too short\n # for cl header\n to_send = tobytes(", " \"GET /short_body HTTP/1.0\\r\\n\"\n \"Connection: Keep-Alive\\r\\n\"\n \"Content-Length: 0\\r\\n\"\n \"\\r\\n\"", " )\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line = fp.readline() # status line\n version, status, reason = (x.strip() for x in line.split(None, 2))\n headers = parse_headers(fp)\n content_length = int(headers.get(\"content-length\"))\n response_body = fp.read(content_length)\n self.assertEqual(int(status), 200)\n self.assertNotEqual(content_length, len(response_body))\n self.assertEqual(len(response_body), content_length - 1)\n self.assertEqual(response_body, tobytes(\"abcdefghi\"))\n # remote closed connection (despite keepalive header); not sure why\n # first send succeeds\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_long_body(self):\n # check server doesnt close connection when body is too short\n # for cl header\n to_send = tobytes(", " \"GET /long_body HTTP/1.0\\r\\n\"\n \"Connection: Keep-Alive\\r\\n\"\n \"Content-Length: 0\\r\\n\"\n \"\\r\\n\"", " )\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line = fp.readline() # status line\n version, status, reason = (x.strip() for x in line.split(None, 2))\n headers = parse_headers(fp)\n content_length = int(headers.get(\"content-length\")) or None\n response_body = fp.read(content_length)\n self.assertEqual(int(status), 200)\n self.assertEqual(content_length, len(response_body))\n self.assertEqual(response_body, tobytes(\"abcdefgh\"))\n # remote does not close connection (keepalive header)\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line = fp.readline() # status line\n version, status, reason = (x.strip() for x in line.split(None, 2))\n headers = parse_headers(fp)\n content_length = int(headers.get(\"content-length\")) or None\n response_body = fp.read(content_length)\n self.assertEqual(int(status), 200)", "\nclass NoContentLengthTests(object):\n def setUp(self):\n from waitress.tests.fixtureapps import nocl", " self.start_subprocess(nocl.app)", " def tearDown(self):\n self.stop_subprocess()", " def test_http10_generator(self):\n body = string.ascii_letters\n to_send = (", " \"GET / HTTP/1.0\\r\\n\"\n \"Connection: Keep-Alive\\r\\n\"\n \"Content-Length: %d\\r\\n\\r\\n\" % len(body)", " )\n to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(headers.get(\"content-length\"), None)\n self.assertEqual(headers.get(\"connection\"), \"close\")\n self.assertEqual(response_body, tobytes(body))\n # remote closed connection (despite keepalive header), because\n # generators cannot have a content-length divined\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_http10_list(self):\n body = string.ascii_letters\n to_send = (", " \"GET /list HTTP/1.0\\r\\n\"\n \"Connection: Keep-Alive\\r\\n\"\n \"Content-Length: %d\\r\\n\\r\\n\" % len(body)", " )\n to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(headers[\"content-length\"], str(len(body)))\n self.assertEqual(headers.get(\"connection\"), \"Keep-Alive\")\n self.assertEqual(response_body, tobytes(body))\n # remote keeps connection open because it divined the content length\n # from a length-1 list\n self.sock.send(to_send)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")", " def test_http10_listlentwo(self):\n body = string.ascii_letters\n to_send = (", " \"GET /list_lentwo HTTP/1.0\\r\\n\"\n \"Connection: Keep-Alive\\r\\n\"\n \"Content-Length: %d\\r\\n\\r\\n\" % len(body)", " )\n to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(headers.get(\"content-length\"), None)\n self.assertEqual(headers.get(\"connection\"), \"close\")\n self.assertEqual(response_body, tobytes(body))\n # remote closed connection (despite keepalive header), because\n # lists of length > 1 cannot have their content length divined\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_http11_generator(self):\n body = string.ascii_letters", " to_send = \"GET / HTTP/1.1\\r\\nContent-Length: %s\\r\\n\\r\\n\" % len(body)", " to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\")\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n expected = b\"\"\n for chunk in chunks(body, 10):\n expected += tobytes(\n \"%s\\r\\n%s\\r\\n\" % (str(hex(len(chunk))[2:].upper()), chunk)\n )\n expected += b\"0\\r\\n\\r\\n\"\n self.assertEqual(response_body, expected)\n # connection is always closed at the end of a chunked response\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_http11_list(self):\n body = string.ascii_letters", " to_send = \"GET /list HTTP/1.1\\r\\nContent-Length: %d\\r\\n\\r\\n\" % len(body)", " to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n self.assertEqual(headers[\"content-length\"], str(len(body)))\n self.assertEqual(response_body, tobytes(body))\n # remote keeps connection open because it divined the content length\n # from a length-1 list\n self.sock.send(to_send)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")", " def test_http11_listlentwo(self):\n body = string.ascii_letters", " to_send = \"GET /list_lentwo HTTP/1.1\\r\\nContent-Length: %s\\r\\n\\r\\n\" % len(body)", " to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\")\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n expected = b\"\"\n for chunk in (body[0], body[1:]):\n expected += tobytes(\n \"%s\\r\\n%s\\r\\n\" % (str(hex(len(chunk))[2:].upper()), chunk)\n )\n expected += b\"0\\r\\n\\r\\n\"\n self.assertEqual(response_body, expected)\n # connection is always closed at the end of a chunked response\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", "\nclass WriteCallbackTests(object):\n def setUp(self):\n from waitress.tests.fixtureapps import writecb", " self.start_subprocess(writecb.app)", " def tearDown(self):\n self.stop_subprocess()", " def test_short_body(self):\n # check to see if server closes connection when body is too short\n # for cl header\n to_send = tobytes(", " \"GET /short_body HTTP/1.0\\r\\n\"\n \"Connection: Keep-Alive\\r\\n\"\n \"Content-Length: 0\\r\\n\"\n \"\\r\\n\"", " )\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n # server trusts the content-length header (5)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, 9)\n self.assertNotEqual(cl, len(response_body))\n self.assertEqual(len(response_body), cl - 1)\n self.assertEqual(response_body, tobytes(\"abcdefgh\"))\n # remote closed connection (despite keepalive header)\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_long_body(self):\n # check server doesnt close connection when body is too long\n # for cl header\n to_send = tobytes(", " \"GET /long_body HTTP/1.0\\r\\n\"\n \"Connection: Keep-Alive\\r\\n\"\n \"Content-Length: 0\\r\\n\"\n \"\\r\\n\"", " )\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n content_length = int(headers.get(\"content-length\")) or None\n self.assertEqual(content_length, 9)\n self.assertEqual(content_length, len(response_body))\n self.assertEqual(response_body, tobytes(\"abcdefghi\"))\n # remote does not close connection (keepalive header)\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")", " def test_equal_body(self):\n # check server doesnt close connection when body is equal to\n # cl header\n to_send = tobytes(", " \"GET /equal_body HTTP/1.0\\r\\n\"\n \"Connection: Keep-Alive\\r\\n\"\n \"Content-Length: 0\\r\\n\"\n \"\\r\\n\"", " )\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n content_length = int(headers.get(\"content-length\")) or None\n self.assertEqual(content_length, 9)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n self.assertEqual(content_length, len(response_body))\n self.assertEqual(response_body, tobytes(\"abcdefghi\"))\n # remote does not close connection (keepalive header)\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")", " def test_no_content_length(self):\n # wtf happens when there's no content-length\n to_send = tobytes(", " \"GET /no_content_length HTTP/1.0\\r\\n\"\n \"Connection: Keep-Alive\\r\\n\"\n \"Content-Length: 0\\r\\n\"\n \"\\r\\n\"", " )\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line = fp.readline() # status line\n line, headers, response_body = read_http(fp)\n content_length = headers.get(\"content-length\")\n self.assertEqual(content_length, None)\n self.assertEqual(response_body, tobytes(\"abcdefghi\"))\n # remote closed connection (despite keepalive header)\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", "\nclass TooLargeTests(object):", " toobig = 1050", " def setUp(self):\n from waitress.tests.fixtureapps import toolarge", " self.start_subprocess(\n toolarge.app, max_request_header_size=1000, max_request_body_size=1000\n )", " def tearDown(self):\n self.stop_subprocess()", " def test_request_body_too_large_with_wrong_cl_http10(self):\n body = \"a\" * self.toobig", " to_send = \"GET / HTTP/1.0\\r\\nContent-Length: 5\\r\\n\\r\\n\"", " to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\")\n # first request succeeds (content-length 5)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # server trusts the content-length header; no pipelining,\n # so request fulfilled, extra bytes are thrown away\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_request_body_too_large_with_wrong_cl_http10_keepalive(self):\n body = \"a\" * self.toobig", " to_send = \"GET / HTTP/1.0\\r\\nContent-Length: 5\\r\\nConnection: Keep-Alive\\r\\n\\r\\n\"", " to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\")\n # first request succeeds (content-length 5)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"431\", \"Request Header Fields Too Large\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_request_body_too_large_with_no_cl_http10(self):\n body = \"a\" * self.toobig", " to_send = \"GET / HTTP/1.0\\r\\n\\r\\n\"", " to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # extra bytes are thrown away (no pipelining), connection closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_request_body_too_large_with_no_cl_http10_keepalive(self):\n body = \"a\" * self.toobig", " to_send = \"GET / HTTP/1.0\\r\\nConnection: Keep-Alive\\r\\n\\r\\n\"", " to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n # server trusts the content-length header (assumed zero)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n line, headers, response_body = read_http(fp)\n # next response overruns because the extra data appears to be\n # header data\n self.assertline(line, \"431\", \"Request Header Fields Too Large\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_request_body_too_large_with_wrong_cl_http11(self):\n body = \"a\" * self.toobig", " to_send = \"GET / HTTP/1.1\\r\\nContent-Length: 5\\r\\n\\r\\n\"", " to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\")\n # first request succeeds (content-length 5)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # second response is an error response\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"431\", \"Request Header Fields Too Large\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_request_body_too_large_with_wrong_cl_http11_connclose(self):\n body = \"a\" * self.toobig", " to_send = \"GET / HTTP/1.1\\r\\nContent-Length: 5\\r\\nConnection: close\\r\\n\\r\\n\"", " to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n # server trusts the content-length header (5)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_request_body_too_large_with_no_cl_http11(self):\n body = \"a\" * self.toobig", " to_send = \"GET / HTTP/1.1\\r\\n\\r\\n\"", " to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\")\n # server trusts the content-length header (assumed 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # server assumes pipelined requests due to http/1.1, and the first\n # request was assumed c-l 0 because it had no content-length header,\n # so entire body looks like the header of the subsequent request\n # second response is an error response\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"431\", \"Request Header Fields Too Large\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_request_body_too_large_with_no_cl_http11_connclose(self):\n body = \"a\" * self.toobig", " to_send = \"GET / HTTP/1.1\\r\\nConnection: close\\r\\n\\r\\n\"", " to_send += body\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n # server trusts the content-length header (assumed 0)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_request_body_too_large_chunked_encoding(self):\n control_line = \"20;\\r\\n\" # 20 hex = 32 dec\n s = \"This string has 32 characters.\\r\\n\"", " to_send = \"GET / HTTP/1.1\\r\\nTransfer-Encoding: chunked\\r\\n\\r\\n\"", " repeat = control_line + s\n to_send += repeat * ((self.toobig // len(repeat)) + 1)\n to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n # body bytes counter caught a max_request_body_size overrun\n self.assertline(line, \"413\", \"Request Entity Too Large\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n self.assertEqual(headers[\"content-type\"], \"text/plain\")\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", "\nclass InternalServerErrorTests(object):\n def setUp(self):\n from waitress.tests.fixtureapps import error", " self.start_subprocess(error.app, expose_tracebacks=True)", " def tearDown(self):\n self.stop_subprocess()", " def test_before_start_response_http_10(self):", " to_send = \"GET /before_start_response HTTP/1.0\\r\\n\\r\\n\"", " to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"500\", \"Internal Server Error\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n self.assertTrue(response_body.startswith(b\"Internal Server Error\"))\n self.assertEqual(headers[\"connection\"], \"close\")\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_before_start_response_http_11(self):", " to_send = \"GET /before_start_response HTTP/1.1\\r\\n\\r\\n\"", " to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"500\", \"Internal Server Error\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n self.assertTrue(response_body.startswith(b\"Internal Server Error\"))\n self.assertEqual(", " sorted(headers.keys()), [\"connection\", \"content-length\", \"content-type\", \"date\", \"server\"]", " )\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_before_start_response_http_11_close(self):\n to_send = tobytes(", " \"GET /before_start_response HTTP/1.1\\r\\nConnection: close\\r\\n\\r\\n\"", " )\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"500\", \"Internal Server Error\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n self.assertTrue(response_body.startswith(b\"Internal Server Error\"))\n self.assertEqual(\n sorted(headers.keys()),\n [\"connection\", \"content-length\", \"content-type\", \"date\", \"server\"],\n )\n self.assertEqual(headers[\"connection\"], \"close\")\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_after_start_response_http10(self):", " to_send = \"GET /after_start_response HTTP/1.0\\r\\n\\r\\n\"", " to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"500\", \"Internal Server Error\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n self.assertTrue(response_body.startswith(b\"Internal Server Error\"))\n self.assertEqual(\n sorted(headers.keys()),\n [\"connection\", \"content-length\", \"content-type\", \"date\", \"server\"],\n )\n self.assertEqual(headers[\"connection\"], \"close\")\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_after_start_response_http11(self):", " to_send = \"GET /after_start_response HTTP/1.1\\r\\n\\r\\n\"", " to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"500\", \"Internal Server Error\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n self.assertTrue(response_body.startswith(b\"Internal Server Error\"))\n self.assertEqual(", " sorted(headers.keys()), [\"connection\", \"content-length\", \"content-type\", \"date\", \"server\"]", " )\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_after_start_response_http11_close(self):\n to_send = tobytes(", " \"GET /after_start_response HTTP/1.1\\r\\nConnection: close\\r\\n\\r\\n\"", " )\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"500\", \"Internal Server Error\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n self.assertTrue(response_body.startswith(b\"Internal Server Error\"))\n self.assertEqual(\n sorted(headers.keys()),\n [\"connection\", \"content-length\", \"content-type\", \"date\", \"server\"],\n )\n self.assertEqual(headers[\"connection\"], \"close\")\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_after_write_cb(self):", " to_send = \"GET /after_write_cb HTTP/1.1\\r\\n\\r\\n\"", " to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n self.assertEqual(response_body, b\"\")\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_in_generator(self):", " to_send = \"GET /in_generator HTTP/1.1\\r\\n\\r\\n\"", " to_send = tobytes(to_send)\n self.connect()\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n self.assertEqual(response_body, b\"\")\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", "\nclass FileWrapperTests(object):\n def setUp(self):\n from waitress.tests.fixtureapps import filewrapper", " self.start_subprocess(filewrapper.app)", " def tearDown(self):\n self.stop_subprocess()", " def test_filelike_http11(self):", " to_send = \"GET /filelike HTTP/1.1\\r\\n\\r\\n\"", " to_send = tobytes(to_send)", " self.connect()", " for t in range(0, 2):\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has not been closed", " def test_filelike_nocl_http11(self):", " to_send = \"GET /filelike_nocl HTTP/1.1\\r\\n\\r\\n\"", " to_send = tobytes(to_send)", " self.connect()", " for t in range(0, 2):\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has not been closed", " def test_filelike_shortcl_http11(self):", " to_send = \"GET /filelike_shortcl HTTP/1.1\\r\\n\\r\\n\"", " to_send = tobytes(to_send)", " self.connect()", " for t in range(0, 2):\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, 1)\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\" in response_body)\n # connection has not been closed", " def test_filelike_longcl_http11(self):", " to_send = \"GET /filelike_longcl HTTP/1.1\\r\\n\\r\\n\"", " to_send = tobytes(to_send)", " self.connect()", " for t in range(0, 2):\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has not been closed", " def test_notfilelike_http11(self):", " to_send = \"GET /notfilelike HTTP/1.1\\r\\n\\r\\n\"", " to_send = tobytes(to_send)", " self.connect()", " for t in range(0, 2):\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has not been closed", " def test_notfilelike_iobase_http11(self):", " to_send = \"GET /notfilelike_iobase HTTP/1.1\\r\\n\\r\\n\"", " to_send = tobytes(to_send)", " self.connect()", " for t in range(0, 2):\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has not been closed", " def test_notfilelike_nocl_http11(self):", " to_send = \"GET /notfilelike_nocl HTTP/1.1\\r\\n\\r\\n\"", " to_send = tobytes(to_send)", " self.connect()", " self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has been closed (no content-length)\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_notfilelike_shortcl_http11(self):", " to_send = \"GET /notfilelike_shortcl HTTP/1.1\\r\\n\\r\\n\"", " to_send = tobytes(to_send)", " self.connect()", " for t in range(0, 2):\n self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, 1)\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\" in response_body)\n # connection has not been closed", " def test_notfilelike_longcl_http11(self):", " to_send = \"GET /notfilelike_longcl HTTP/1.1\\r\\n\\r\\n\"", " to_send = tobytes(to_send)", " self.connect()", " self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.1\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body) + 10)\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_filelike_http10(self):", " to_send = \"GET /filelike HTTP/1.0\\r\\n\\r\\n\"", " to_send = tobytes(to_send)", " self.connect()", " self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_filelike_nocl_http10(self):", " to_send = \"GET /filelike_nocl HTTP/1.0\\r\\n\\r\\n\"", " to_send = tobytes(to_send)", " self.connect()", " self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_notfilelike_http10(self):", " to_send = \"GET /notfilelike HTTP/1.0\\r\\n\\r\\n\"", " to_send = tobytes(to_send)", " self.connect()", " self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n cl = int(headers[\"content-length\"])\n self.assertEqual(cl, len(response_body))\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has been closed\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", " def test_notfilelike_nocl_http10(self):", " to_send = \"GET /notfilelike_nocl HTTP/1.0\\r\\n\\r\\n\"", " to_send = tobytes(to_send)", " self.connect()", " self.sock.send(to_send)\n fp = self.sock.makefile(\"rb\", 0)\n line, headers, response_body = read_http(fp)\n self.assertline(line, \"200\", \"OK\", \"HTTP/1.0\")\n ct = headers[\"content-type\"]\n self.assertEqual(ct, \"image/jpeg\")\n self.assertTrue(b\"\\377\\330\\377\" in response_body)\n # connection has been closed (no content-length)\n self.send_check_error(to_send)\n self.assertRaises(ConnectionClosed, read_http, fp)", "\nclass TcpEchoTests(EchoTests, TcpTests, unittest.TestCase):\n pass", "\nclass TcpPipeliningTests(PipeliningTests, TcpTests, unittest.TestCase):\n pass", "\nclass TcpExpectContinueTests(ExpectContinueTests, TcpTests, unittest.TestCase):\n pass", "\nclass TcpBadContentLengthTests(BadContentLengthTests, TcpTests, unittest.TestCase):\n pass", "\nclass TcpNoContentLengthTests(NoContentLengthTests, TcpTests, unittest.TestCase):\n pass", "\nclass TcpWriteCallbackTests(WriteCallbackTests, TcpTests, unittest.TestCase):\n pass", "\nclass TcpTooLargeTests(TooLargeTests, TcpTests, unittest.TestCase):\n pass", "\nclass TcpInternalServerErrorTests(\n InternalServerErrorTests, TcpTests, unittest.TestCase\n):\n pass", "\nclass TcpFileWrapperTests(FileWrapperTests, TcpTests, unittest.TestCase):\n pass", "\nif hasattr(socket, \"AF_UNIX\"):", " class FixtureUnixWSGIServer(server.UnixWSGIServer):\n \"\"\"A version of UnixWSGIServer that relays back what it's bound to.\n \"\"\"", " family = socket.AF_UNIX # Testing", " def __init__(self, application, queue, **kw): # pragma: no cover\n # Coverage doesn't see this as it's ran in a separate process.\n # To permit parallel testing, use a PID-dependent socket.\n kw[\"unix_socket\"] = \"/tmp/waitress.test-%d.sock\" % os.getpid()\n super(FixtureUnixWSGIServer, self).__init__(application, **kw)\n queue.put(self.socket.getsockname())", " class UnixTests(SubprocessTests):", " server = FixtureUnixWSGIServer", " def make_http_connection(self):\n return UnixHTTPConnection(self.bound_to)", " def stop_subprocess(self):\n super(UnixTests, self).stop_subprocess()\n cleanup_unix_socket(self.bound_to)", " def send_check_error(self, to_send):\n # Unlike inet domain sockets, Unix domain sockets can trigger a\n # 'Broken pipe' error when the socket it closed.\n try:\n self.sock.send(to_send)\n except socket.error as exc:\n self.assertEqual(get_errno(exc), errno.EPIPE)", " class UnixEchoTests(EchoTests, UnixTests, unittest.TestCase):\n pass", " class UnixPipeliningTests(PipeliningTests, UnixTests, unittest.TestCase):\n pass", " class UnixExpectContinueTests(ExpectContinueTests, UnixTests, unittest.TestCase):\n pass", " class UnixBadContentLengthTests(\n BadContentLengthTests, UnixTests, unittest.TestCase\n ):\n pass", " class UnixNoContentLengthTests(NoContentLengthTests, UnixTests, unittest.TestCase):\n pass", " class UnixWriteCallbackTests(WriteCallbackTests, UnixTests, unittest.TestCase):\n pass", " class UnixTooLargeTests(TooLargeTests, UnixTests, unittest.TestCase):\n pass", " class UnixInternalServerErrorTests(\n InternalServerErrorTests, UnixTests, unittest.TestCase\n ):\n pass", " class UnixFileWrapperTests(FileWrapperTests, UnixTests, unittest.TestCase):\n pass", "\ndef parse_headers(fp):\n \"\"\"Parses only RFC2822 headers from a file pointer.\n \"\"\"\n headers = {}\n while True:\n line = fp.readline()\n if line in (b\"\\r\\n\", b\"\\n\", b\"\"):\n break\n line = line.decode(\"iso-8859-1\")\n name, value = line.strip().split(\":\", 1)\n headers[name.lower().strip()] = value.lower().strip()\n return headers", "\nclass UnixHTTPConnection(httplib.HTTPConnection):\n \"\"\"Patched version of HTTPConnection that uses Unix domain sockets.\n \"\"\"", " def __init__(self, path):\n httplib.HTTPConnection.__init__(self, \"localhost\")\n self.path = path", " def connect(self):\n sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n sock.connect(self.path)\n self.sock = sock", "\nclass ConnectionClosed(Exception):\n pass", "\n# stolen from gevent\ndef read_http(fp): # pragma: no cover\n try:\n response_line = fp.readline()\n except socket.error as exc:\n fp.close()\n # errno 104 is ENOTRECOVERABLE, In WinSock 10054 is ECONNRESET\n if get_errno(exc) in (errno.ECONNABORTED, errno.ECONNRESET, 104, 10054):\n raise ConnectionClosed\n raise\n if not response_line:\n raise ConnectionClosed", " header_lines = []\n while True:\n line = fp.readline()", " if line in (b\"\\r\\n\", b\"\\r\\n\", b\"\"):", " break\n else:\n header_lines.append(line)\n headers = dict()\n for x in header_lines:\n x = x.strip()\n if not x:\n continue\n key, value = x.split(b\": \", 1)\n key = key.decode(\"iso-8859-1\").lower()\n value = value.decode(\"iso-8859-1\")\n assert key not in headers, \"%s header duplicated\" % key\n headers[key] = value", " if \"content-length\" in headers:\n num = int(headers[\"content-length\"])\n body = b\"\"\n left = num\n while left > 0:\n data = fp.read(left)\n if not data:\n break\n body += data\n left -= len(data)\n else:\n # read until EOF\n body = fp.read()", " return response_line, headers, body", "\n# stolen from gevent\ndef get_errno(exc): # pragma: no cover\n \"\"\" Get the error code out of socket.error objects.\n socket.error in <2.5 does not have errno attribute\n socket.error in 3.x does not allow indexing access\n e.args[0] works for all.\n There are cases when args[0] is not errno.\n i.e. http://bugs.python.org/issue6471\n Maybe there are cases when errno is set, but it is not the first argument?\n \"\"\"\n try:\n if exc.errno is not None:\n return exc.errno\n except AttributeError:\n pass\n try:\n return exc.args[0]\n except IndexError:\n return None", "\ndef chunks(l, n):\n \"\"\" Yield successive n-sized chunks from l.\n \"\"\"\n for i in range(0, len(l), n):\n yield l[i : i + n]" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "##############################################################################\n#\n# Copyright (c) 2002 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"HTTP Request Parser tests\n\"\"\"\nimport unittest\n", "from waitress.compat import (\n text_,\n tobytes,\n)", "", "class TestHTTPRequestParser(unittest.TestCase):\n def setUp(self):\n from waitress.parser import HTTPRequestParser\n from waitress.adjustments import Adjustments", " my_adj = Adjustments()\n self.parser = HTTPRequestParser(my_adj)", " def test_get_body_stream_None(self):\n self.parser.body_recv = None\n result = self.parser.get_body_stream()\n self.assertEqual(result.getvalue(), b\"\")", " def test_get_body_stream_nonNone(self):\n body_rcv = DummyBodyStream()\n self.parser.body_rcv = body_rcv\n result = self.parser.get_body_stream()\n self.assertEqual(result, body_rcv)\n", " def test_received_nonsense_with_double_cr(self):\n data = b\"\"\"\\\nHTTP/1.0 GET /foobar", "\n\"\"\"\n result = self.parser.received(data)\n self.assertEqual(result, 22)", " self.assertTrue(self.parser.completed)\n self.assertEqual(self.parser.headers, {})", " def test_received_bad_host_header(self):\n from waitress.utilities import BadRequest\n", " data = b\"\"\"\\\nHTTP/1.0 GET /foobar\n Host: foo", "\n\"\"\"\n result = self.parser.received(data)\n self.assertEqual(result, 33)", " self.assertTrue(self.parser.completed)\n self.assertEqual(self.parser.error.__class__, BadRequest)\n", "", " def test_received_nonsense_nothing(self):", " data = b\"\"\"\\", "\n\"\"\"\n result = self.parser.received(data)\n self.assertEqual(result, 2)", " self.assertTrue(self.parser.completed)\n self.assertEqual(self.parser.headers, {})", " def test_received_no_doublecr(self):", " data = b\"\"\"\\\nGET /foobar HTTP/8.4\n\"\"\"\n result = self.parser.received(data)\n self.assertEqual(result, 21)", " self.assertFalse(self.parser.completed)\n self.assertEqual(self.parser.headers, {})", " def test_received_already_completed(self):\n self.parser.completed = True\n result = self.parser.received(b\"a\")\n self.assertEqual(result, 0)", " def test_received_cl_too_large(self):\n from waitress.utilities import RequestEntityTooLarge", " self.parser.adj.max_request_body_size = 2", " data = b\"\"\"\\\nGET /foobar HTTP/8.4\nContent-Length: 10", "\"\"\"\n result = self.parser.received(data)\n self.assertEqual(result, 41)", " self.assertTrue(self.parser.completed)\n self.assertTrue(isinstance(self.parser.error, RequestEntityTooLarge))", " def test_received_headers_too_large(self):\n from waitress.utilities import RequestHeaderFieldsTooLarge", " self.parser.adj.max_request_header_size = 2", " data = b\"\"\"\\\nGET /foobar HTTP/8.4\nX-Foo: 1\n\"\"\"\n result = self.parser.received(data)\n self.assertEqual(result, 30)", " self.assertTrue(self.parser.completed)\n self.assertTrue(isinstance(self.parser.error, RequestHeaderFieldsTooLarge))", " def test_received_body_too_large(self):\n from waitress.utilities import RequestEntityTooLarge", " self.parser.adj.max_request_body_size = 2", " data = b\"\"\"\\\nGET /foobar HTTP/1.1\nTransfer-Encoding: chunked\nX-Foo: 1", "20;\\r\\n\nThis string has 32 characters\\r\\n\n0\\r\\n\\r\\n\"\"\"\n result = self.parser.received(data)\n self.assertEqual(result, 58)", " self.parser.received(data[result:])\n self.assertTrue(self.parser.completed)\n self.assertTrue(isinstance(self.parser.error, RequestEntityTooLarge))", " def test_received_error_from_parser(self):\n from waitress.utilities import BadRequest\n", " data = b\"\"\"\\\nGET /foobar HTTP/1.1\nTransfer-Encoding: chunked\nX-Foo: 1", "garbage\n\"\"\"", " # header\n result = self.parser.received(data)\n # body\n result = self.parser.received(data[result:])", " self.assertEqual(result, 8)", " self.assertTrue(self.parser.completed)\n self.assertTrue(isinstance(self.parser.error, BadRequest))", " def test_received_chunked_completed_sets_content_length(self):", " data = b\"\"\"\\\nGET /foobar HTTP/1.1\nTransfer-Encoding: chunked\nX-Foo: 1", "20;\\r\\n\nThis string has 32 characters\\r\\n\n0\\r\\n\\r\\n\"\"\"\n result = self.parser.received(data)\n self.assertEqual(result, 58)", " data = data[result:]\n result = self.parser.received(data)\n self.assertTrue(self.parser.completed)\n self.assertTrue(self.parser.error is None)", " self.assertEqual(self.parser.headers[\"CONTENT_LENGTH\"], \"32\")", "\n def test_parse_header_gardenpath(self):", " data = b\"\"\"\\\nGET /foobar HTTP/8.4\nfoo: bar\"\"\"", " self.parser.parse_header(data)\n self.assertEqual(self.parser.first_line, b\"GET /foobar HTTP/8.4\")\n self.assertEqual(self.parser.headers[\"FOO\"], \"bar\")", " def test_parse_header_no_cr_in_headerplus(self):", "", " data = b\"GET /foobar HTTP/8.4\"", " self.parser.parse_header(data)\n self.assertEqual(self.parser.first_line, data)", "\n def test_parse_header_bad_content_length(self):", " data = b\"GET /foobar HTTP/8.4\\ncontent-length: abc\"\n self.parser.parse_header(data)\n self.assertEqual(self.parser.body_rcv, None)", "\n def test_parse_header_11_te_chunked(self):\n # NB: test that capitalization of header value is unimportant", " data = b\"GET /foobar HTTP/1.1\\ntransfer-encoding: ChUnKed\"", " self.parser.parse_header(data)\n self.assertEqual(self.parser.body_rcv.__class__.__name__, \"ChunkedReceiver\")\n", "", " def test_parse_header_11_expect_continue(self):", " data = b\"GET /foobar HTTP/1.1\\nexpect: 100-continue\"", " self.parser.parse_header(data)\n self.assertEqual(self.parser.expect_continue, True)", " def test_parse_header_connection_close(self):", " data = b\"GET /foobar HTTP/1.1\\nConnection: close\\n\\n\"", " self.parser.parse_header(data)\n self.assertEqual(self.parser.connection_close, True)", " def test_close_with_body_rcv(self):\n body_rcv = DummyBodyStream()\n self.parser.body_rcv = body_rcv\n self.parser.close()\n self.assertTrue(body_rcv.closed)", " def test_close_with_no_body_rcv(self):\n self.parser.body_rcv = None\n self.parser.close() # doesn't raise", "", "", "class Test_split_uri(unittest.TestCase):\n def _callFUT(self, uri):\n from waitress.parser import split_uri", " (\n self.proxy_scheme,\n self.proxy_netloc,\n self.path,\n self.query,\n self.fragment,\n ) = split_uri(uri)", " def test_split_uri_unquoting_unneeded(self):\n self._callFUT(b\"http://localhost:8080/abc def\")\n self.assertEqual(self.path, \"/abc def\")", " def test_split_uri_unquoting_needed(self):\n self._callFUT(b\"http://localhost:8080/abc%20def\")\n self.assertEqual(self.path, \"/abc def\")", " def test_split_url_with_query(self):\n self._callFUT(b\"http://localhost:8080/abc?a=1&b=2\")\n self.assertEqual(self.path, \"/abc\")\n self.assertEqual(self.query, \"a=1&b=2\")", " def test_split_url_with_query_empty(self):\n self._callFUT(b\"http://localhost:8080/abc?\")\n self.assertEqual(self.path, \"/abc\")\n self.assertEqual(self.query, \"\")", " def test_split_url_with_fragment(self):\n self._callFUT(b\"http://localhost:8080/#foo\")\n self.assertEqual(self.path, \"/\")\n self.assertEqual(self.fragment, \"foo\")", " def test_split_url_https(self):\n self._callFUT(b\"https://localhost:8080/\")\n self.assertEqual(self.path, \"/\")\n self.assertEqual(self.proxy_scheme, \"https\")\n self.assertEqual(self.proxy_netloc, \"localhost:8080\")", " def test_split_uri_unicode_error_raises_parsing_error(self):\n # See https://github.com/Pylons/waitress/issues/64\n from waitress.parser import ParsingError", " # Either pass or throw a ParsingError, just don't throw another type of\n # exception as that will cause the connection to close badly:\n try:\n self._callFUT(b\"/\\xd0\")\n except ParsingError:\n pass", " def test_split_uri_path(self):\n self._callFUT(b\"//testing/whatever\")\n self.assertEqual(self.path, \"//testing/whatever\")\n self.assertEqual(self.proxy_scheme, \"\")\n self.assertEqual(self.proxy_netloc, \"\")\n self.assertEqual(self.query, \"\")\n self.assertEqual(self.fragment, \"\")", " def test_split_uri_path_query(self):\n self._callFUT(b\"//testing/whatever?a=1&b=2\")\n self.assertEqual(self.path, \"//testing/whatever\")\n self.assertEqual(self.proxy_scheme, \"\")\n self.assertEqual(self.proxy_netloc, \"\")\n self.assertEqual(self.query, \"a=1&b=2\")\n self.assertEqual(self.fragment, \"\")", " def test_split_uri_path_query_fragment(self):\n self._callFUT(b\"//testing/whatever?a=1&b=2#fragment\")\n self.assertEqual(self.path, \"//testing/whatever\")\n self.assertEqual(self.proxy_scheme, \"\")\n self.assertEqual(self.proxy_netloc, \"\")\n self.assertEqual(self.query, \"a=1&b=2\")\n self.assertEqual(self.fragment, \"fragment\")", "\nclass Test_get_header_lines(unittest.TestCase):\n def _callFUT(self, data):\n from waitress.parser import get_header_lines", " return get_header_lines(data)", " def test_get_header_lines(self):", " result = self._callFUT(b\"slam\\nslim\")", " self.assertEqual(result, [b\"slam\", b\"slim\"])", " def test_get_header_lines_folded(self):\n # From RFC2616:\n # HTTP/1.1 header field values can be folded onto multiple lines if the\n # continuation line begins with a space or horizontal tab. All linear\n # white space, including folding, has the same semantics as SP. A\n # recipient MAY replace any linear white space with a single SP before\n # interpreting the field value or forwarding the message downstream.", " # We are just preserving the whitespace that indicates folding.", " result = self._callFUT(b\"slim\\n slam\")", " self.assertEqual(result, [b\"slim slam\"])", " def test_get_header_lines_tabbed(self):", " result = self._callFUT(b\"slam\\n\\tslim\")", " self.assertEqual(result, [b\"slam\\tslim\"])", " def test_get_header_lines_malformed(self):\n # https://corte.si/posts/code/pathod/pythonservers/index.html\n from waitress.parser import ParsingError", " self.assertRaises(ParsingError, self._callFUT, b\" Host: localhost\\r\\n\\r\\n\")", "\nclass Test_crack_first_line(unittest.TestCase):\n def _callFUT(self, line):\n from waitress.parser import crack_first_line", " return crack_first_line(line)", " def test_crack_first_line_matchok(self):\n result = self._callFUT(b\"GET / HTTP/1.0\")\n self.assertEqual(result, (b\"GET\", b\"/\", b\"1.0\"))", " def test_crack_first_line_lowercase_method(self):\n from waitress.parser import ParsingError", " self.assertRaises(ParsingError, self._callFUT, b\"get / HTTP/1.0\")", " def test_crack_first_line_nomatch(self):\n result = self._callFUT(b\"GET / bleh\")\n self.assertEqual(result, (b\"\", b\"\", b\"\"))", " result = self._callFUT(b\"GET /info?txtAirPlay&txtRAOP RTSP/1.0\")\n self.assertEqual(result, (b\"\", b\"\", b\"\"))", " def test_crack_first_line_missing_version(self):\n result = self._callFUT(b\"GET /\")\n self.assertEqual(result, (b\"GET\", b\"/\", b\"\"))", "\nclass TestHTTPRequestParserIntegration(unittest.TestCase):\n def setUp(self):\n from waitress.parser import HTTPRequestParser\n from waitress.adjustments import Adjustments", " my_adj = Adjustments()\n self.parser = HTTPRequestParser(my_adj)", " def feed(self, data):\n parser = self.parser", "", " for n in range(100): # make sure we never loop forever\n consumed = parser.received(data)\n data = data[consumed:]", "", " if parser.completed:\n return\n raise ValueError(\"Looping\") # pragma: no cover", " def testSimpleGET(self):", " data = b\"\"\"\\\nGET /foobar HTTP/8.4\nFirstName: mickey\nlastname: Mouse\ncontent-length: 7", "Hello.\n\"\"\"", " parser = self.parser\n self.feed(data)\n self.assertTrue(parser.completed)\n self.assertEqual(parser.version, \"8.4\")\n self.assertFalse(parser.empty)\n self.assertEqual(\n parser.headers,", " {\"FIRSTNAME\": \"mickey\", \"LASTNAME\": \"Mouse\", \"CONTENT_LENGTH\": \"7\",},", " )\n self.assertEqual(parser.path, \"/foobar\")\n self.assertEqual(parser.command, \"GET\")\n self.assertEqual(parser.query, \"\")\n self.assertEqual(parser.proxy_scheme, \"\")\n self.assertEqual(parser.proxy_netloc, \"\")", " self.assertEqual(parser.get_body_stream().getvalue(), b\"Hello.\\n\")", "\n def testComplexGET(self):", " data = b\"\"\"\\\nGET /foo/a+%2B%2F%C3%A4%3D%26a%3Aint?d=b+%2B%2F%3D%26b%3Aint&c+%2B%2F%3D%26c%3Aint=6 HTTP/8.4\nFirstName: mickey\nlastname: Mouse\ncontent-length: 10", "Hello mickey.\n\"\"\"", " parser = self.parser\n self.feed(data)\n self.assertEqual(parser.command, \"GET\")\n self.assertEqual(parser.version, \"8.4\")\n self.assertFalse(parser.empty)\n self.assertEqual(\n parser.headers,", " {\"FIRSTNAME\": \"mickey\", \"LASTNAME\": \"Mouse\", \"CONTENT_LENGTH\": \"10\",},", " )\n # path should be utf-8 encoded\n self.assertEqual(\n tobytes(parser.path).decode(\"utf-8\"),\n text_(b\"/foo/a++/\\xc3\\xa4=&a:int\", \"utf-8\"),\n )\n self.assertEqual(\n parser.query, \"d=b+%2B%2F%3D%26b%3Aint&c+%2B%2F%3D%26c%3Aint=6\"\n )\n self.assertEqual(parser.get_body_stream().getvalue(), b\"Hello mick\")", " def testProxyGET(self):", " data = b\"\"\"\\\nGET https://example.com:8080/foobar HTTP/8.4\ncontent-length: 7", "Hello.\n\"\"\"", " parser = self.parser\n self.feed(data)\n self.assertTrue(parser.completed)\n self.assertEqual(parser.version, \"8.4\")\n self.assertFalse(parser.empty)", " self.assertEqual(parser.headers, {\"CONTENT_LENGTH\": \"7\",})", " self.assertEqual(parser.path, \"/foobar\")\n self.assertEqual(parser.command, \"GET\")\n self.assertEqual(parser.proxy_scheme, \"https\")\n self.assertEqual(parser.proxy_netloc, \"example.com:8080\")\n self.assertEqual(parser.command, \"GET\")\n self.assertEqual(parser.query, \"\")", " self.assertEqual(parser.get_body_stream().getvalue(), b\"Hello.\\n\")", "\n def testDuplicateHeaders(self):\n # Ensure that headers with the same key get concatenated as per\n # RFC2616.", " data = b\"\"\"\\\nGET /foobar HTTP/8.4\nx-forwarded-for: 10.11.12.13\nx-forwarded-for: unknown,127.0.0.1\nX-Forwarded_for: 255.255.255.255\ncontent-length: 7", "Hello.\n\"\"\"", " self.feed(data)\n self.assertTrue(self.parser.completed)\n self.assertEqual(\n self.parser.headers,\n {", " \"CONTENT_LENGTH\": \"7\",", " \"X_FORWARDED_FOR\": \"10.11.12.13, unknown,127.0.0.1\",\n },\n )", " def testSpoofedHeadersDropped(self):", " data = b\"\"\"\\\nGET /foobar HTTP/8.4\nx-auth_user: bob\ncontent-length: 7", "Hello.\n\"\"\"", " self.feed(data)\n self.assertTrue(self.parser.completed)", " self.assertEqual(self.parser.headers, {\"CONTENT_LENGTH\": \"7\",})", "", "class DummyBodyStream(object):\n def getfile(self):\n return self", " def getbuf(self):\n return self", " def close(self):\n self.closed = True" ]
[ 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "##############################################################################\n#\n# Copyright (c) 2002 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"HTTP Request Parser tests\n\"\"\"\nimport unittest\n", "from waitress.compat import text_, tobytes", "", "class TestHTTPRequestParser(unittest.TestCase):\n def setUp(self):\n from waitress.parser import HTTPRequestParser\n from waitress.adjustments import Adjustments", " my_adj = Adjustments()\n self.parser = HTTPRequestParser(my_adj)", " def test_get_body_stream_None(self):\n self.parser.body_recv = None\n result = self.parser.get_body_stream()\n self.assertEqual(result.getvalue(), b\"\")", " def test_get_body_stream_nonNone(self):\n body_rcv = DummyBodyStream()\n self.parser.body_rcv = body_rcv\n result = self.parser.get_body_stream()\n self.assertEqual(result, body_rcv)\n", " def test_received_get_no_headers(self):\n data = b\"HTTP/1.0 GET /foobar\\r\\n\\r\\n\"\n result = self.parser.received(data)\n self.assertEqual(result, 24)", " self.assertTrue(self.parser.completed)\n self.assertEqual(self.parser.headers, {})", " def test_received_bad_host_header(self):\n from waitress.utilities import BadRequest\n", " data = b\"HTTP/1.0 GET /foobar\\r\\n Host: foo\\r\\n\\r\\n\"\n result = self.parser.received(data)\n self.assertEqual(result, 36)", " self.assertTrue(self.parser.completed)\n self.assertEqual(self.parser.error.__class__, BadRequest)\n", " def test_received_bad_transfer_encoding(self):\n from waitress.utilities import ServerNotImplemented\n data = (\n b\"GET /foobar HTTP/1.1\\r\\n\"\n b\"Transfer-Encoding: foo\\r\\n\"\n b\"\\r\\n\"\n b\"1d;\\r\\n\"\n b\"This string has 29 characters\\r\\n\"\n b\"0\\r\\n\\r\\n\"\n )\n result = self.parser.received(data)\n self.assertEqual(result, 48)\n self.assertTrue(self.parser.completed)\n self.assertEqual(self.parser.error.__class__, ServerNotImplemented)\n", " def test_received_nonsense_nothing(self):", " data = b\"\\r\\n\\r\\n\"\n result = self.parser.received(data)\n self.assertEqual(result, 4)", " self.assertTrue(self.parser.completed)\n self.assertEqual(self.parser.headers, {})", " def test_received_no_doublecr(self):", " data = b\"GET /foobar HTTP/8.4\\r\\n\"\n result = self.parser.received(data)\n self.assertEqual(result, 22)", " self.assertFalse(self.parser.completed)\n self.assertEqual(self.parser.headers, {})", " def test_received_already_completed(self):\n self.parser.completed = True\n result = self.parser.received(b\"a\")\n self.assertEqual(result, 0)", " def test_received_cl_too_large(self):\n from waitress.utilities import RequestEntityTooLarge", " self.parser.adj.max_request_body_size = 2", " data = b\"GET /foobar HTTP/8.4\\r\\nContent-Length: 10\\r\\n\\r\\n\"\n result = self.parser.received(data)\n self.assertEqual(result, 44)", " self.assertTrue(self.parser.completed)\n self.assertTrue(isinstance(self.parser.error, RequestEntityTooLarge))", " def test_received_headers_too_large(self):\n from waitress.utilities import RequestHeaderFieldsTooLarge", " self.parser.adj.max_request_header_size = 2", " data = b\"GET /foobar HTTP/8.4\\r\\nX-Foo: 1\\r\\n\\r\\n\"\n result = self.parser.received(data)\n self.assertEqual(result, 34)", " self.assertTrue(self.parser.completed)\n self.assertTrue(isinstance(self.parser.error, RequestHeaderFieldsTooLarge))", " def test_received_body_too_large(self):\n from waitress.utilities import RequestEntityTooLarge", " self.parser.adj.max_request_body_size = 2", " data = (\n b\"GET /foobar HTTP/1.1\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\"\n b\"X-Foo: 1\\r\\n\"\n b\"\\r\\n\"\n b\"1d;\\r\\n\"\n b\"This string has 29 characters\\r\\n\"\n b\"0\\r\\n\\r\\n\"\n )", " result = self.parser.received(data)\n self.assertEqual(result, 62)", " self.parser.received(data[result:])\n self.assertTrue(self.parser.completed)\n self.assertTrue(isinstance(self.parser.error, RequestEntityTooLarge))", " def test_received_error_from_parser(self):\n from waitress.utilities import BadRequest\n", " data = (\n b\"GET /foobar HTTP/1.1\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\"\n b\"X-Foo: 1\\r\\n\"\n b\"\\r\\n\"\n b\"garbage\\r\\n\"\n )", " # header\n result = self.parser.received(data)\n # body\n result = self.parser.received(data[result:])", " self.assertEqual(result, 9)", " self.assertTrue(self.parser.completed)\n self.assertTrue(isinstance(self.parser.error, BadRequest))", " def test_received_chunked_completed_sets_content_length(self):", " data = (\n b\"GET /foobar HTTP/1.1\\r\\n\"\n b\"Transfer-Encoding: chunked\\r\\n\"\n b\"X-Foo: 1\\r\\n\"\n b\"\\r\\n\"\n b\"1d;\\r\\n\"\n b\"This string has 29 characters\\r\\n\"\n b\"0\\r\\n\\r\\n\"\n )\n result = self.parser.received(data)\n self.assertEqual(result, 62)", " data = data[result:]\n result = self.parser.received(data)\n self.assertTrue(self.parser.completed)\n self.assertTrue(self.parser.error is None)", " self.assertEqual(self.parser.headers[\"CONTENT_LENGTH\"], \"29\")", "\n def test_parse_header_gardenpath(self):", " data = b\"GET /foobar HTTP/8.4\\r\\nfoo: bar\\r\\n\"", " self.parser.parse_header(data)\n self.assertEqual(self.parser.first_line, b\"GET /foobar HTTP/8.4\")\n self.assertEqual(self.parser.headers[\"FOO\"], \"bar\")", " def test_parse_header_no_cr_in_headerplus(self):", " from waitress.parser import ParsingError\n", " data = b\"GET /foobar HTTP/8.4\"", "\n try:\n self.parser.parse_header(data)\n except ParsingError:\n pass\n else: # pragma: nocover\n self.assertTrue(False)", "\n def test_parse_header_bad_content_length(self):", " from waitress.parser import ParsingError", " data = b\"GET /foobar HTTP/8.4\\r\\ncontent-length: abc\\r\\n\"", " try:\n self.parser.parse_header(data)\n except ParsingError as e:\n self.assertIn(\"Content-Length is invalid\", e.args[0])\n else: # pragma: nocover\n self.assertTrue(False)", " def test_parse_header_multiple_content_length(self):\n from waitress.parser import ParsingError", " data = b\"GET /foobar HTTP/8.4\\r\\ncontent-length: 10\\r\\ncontent-length: 20\\r\\n\"", " try:\n self.parser.parse_header(data)\n except ParsingError as e:\n self.assertIn(\"Content-Length is invalid\", e.args[0])\n else: # pragma: nocover\n self.assertTrue(False)", "\n def test_parse_header_11_te_chunked(self):\n # NB: test that capitalization of header value is unimportant", " data = b\"GET /foobar HTTP/1.1\\r\\ntransfer-encoding: ChUnKed\\r\\n\"", " self.parser.parse_header(data)\n self.assertEqual(self.parser.body_rcv.__class__.__name__, \"ChunkedReceiver\")\n", "\n def test_parse_header_transfer_encoding_invalid(self):\n from waitress.parser import TransferEncodingNotImplemented", " data = b\"GET /foobar HTTP/1.1\\r\\ntransfer-encoding: gzip\\r\\n\"", " try:\n self.parser.parse_header(data)\n except TransferEncodingNotImplemented as e:\n self.assertIn(\"Transfer-Encoding requested is not supported.\", e.args[0])\n else: # pragma: nocover\n self.assertTrue(False)", " def test_parse_header_transfer_encoding_invalid_multiple(self):\n from waitress.parser import TransferEncodingNotImplemented", " data = b\"GET /foobar HTTP/1.1\\r\\ntransfer-encoding: gzip\\r\\ntransfer-encoding: chunked\\r\\n\"", " try:\n self.parser.parse_header(data)\n except TransferEncodingNotImplemented as e:\n self.assertIn(\"Transfer-Encoding requested is not supported.\", e.args[0])\n else: # pragma: nocover\n self.assertTrue(False)\n", " def test_parse_header_11_expect_continue(self):", " data = b\"GET /foobar HTTP/1.1\\r\\nexpect: 100-continue\\r\\n\"", " self.parser.parse_header(data)\n self.assertEqual(self.parser.expect_continue, True)", " def test_parse_header_connection_close(self):", " data = b\"GET /foobar HTTP/1.1\\r\\nConnection: close\\r\\n\"", " self.parser.parse_header(data)\n self.assertEqual(self.parser.connection_close, True)", " def test_close_with_body_rcv(self):\n body_rcv = DummyBodyStream()\n self.parser.body_rcv = body_rcv\n self.parser.close()\n self.assertTrue(body_rcv.closed)", " def test_close_with_no_body_rcv(self):\n self.parser.body_rcv = None\n self.parser.close() # doesn't raise", "\n def test_parse_header_lf_only(self):\n from waitress.parser import ParsingError", " data = b\"GET /foobar HTTP/8.4\\nfoo: bar\"", " try:\n self.parser.parse_header(data)\n except ParsingError:\n pass\n else: # pragma: nocover\n self.assertTrue(False)", " def test_parse_header_cr_only(self):\n from waitress.parser import ParsingError", " data = b\"GET /foobar HTTP/8.4\\rfoo: bar\"\n try:\n self.parser.parse_header(data)\n except ParsingError:\n pass\n else: # pragma: nocover\n self.assertTrue(False)", " def test_parse_header_extra_lf_in_header(self):\n from waitress.parser import ParsingError", " data = b\"GET /foobar HTTP/8.4\\r\\nfoo: \\nbar\\r\\n\"\n try:\n self.parser.parse_header(data)\n except ParsingError as e:\n self.assertIn(\"Bare CR or LF found in header line\", e.args[0])\n else: # pragma: nocover\n self.assertTrue(False)", " def test_parse_header_extra_lf_in_first_line(self):\n from waitress.parser import ParsingError", " data = b\"GET /foobar\\n HTTP/8.4\\r\\n\"\n try:\n self.parser.parse_header(data)\n except ParsingError as e:\n self.assertIn(\"Bare CR or LF found in HTTP message\", e.args[0])\n else: # pragma: nocover\n self.assertTrue(False)", " def test_parse_header_invalid_whitespace(self):\n from waitress.parser import ParsingError", " data = b\"GET /foobar HTTP/8.4\\r\\nfoo : bar\\r\\n\"\n try:\n self.parser.parse_header(data)\n except ParsingError as e:\n self.assertIn(\"Invalid whitespace after field-name\", e.args[0])\n else: # pragma: nocover\n self.assertTrue(False)", "", "class Test_split_uri(unittest.TestCase):\n def _callFUT(self, uri):\n from waitress.parser import split_uri", " (\n self.proxy_scheme,\n self.proxy_netloc,\n self.path,\n self.query,\n self.fragment,\n ) = split_uri(uri)", " def test_split_uri_unquoting_unneeded(self):\n self._callFUT(b\"http://localhost:8080/abc def\")\n self.assertEqual(self.path, \"/abc def\")", " def test_split_uri_unquoting_needed(self):\n self._callFUT(b\"http://localhost:8080/abc%20def\")\n self.assertEqual(self.path, \"/abc def\")", " def test_split_url_with_query(self):\n self._callFUT(b\"http://localhost:8080/abc?a=1&b=2\")\n self.assertEqual(self.path, \"/abc\")\n self.assertEqual(self.query, \"a=1&b=2\")", " def test_split_url_with_query_empty(self):\n self._callFUT(b\"http://localhost:8080/abc?\")\n self.assertEqual(self.path, \"/abc\")\n self.assertEqual(self.query, \"\")", " def test_split_url_with_fragment(self):\n self._callFUT(b\"http://localhost:8080/#foo\")\n self.assertEqual(self.path, \"/\")\n self.assertEqual(self.fragment, \"foo\")", " def test_split_url_https(self):\n self._callFUT(b\"https://localhost:8080/\")\n self.assertEqual(self.path, \"/\")\n self.assertEqual(self.proxy_scheme, \"https\")\n self.assertEqual(self.proxy_netloc, \"localhost:8080\")", " def test_split_uri_unicode_error_raises_parsing_error(self):\n # See https://github.com/Pylons/waitress/issues/64\n from waitress.parser import ParsingError", " # Either pass or throw a ParsingError, just don't throw another type of\n # exception as that will cause the connection to close badly:\n try:\n self._callFUT(b\"/\\xd0\")\n except ParsingError:\n pass", " def test_split_uri_path(self):\n self._callFUT(b\"//testing/whatever\")\n self.assertEqual(self.path, \"//testing/whatever\")\n self.assertEqual(self.proxy_scheme, \"\")\n self.assertEqual(self.proxy_netloc, \"\")\n self.assertEqual(self.query, \"\")\n self.assertEqual(self.fragment, \"\")", " def test_split_uri_path_query(self):\n self._callFUT(b\"//testing/whatever?a=1&b=2\")\n self.assertEqual(self.path, \"//testing/whatever\")\n self.assertEqual(self.proxy_scheme, \"\")\n self.assertEqual(self.proxy_netloc, \"\")\n self.assertEqual(self.query, \"a=1&b=2\")\n self.assertEqual(self.fragment, \"\")", " def test_split_uri_path_query_fragment(self):\n self._callFUT(b\"//testing/whatever?a=1&b=2#fragment\")\n self.assertEqual(self.path, \"//testing/whatever\")\n self.assertEqual(self.proxy_scheme, \"\")\n self.assertEqual(self.proxy_netloc, \"\")\n self.assertEqual(self.query, \"a=1&b=2\")\n self.assertEqual(self.fragment, \"fragment\")", "\nclass Test_get_header_lines(unittest.TestCase):\n def _callFUT(self, data):\n from waitress.parser import get_header_lines", " return get_header_lines(data)", " def test_get_header_lines(self):", " result = self._callFUT(b\"slam\\r\\nslim\")", " self.assertEqual(result, [b\"slam\", b\"slim\"])", " def test_get_header_lines_folded(self):\n # From RFC2616:\n # HTTP/1.1 header field values can be folded onto multiple lines if the\n # continuation line begins with a space or horizontal tab. All linear\n # white space, including folding, has the same semantics as SP. A\n # recipient MAY replace any linear white space with a single SP before\n # interpreting the field value or forwarding the message downstream.", " # We are just preserving the whitespace that indicates folding.", " result = self._callFUT(b\"slim\\r\\n slam\")", " self.assertEqual(result, [b\"slim slam\"])", " def test_get_header_lines_tabbed(self):", " result = self._callFUT(b\"slam\\r\\n\\tslim\")", " self.assertEqual(result, [b\"slam\\tslim\"])", " def test_get_header_lines_malformed(self):\n # https://corte.si/posts/code/pathod/pythonservers/index.html\n from waitress.parser import ParsingError", " self.assertRaises(ParsingError, self._callFUT, b\" Host: localhost\\r\\n\\r\\n\")", "\nclass Test_crack_first_line(unittest.TestCase):\n def _callFUT(self, line):\n from waitress.parser import crack_first_line", " return crack_first_line(line)", " def test_crack_first_line_matchok(self):\n result = self._callFUT(b\"GET / HTTP/1.0\")\n self.assertEqual(result, (b\"GET\", b\"/\", b\"1.0\"))", " def test_crack_first_line_lowercase_method(self):\n from waitress.parser import ParsingError", " self.assertRaises(ParsingError, self._callFUT, b\"get / HTTP/1.0\")", " def test_crack_first_line_nomatch(self):\n result = self._callFUT(b\"GET / bleh\")\n self.assertEqual(result, (b\"\", b\"\", b\"\"))", " result = self._callFUT(b\"GET /info?txtAirPlay&txtRAOP RTSP/1.0\")\n self.assertEqual(result, (b\"\", b\"\", b\"\"))", " def test_crack_first_line_missing_version(self):\n result = self._callFUT(b\"GET /\")\n self.assertEqual(result, (b\"GET\", b\"/\", b\"\"))", "\nclass TestHTTPRequestParserIntegration(unittest.TestCase):\n def setUp(self):\n from waitress.parser import HTTPRequestParser\n from waitress.adjustments import Adjustments", " my_adj = Adjustments()\n self.parser = HTTPRequestParser(my_adj)", " def feed(self, data):\n parser = self.parser", "", " for n in range(100): # make sure we never loop forever\n consumed = parser.received(data)\n data = data[consumed:]", "", " if parser.completed:\n return\n raise ValueError(\"Looping\") # pragma: no cover", " def testSimpleGET(self):", " data = (\n b\"GET /foobar HTTP/8.4\\r\\n\"\n b\"FirstName: mickey\\r\\n\"\n b\"lastname: Mouse\\r\\n\"\n b\"content-length: 6\\r\\n\"\n b\"\\r\\n\"\n b\"Hello.\"\n )", " parser = self.parser\n self.feed(data)\n self.assertTrue(parser.completed)\n self.assertEqual(parser.version, \"8.4\")\n self.assertFalse(parser.empty)\n self.assertEqual(\n parser.headers,", " {\"FIRSTNAME\": \"mickey\", \"LASTNAME\": \"Mouse\", \"CONTENT_LENGTH\": \"6\",},", " )\n self.assertEqual(parser.path, \"/foobar\")\n self.assertEqual(parser.command, \"GET\")\n self.assertEqual(parser.query, \"\")\n self.assertEqual(parser.proxy_scheme, \"\")\n self.assertEqual(parser.proxy_netloc, \"\")", " self.assertEqual(parser.get_body_stream().getvalue(), b\"Hello.\")", "\n def testComplexGET(self):", " data = (\n b\"GET /foo/a+%2B%2F%C3%A4%3D%26a%3Aint?d=b+%2B%2F%3D%26b%3Aint&c+%2B%2F%3D%26c%3Aint=6 HTTP/8.4\\r\\n\"\n b\"FirstName: mickey\\r\\n\"\n b\"lastname: Mouse\\r\\n\"\n b\"content-length: 10\\r\\n\"\n b\"\\r\\n\"\n b\"Hello mickey.\"\n )", " parser = self.parser\n self.feed(data)\n self.assertEqual(parser.command, \"GET\")\n self.assertEqual(parser.version, \"8.4\")\n self.assertFalse(parser.empty)\n self.assertEqual(\n parser.headers,", " {\"FIRSTNAME\": \"mickey\", \"LASTNAME\": \"Mouse\", \"CONTENT_LENGTH\": \"10\"},", " )\n # path should be utf-8 encoded\n self.assertEqual(\n tobytes(parser.path).decode(\"utf-8\"),\n text_(b\"/foo/a++/\\xc3\\xa4=&a:int\", \"utf-8\"),\n )\n self.assertEqual(\n parser.query, \"d=b+%2B%2F%3D%26b%3Aint&c+%2B%2F%3D%26c%3Aint=6\"\n )\n self.assertEqual(parser.get_body_stream().getvalue(), b\"Hello mick\")", " def testProxyGET(self):", " data = (\n b\"GET https://example.com:8080/foobar HTTP/8.4\\r\\n\"\n b\"content-length: 6\\r\\n\"\n b\"\\r\\n\"\n b\"Hello.\"\n )", " parser = self.parser\n self.feed(data)\n self.assertTrue(parser.completed)\n self.assertEqual(parser.version, \"8.4\")\n self.assertFalse(parser.empty)", " self.assertEqual(parser.headers, {\"CONTENT_LENGTH\": \"6\"})", " self.assertEqual(parser.path, \"/foobar\")\n self.assertEqual(parser.command, \"GET\")\n self.assertEqual(parser.proxy_scheme, \"https\")\n self.assertEqual(parser.proxy_netloc, \"example.com:8080\")\n self.assertEqual(parser.command, \"GET\")\n self.assertEqual(parser.query, \"\")", " self.assertEqual(parser.get_body_stream().getvalue(), b\"Hello.\")", "\n def testDuplicateHeaders(self):\n # Ensure that headers with the same key get concatenated as per\n # RFC2616.", " data = (\n b\"GET /foobar HTTP/8.4\\r\\n\"\n b\"x-forwarded-for: 10.11.12.13\\r\\n\"\n b\"x-forwarded-for: unknown,127.0.0.1\\r\\n\"\n b\"X-Forwarded_for: 255.255.255.255\\r\\n\"\n b\"content-length: 6\\r\\n\"\n b\"\\r\\n\"\n b\"Hello.\"\n )", " self.feed(data)\n self.assertTrue(self.parser.completed)\n self.assertEqual(\n self.parser.headers,\n {", " \"CONTENT_LENGTH\": \"6\",", " \"X_FORWARDED_FOR\": \"10.11.12.13, unknown,127.0.0.1\",\n },\n )", " def testSpoofedHeadersDropped(self):", " data = (\n b\"GET /foobar HTTP/8.4\\r\\n\"\n b\"x-auth_user: bob\\r\\n\"\n b\"content-length: 6\\r\\n\"\n b\"\\r\\n\"\n b\"Hello.\"\n )", " self.feed(data)\n self.assertTrue(self.parser.completed)", " self.assertEqual(self.parser.headers, {\"CONTENT_LENGTH\": \"6\",})", "", "class DummyBodyStream(object):\n def getfile(self):\n return self", " def getbuf(self):\n return self", " def close(self):\n self.closed = True" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "import unittest", "\nclass TestFixedStreamReceiver(unittest.TestCase):\n def _makeOne(self, cl, buf):\n from waitress.receiver import FixedStreamReceiver", " return FixedStreamReceiver(cl, buf)", " def test_received_remain_lt_1(self):\n buf = DummyBuffer()\n inst = self._makeOne(0, buf)\n result = inst.received(\"a\")\n self.assertEqual(result, 0)\n self.assertEqual(inst.completed, True)", " def test_received_remain_lte_datalen(self):\n buf = DummyBuffer()\n inst = self._makeOne(1, buf)\n result = inst.received(\"aa\")\n self.assertEqual(result, 1)\n self.assertEqual(inst.completed, True)\n self.assertEqual(inst.completed, 1)\n self.assertEqual(inst.remain, 0)\n self.assertEqual(buf.data, [\"a\"])", " def test_received_remain_gt_datalen(self):\n buf = DummyBuffer()\n inst = self._makeOne(10, buf)\n result = inst.received(\"aa\")\n self.assertEqual(result, 2)\n self.assertEqual(inst.completed, False)\n self.assertEqual(inst.remain, 8)\n self.assertEqual(buf.data, [\"aa\"])", " def test_getfile(self):\n buf = DummyBuffer()\n inst = self._makeOne(10, buf)\n self.assertEqual(inst.getfile(), buf)", " def test_getbuf(self):\n buf = DummyBuffer()\n inst = self._makeOne(10, buf)\n self.assertEqual(inst.getbuf(), buf)", " def test___len__(self):\n buf = DummyBuffer([\"1\", \"2\"])\n inst = self._makeOne(10, buf)\n self.assertEqual(inst.__len__(), 2)", "\nclass TestChunkedReceiver(unittest.TestCase):\n def _makeOne(self, buf):\n from waitress.receiver import ChunkedReceiver", " return ChunkedReceiver(buf)", " def test_alreadycompleted(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)\n inst.completed = True\n result = inst.received(b\"a\")\n self.assertEqual(result, 0)\n self.assertEqual(inst.completed, True)", " def test_received_remain_gt_zero(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)\n inst.chunk_remainder = 100\n result = inst.received(b\"a\")\n self.assertEqual(inst.chunk_remainder, 99)\n self.assertEqual(result, 1)\n self.assertEqual(inst.completed, False)", " def test_received_control_line_notfinished(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)\n result = inst.received(b\"a\")\n self.assertEqual(inst.control_line, b\"a\")\n self.assertEqual(result, 1)\n self.assertEqual(inst.completed, False)", " def test_received_control_line_finished_garbage_in_input(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)", " result = inst.received(b\"garbage\\n\")\n self.assertEqual(result, 8)", " self.assertTrue(inst.error)", " def test_received_control_line_finished_all_chunks_not_received(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)", " result = inst.received(b\"a;discard\\n\")", " self.assertEqual(inst.control_line, b\"\")\n self.assertEqual(inst.chunk_remainder, 10)\n self.assertEqual(inst.all_chunks_received, False)", " self.assertEqual(result, 10)", " self.assertEqual(inst.completed, False)", " def test_received_control_line_finished_all_chunks_received(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)", " result = inst.received(b\"0;discard\\n\")", " self.assertEqual(inst.control_line, b\"\")\n self.assertEqual(inst.all_chunks_received, True)", " self.assertEqual(result, 10)", " self.assertEqual(inst.completed, False)", " def test_received_trailer_startswith_crlf(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)\n inst.all_chunks_received = True\n result = inst.received(b\"\\r\\n\")\n self.assertEqual(result, 2)\n self.assertEqual(inst.completed, True)", " def test_received_trailer_startswith_lf(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)\n inst.all_chunks_received = True\n result = inst.received(b\"\\n\")\n self.assertEqual(result, 1)", " self.assertEqual(inst.completed, True)", "\n def test_received_trailer_not_finished(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)\n inst.all_chunks_received = True\n result = inst.received(b\"a\")\n self.assertEqual(result, 1)\n self.assertEqual(inst.completed, False)", " def test_received_trailer_finished(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)\n inst.all_chunks_received = True\n result = inst.received(b\"abc\\r\\n\\r\\n\")\n self.assertEqual(inst.trailer, b\"abc\\r\\n\\r\\n\")\n self.assertEqual(result, 7)\n self.assertEqual(inst.completed, True)", " def test_getfile(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)\n self.assertEqual(inst.getfile(), buf)", " def test_getbuf(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)\n self.assertEqual(inst.getbuf(), buf)", " def test___len__(self):\n buf = DummyBuffer([\"1\", \"2\"])\n inst = self._makeOne(buf)\n self.assertEqual(inst.__len__(), 2)", "", "", "class DummyBuffer(object):\n def __init__(self, data=None):\n if data is None:\n data = []\n self.data = data", " def append(self, s):\n self.data.append(s)", " def getfile(self):\n return self", " def __len__(self):\n return len(self.data)" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "import unittest", "\nclass TestFixedStreamReceiver(unittest.TestCase):\n def _makeOne(self, cl, buf):\n from waitress.receiver import FixedStreamReceiver", " return FixedStreamReceiver(cl, buf)", " def test_received_remain_lt_1(self):\n buf = DummyBuffer()\n inst = self._makeOne(0, buf)\n result = inst.received(\"a\")\n self.assertEqual(result, 0)\n self.assertEqual(inst.completed, True)", " def test_received_remain_lte_datalen(self):\n buf = DummyBuffer()\n inst = self._makeOne(1, buf)\n result = inst.received(\"aa\")\n self.assertEqual(result, 1)\n self.assertEqual(inst.completed, True)\n self.assertEqual(inst.completed, 1)\n self.assertEqual(inst.remain, 0)\n self.assertEqual(buf.data, [\"a\"])", " def test_received_remain_gt_datalen(self):\n buf = DummyBuffer()\n inst = self._makeOne(10, buf)\n result = inst.received(\"aa\")\n self.assertEqual(result, 2)\n self.assertEqual(inst.completed, False)\n self.assertEqual(inst.remain, 8)\n self.assertEqual(buf.data, [\"aa\"])", " def test_getfile(self):\n buf = DummyBuffer()\n inst = self._makeOne(10, buf)\n self.assertEqual(inst.getfile(), buf)", " def test_getbuf(self):\n buf = DummyBuffer()\n inst = self._makeOne(10, buf)\n self.assertEqual(inst.getbuf(), buf)", " def test___len__(self):\n buf = DummyBuffer([\"1\", \"2\"])\n inst = self._makeOne(10, buf)\n self.assertEqual(inst.__len__(), 2)", "\nclass TestChunkedReceiver(unittest.TestCase):\n def _makeOne(self, buf):\n from waitress.receiver import ChunkedReceiver", " return ChunkedReceiver(buf)", " def test_alreadycompleted(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)\n inst.completed = True\n result = inst.received(b\"a\")\n self.assertEqual(result, 0)\n self.assertEqual(inst.completed, True)", " def test_received_remain_gt_zero(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)\n inst.chunk_remainder = 100\n result = inst.received(b\"a\")\n self.assertEqual(inst.chunk_remainder, 99)\n self.assertEqual(result, 1)\n self.assertEqual(inst.completed, False)", " def test_received_control_line_notfinished(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)\n result = inst.received(b\"a\")\n self.assertEqual(inst.control_line, b\"a\")\n self.assertEqual(result, 1)\n self.assertEqual(inst.completed, False)", " def test_received_control_line_finished_garbage_in_input(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)", " result = inst.received(b\"garbage\\r\\n\")\n self.assertEqual(result, 9)", " self.assertTrue(inst.error)", " def test_received_control_line_finished_all_chunks_not_received(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)", " result = inst.received(b\"a;discard\\r\\n\")", " self.assertEqual(inst.control_line, b\"\")\n self.assertEqual(inst.chunk_remainder, 10)\n self.assertEqual(inst.all_chunks_received, False)", " self.assertEqual(result, 11)", " self.assertEqual(inst.completed, False)", " def test_received_control_line_finished_all_chunks_received(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)", " result = inst.received(b\"0;discard\\r\\n\")", " self.assertEqual(inst.control_line, b\"\")\n self.assertEqual(inst.all_chunks_received, True)", " self.assertEqual(result, 11)", " self.assertEqual(inst.completed, False)", " def test_received_trailer_startswith_crlf(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)\n inst.all_chunks_received = True\n result = inst.received(b\"\\r\\n\")\n self.assertEqual(result, 2)\n self.assertEqual(inst.completed, True)", " def test_received_trailer_startswith_lf(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)\n inst.all_chunks_received = True\n result = inst.received(b\"\\n\")\n self.assertEqual(result, 1)", " self.assertEqual(inst.completed, False)", "\n def test_received_trailer_not_finished(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)\n inst.all_chunks_received = True\n result = inst.received(b\"a\")\n self.assertEqual(result, 1)\n self.assertEqual(inst.completed, False)", " def test_received_trailer_finished(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)\n inst.all_chunks_received = True\n result = inst.received(b\"abc\\r\\n\\r\\n\")\n self.assertEqual(inst.trailer, b\"abc\\r\\n\\r\\n\")\n self.assertEqual(result, 7)\n self.assertEqual(inst.completed, True)", " def test_getfile(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)\n self.assertEqual(inst.getfile(), buf)", " def test_getbuf(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)\n self.assertEqual(inst.getbuf(), buf)", " def test___len__(self):\n buf = DummyBuffer([\"1\", \"2\"])\n inst = self._makeOne(buf)\n self.assertEqual(inst.__len__(), 2)", "\n def test_received_chunk_is_properly_terminated(self):\n buf = DummyBuffer()\n inst = self._makeOne(buf)\n data = b\"4\\r\\nWiki\\r\\n\"\n result = inst.received(data)\n self.assertEqual(result, len(data))\n self.assertEqual(inst.completed, False)\n self.assertEqual(buf.data[0], b\"Wiki\")", " def test_received_chunk_not_properly_terminated(self):\n from waitress.utilities import BadRequest", " buf = DummyBuffer()\n inst = self._makeOne(buf)\n data = b\"4\\r\\nWikibadchunk\\r\\n\"\n result = inst.received(data)\n self.assertEqual(result, len(data))\n self.assertEqual(inst.completed, False)\n self.assertEqual(buf.data[0], b\"Wiki\")\n self.assertEqual(inst.error.__class__, BadRequest)", " def test_received_multiple_chunks(self):\n from waitress.utilities import BadRequest", " buf = DummyBuffer()\n inst = self._makeOne(buf)\n data = (\n b\"4\\r\\n\"\n b\"Wiki\\r\\n\"\n b\"5\\r\\n\"\n b\"pedia\\r\\n\"\n b\"E\\r\\n\"\n b\" in\\r\\n\"\n b\"\\r\\n\"\n b\"chunks.\\r\\n\"\n b\"0\\r\\n\"\n b\"\\r\\n\"\n )\n result = inst.received(data)\n self.assertEqual(result, len(data))\n self.assertEqual(inst.completed, True)\n self.assertEqual(b\"\".join(buf.data), b\"Wikipedia in\\r\\n\\r\\nchunks.\")\n self.assertEqual(inst.error, None)", " def test_received_multiple_chunks_split(self):\n from waitress.utilities import BadRequest", " buf = DummyBuffer()\n inst = self._makeOne(buf)\n data1 = b\"4\\r\\nWiki\\r\"\n result = inst.received(data1)\n self.assertEqual(result, len(data1))", " data2 = (\n b\"\\n5\\r\\n\"\n b\"pedia\\r\\n\"\n b\"E\\r\\n\"\n b\" in\\r\\n\"\n b\"\\r\\n\"\n b\"chunks.\\r\\n\"\n b\"0\\r\\n\"\n b\"\\r\\n\"\n )", " result = inst.received(data2)\n self.assertEqual(result, len(data2))", " self.assertEqual(inst.completed, True)\n self.assertEqual(b\"\".join(buf.data), b\"Wikipedia in\\r\\n\\r\\nchunks.\")\n self.assertEqual(inst.error, None)", "", "class DummyBuffer(object):\n def __init__(self, data=None):\n if data is None:\n data = []\n self.data = data", " def append(self, s):\n self.data.append(s)", " def getfile(self):\n return self", " def __len__(self):\n return len(self.data)" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "import unittest\nimport io", "\nclass TestThreadedTaskDispatcher(unittest.TestCase):\n def _makeOne(self):\n from waitress.task import ThreadedTaskDispatcher", " return ThreadedTaskDispatcher()", " def test_handler_thread_task_raises(self):\n inst = self._makeOne()\n inst.threads.add(0)\n inst.logger = DummyLogger()", " class BadDummyTask(DummyTask):\n def service(self):\n super(BadDummyTask, self).service()\n inst.stop_count += 1\n raise Exception", " task = BadDummyTask()\n inst.logger = DummyLogger()\n inst.queue.append(task)\n inst.active_count += 1\n inst.handler_thread(0)\n self.assertEqual(inst.stop_count, 0)\n self.assertEqual(inst.active_count, 0)\n self.assertEqual(inst.threads, set())\n self.assertEqual(len(inst.logger.logged), 1)", " def test_set_thread_count_increase(self):\n inst = self._makeOne()\n L = []\n inst.start_new_thread = lambda *x: L.append(x)\n inst.set_thread_count(1)\n self.assertEqual(L, [(inst.handler_thread, (0,))])", " def test_set_thread_count_increase_with_existing(self):\n inst = self._makeOne()\n L = []\n inst.threads = {0}\n inst.start_new_thread = lambda *x: L.append(x)\n inst.set_thread_count(2)\n self.assertEqual(L, [(inst.handler_thread, (1,))])", " def test_set_thread_count_decrease(self):\n inst = self._makeOne()\n inst.threads = {0, 1}\n inst.set_thread_count(1)\n self.assertEqual(inst.stop_count, 1)", " def test_set_thread_count_same(self):\n inst = self._makeOne()\n L = []\n inst.start_new_thread = lambda *x: L.append(x)\n inst.threads = {0}\n inst.set_thread_count(1)\n self.assertEqual(L, [])", " def test_add_task_with_idle_threads(self):\n task = DummyTask()\n inst = self._makeOne()\n inst.threads.add(0)\n inst.queue_logger = DummyLogger()\n inst.add_task(task)\n self.assertEqual(len(inst.queue), 1)\n self.assertEqual(len(inst.queue_logger.logged), 0)", " def test_add_task_with_all_busy_threads(self):\n task = DummyTask()\n inst = self._makeOne()\n inst.queue_logger = DummyLogger()\n inst.add_task(task)\n self.assertEqual(len(inst.queue_logger.logged), 1)\n inst.add_task(task)\n self.assertEqual(len(inst.queue_logger.logged), 2)", " def test_shutdown_one_thread(self):\n inst = self._makeOne()\n inst.threads.add(0)\n inst.logger = DummyLogger()\n task = DummyTask()\n inst.queue.append(task)\n self.assertEqual(inst.shutdown(timeout=0.01), True)\n self.assertEqual(\n inst.logger.logged,\n [\"1 thread(s) still running\", \"Canceling 1 pending task(s)\",],\n )\n self.assertEqual(task.cancelled, True)", " def test_shutdown_no_threads(self):\n inst = self._makeOne()\n self.assertEqual(inst.shutdown(timeout=0.01), True)", " def test_shutdown_no_cancel_pending(self):\n inst = self._makeOne()\n self.assertEqual(inst.shutdown(cancel_pending=False, timeout=0.01), False)", "\nclass TestTask(unittest.TestCase):\n def _makeOne(self, channel=None, request=None):\n if channel is None:\n channel = DummyChannel()\n if request is None:\n request = DummyParser()\n from waitress.task import Task", " return Task(channel, request)", " def test_ctor_version_not_in_known(self):\n request = DummyParser()\n request.version = \"8.4\"\n inst = self._makeOne(request=request)\n self.assertEqual(inst.version, \"1.0\")", " def test_build_response_header_bad_http_version(self):\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.version = \"8.4\"\n self.assertRaises(AssertionError, inst.build_response_header)", " def test_build_response_header_v10_keepalive_no_content_length(self):\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.request.headers[\"CONNECTION\"] = \"keep-alive\"\n inst.version = \"1.0\"\n result = inst.build_response_header()\n lines = filter_lines(result)\n self.assertEqual(len(lines), 4)\n self.assertEqual(lines[0], b\"HTTP/1.0 200 OK\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertTrue(lines[2].startswith(b\"Date:\"))\n self.assertEqual(lines[3], b\"Server: waitress\")\n self.assertEqual(inst.close_on_finish, True)\n self.assertTrue((\"Connection\", \"close\") in inst.response_headers)", " def test_build_response_header_v10_keepalive_with_content_length(self):\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.request.headers[\"CONNECTION\"] = \"keep-alive\"\n inst.response_headers = [(\"Content-Length\", \"10\")]\n inst.version = \"1.0\"\n inst.content_length = 0\n result = inst.build_response_header()\n lines = filter_lines(result)\n self.assertEqual(len(lines), 5)\n self.assertEqual(lines[0], b\"HTTP/1.0 200 OK\")\n self.assertEqual(lines[1], b\"Connection: Keep-Alive\")\n self.assertEqual(lines[2], b\"Content-Length: 10\")\n self.assertTrue(lines[3].startswith(b\"Date:\"))\n self.assertEqual(lines[4], b\"Server: waitress\")\n self.assertEqual(inst.close_on_finish, False)", " def test_build_response_header_v11_connection_closed_by_client(self):\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.version = \"1.1\"\n inst.request.headers[\"CONNECTION\"] = \"close\"\n result = inst.build_response_header()\n lines = filter_lines(result)\n self.assertEqual(len(lines), 5)\n self.assertEqual(lines[0], b\"HTTP/1.1 200 OK\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertTrue(lines[2].startswith(b\"Date:\"))\n self.assertEqual(lines[3], b\"Server: waitress\")\n self.assertEqual(lines[4], b\"Transfer-Encoding: chunked\")\n self.assertTrue((\"Connection\", \"close\") in inst.response_headers)\n self.assertEqual(inst.close_on_finish, True)", " def test_build_response_header_v11_connection_keepalive_by_client(self):\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.request.headers[\"CONNECTION\"] = \"keep-alive\"\n inst.version = \"1.1\"\n result = inst.build_response_header()\n lines = filter_lines(result)\n self.assertEqual(len(lines), 5)\n self.assertEqual(lines[0], b\"HTTP/1.1 200 OK\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertTrue(lines[2].startswith(b\"Date:\"))\n self.assertEqual(lines[3], b\"Server: waitress\")\n self.assertEqual(lines[4], b\"Transfer-Encoding: chunked\")\n self.assertTrue((\"Connection\", \"close\") in inst.response_headers)\n self.assertEqual(inst.close_on_finish, True)", " def test_build_response_header_v11_200_no_content_length(self):\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.version = \"1.1\"\n result = inst.build_response_header()\n lines = filter_lines(result)\n self.assertEqual(len(lines), 5)\n self.assertEqual(lines[0], b\"HTTP/1.1 200 OK\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertTrue(lines[2].startswith(b\"Date:\"))\n self.assertEqual(lines[3], b\"Server: waitress\")\n self.assertEqual(lines[4], b\"Transfer-Encoding: chunked\")\n self.assertEqual(inst.close_on_finish, True)\n self.assertTrue((\"Connection\", \"close\") in inst.response_headers)", " def test_build_response_header_v11_204_no_content_length_or_transfer_encoding(self):\n # RFC 7230: MUST NOT send Transfer-Encoding or Content-Length\n # for any response with a status code of 1xx or 204.\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.version = \"1.1\"\n inst.status = \"204 No Content\"\n result = inst.build_response_header()\n lines = filter_lines(result)\n self.assertEqual(len(lines), 4)\n self.assertEqual(lines[0], b\"HTTP/1.1 204 No Content\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertTrue(lines[2].startswith(b\"Date:\"))\n self.assertEqual(lines[3], b\"Server: waitress\")\n self.assertEqual(inst.close_on_finish, True)\n self.assertTrue((\"Connection\", \"close\") in inst.response_headers)", " def test_build_response_header_v11_1xx_no_content_length_or_transfer_encoding(self):\n # RFC 7230: MUST NOT send Transfer-Encoding or Content-Length\n # for any response with a status code of 1xx or 204.\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.version = \"1.1\"\n inst.status = \"100 Continue\"\n result = inst.build_response_header()\n lines = filter_lines(result)\n self.assertEqual(len(lines), 4)\n self.assertEqual(lines[0], b\"HTTP/1.1 100 Continue\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertTrue(lines[2].startswith(b\"Date:\"))\n self.assertEqual(lines[3], b\"Server: waitress\")\n self.assertEqual(inst.close_on_finish, True)\n self.assertTrue((\"Connection\", \"close\") in inst.response_headers)", " def test_build_response_header_v11_304_no_content_length_or_transfer_encoding(self):\n # RFC 7230: MUST NOT send Transfer-Encoding or Content-Length\n # for any response with a status code of 1xx, 204 or 304.\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.version = \"1.1\"\n inst.status = \"304 Not Modified\"\n result = inst.build_response_header()\n lines = filter_lines(result)\n self.assertEqual(len(lines), 4)\n self.assertEqual(lines[0], b\"HTTP/1.1 304 Not Modified\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertTrue(lines[2].startswith(b\"Date:\"))\n self.assertEqual(lines[3], b\"Server: waitress\")\n self.assertEqual(inst.close_on_finish, True)\n self.assertTrue((\"Connection\", \"close\") in inst.response_headers)", " def test_build_response_header_via_added(self):\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.version = \"1.0\"\n inst.response_headers = [(\"Server\", \"abc\")]\n result = inst.build_response_header()\n lines = filter_lines(result)\n self.assertEqual(len(lines), 5)\n self.assertEqual(lines[0], b\"HTTP/1.0 200 OK\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertTrue(lines[2].startswith(b\"Date:\"))\n self.assertEqual(lines[3], b\"Server: abc\")\n self.assertEqual(lines[4], b\"Via: waitress\")", " def test_build_response_header_date_exists(self):\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.version = \"1.0\"\n inst.response_headers = [(\"Date\", \"date\")]\n result = inst.build_response_header()\n lines = filter_lines(result)\n self.assertEqual(len(lines), 4)\n self.assertEqual(lines[0], b\"HTTP/1.0 200 OK\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertTrue(lines[2].startswith(b\"Date:\"))\n self.assertEqual(lines[3], b\"Server: waitress\")", " def test_build_response_header_preexisting_content_length(self):\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.version = \"1.1\"\n inst.content_length = 100\n result = inst.build_response_header()\n lines = filter_lines(result)\n self.assertEqual(len(lines), 4)\n self.assertEqual(lines[0], b\"HTTP/1.1 200 OK\")\n self.assertEqual(lines[1], b\"Content-Length: 100\")\n self.assertTrue(lines[2].startswith(b\"Date:\"))\n self.assertEqual(lines[3], b\"Server: waitress\")", " def test_remove_content_length_header(self):\n inst = self._makeOne()\n inst.response_headers = [(\"Content-Length\", \"70\")]\n inst.remove_content_length_header()\n self.assertEqual(inst.response_headers, [])", " def test_remove_content_length_header_with_other(self):\n inst = self._makeOne()\n inst.response_headers = [\n (\"Content-Length\", \"70\"),\n (\"Content-Type\", \"text/html\"),\n ]\n inst.remove_content_length_header()\n self.assertEqual(inst.response_headers, [(\"Content-Type\", \"text/html\")])", " def test_start(self):\n inst = self._makeOne()\n inst.start()\n self.assertTrue(inst.start_time)", " def test_finish_didnt_write_header(self):\n inst = self._makeOne()\n inst.wrote_header = False\n inst.complete = True\n inst.finish()\n self.assertTrue(inst.channel.written)", " def test_finish_wrote_header(self):\n inst = self._makeOne()\n inst.wrote_header = True\n inst.finish()\n self.assertFalse(inst.channel.written)", " def test_finish_chunked_response(self):\n inst = self._makeOne()\n inst.wrote_header = True\n inst.chunked_response = True\n inst.finish()\n self.assertEqual(inst.channel.written, b\"0\\r\\n\\r\\n\")", " def test_write_wrote_header(self):\n inst = self._makeOne()\n inst.wrote_header = True\n inst.complete = True\n inst.content_length = 3\n inst.write(b\"abc\")\n self.assertEqual(inst.channel.written, b\"abc\")", " def test_write_header_not_written(self):\n inst = self._makeOne()\n inst.wrote_header = False\n inst.complete = True\n inst.write(b\"abc\")\n self.assertTrue(inst.channel.written)\n self.assertEqual(inst.wrote_header, True)", " def test_write_start_response_uncalled(self):\n inst = self._makeOne()\n self.assertRaises(RuntimeError, inst.write, b\"\")", " def test_write_chunked_response(self):\n inst = self._makeOne()\n inst.wrote_header = True\n inst.chunked_response = True\n inst.complete = True\n inst.write(b\"abc\")\n self.assertEqual(inst.channel.written, b\"3\\r\\nabc\\r\\n\")", " def test_write_preexisting_content_length(self):\n inst = self._makeOne()\n inst.wrote_header = True\n inst.complete = True\n inst.content_length = 1\n inst.logger = DummyLogger()\n inst.write(b\"abc\")\n self.assertTrue(inst.channel.written)\n self.assertEqual(inst.logged_write_excess, True)\n self.assertEqual(len(inst.logger.logged), 1)", "\nclass TestWSGITask(unittest.TestCase):\n def _makeOne(self, channel=None, request=None):\n if channel is None:\n channel = DummyChannel()\n if request is None:\n request = DummyParser()\n from waitress.task import WSGITask", " return WSGITask(channel, request)", " def test_service(self):\n inst = self._makeOne()", " def execute():\n inst.executed = True", " inst.execute = execute\n inst.complete = True\n inst.service()\n self.assertTrue(inst.start_time)\n self.assertTrue(inst.close_on_finish)\n self.assertTrue(inst.channel.written)\n self.assertEqual(inst.executed, True)", " def test_service_server_raises_socket_error(self):\n import socket", " inst = self._makeOne()", " def execute():\n raise socket.error", " inst.execute = execute\n self.assertRaises(socket.error, inst.service)\n self.assertTrue(inst.start_time)\n self.assertTrue(inst.close_on_finish)\n self.assertFalse(inst.channel.written)", " def test_execute_app_calls_start_response_twice_wo_exc_info(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [])\n start_response(\"200 OK\", [])", " inst = self._makeOne()\n inst.channel.server.application = app\n self.assertRaises(AssertionError, inst.execute)", " def test_execute_app_calls_start_response_w_exc_info_complete(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [], [ValueError, ValueError(), None])\n return [b\"a\"]", " inst = self._makeOne()\n inst.complete = True\n inst.channel.server.application = app\n inst.execute()\n self.assertTrue(inst.complete)\n self.assertEqual(inst.status, \"200 OK\")\n self.assertTrue(inst.channel.written)", " def test_execute_app_calls_start_response_w_excinf_headers_unwritten(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [], [ValueError, None, None])\n return [b\"a\"]", " inst = self._makeOne()\n inst.wrote_header = False\n inst.channel.server.application = app\n inst.response_headers = [(\"a\", \"b\")]\n inst.execute()\n self.assertTrue(inst.complete)\n self.assertEqual(inst.status, \"200 OK\")\n self.assertTrue(inst.channel.written)\n self.assertFalse((\"a\", \"b\") in inst.response_headers)", " def test_execute_app_calls_start_response_w_excinf_headers_written(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [], [ValueError, ValueError(), None])", " inst = self._makeOne()\n inst.complete = True\n inst.wrote_header = True\n inst.channel.server.application = app\n self.assertRaises(ValueError, inst.execute)", " def test_execute_bad_header_key(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [(None, \"a\")])", " inst = self._makeOne()\n inst.channel.server.application = app\n self.assertRaises(AssertionError, inst.execute)", " def test_execute_bad_header_value(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [(\"a\", None)])", " inst = self._makeOne()\n inst.channel.server.application = app\n self.assertRaises(AssertionError, inst.execute)", " def test_execute_hopbyhop_header(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [(\"Connection\", \"close\")])", " inst = self._makeOne()\n inst.channel.server.application = app\n self.assertRaises(AssertionError, inst.execute)", " def test_execute_bad_header_value_control_characters(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [(\"a\", \"\\n\")])", " inst = self._makeOne()\n inst.channel.server.application = app\n self.assertRaises(ValueError, inst.execute)", " def test_execute_bad_header_name_control_characters(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [(\"a\\r\", \"value\")])", " inst = self._makeOne()\n inst.channel.server.application = app\n self.assertRaises(ValueError, inst.execute)", " def test_execute_bad_status_control_characters(self):\n def app(environ, start_response):\n start_response(\"200 OK\\r\", [])", " inst = self._makeOne()\n inst.channel.server.application = app\n self.assertRaises(ValueError, inst.execute)", " def test_preserve_header_value_order(self):\n def app(environ, start_response):\n write = start_response(\"200 OK\", [(\"C\", \"b\"), (\"A\", \"b\"), (\"A\", \"a\")])\n write(b\"abc\")\n return []", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.execute()\n self.assertTrue(b\"A: b\\r\\nA: a\\r\\nC: b\\r\\n\" in inst.channel.written)", " def test_execute_bad_status_value(self):\n def app(environ, start_response):\n start_response(None, [])", " inst = self._makeOne()\n inst.channel.server.application = app\n self.assertRaises(AssertionError, inst.execute)", " def test_execute_with_content_length_header(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [(\"Content-Length\", \"1\")])\n return [b\"a\"]", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.execute()\n self.assertEqual(inst.content_length, 1)", " def test_execute_app_calls_write(self):\n def app(environ, start_response):\n write = start_response(\"200 OK\", [(\"Content-Length\", \"3\")])\n write(b\"abc\")\n return []", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.execute()\n self.assertEqual(inst.channel.written[-3:], b\"abc\")", " def test_execute_app_returns_len1_chunk_without_cl(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [])\n return [b\"abc\"]", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.execute()\n self.assertEqual(inst.content_length, 3)", " def test_execute_app_returns_empty_chunk_as_first(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [])\n return [\"\", b\"abc\"]", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.execute()\n self.assertEqual(inst.content_length, None)", " def test_execute_app_returns_too_many_bytes(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [(\"Content-Length\", \"1\")])\n return [b\"abc\"]", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.logger = DummyLogger()\n inst.execute()\n self.assertEqual(inst.close_on_finish, True)\n self.assertEqual(len(inst.logger.logged), 1)", " def test_execute_app_returns_too_few_bytes(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [(\"Content-Length\", \"3\")])\n return [b\"a\"]", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.logger = DummyLogger()\n inst.execute()\n self.assertEqual(inst.close_on_finish, True)\n self.assertEqual(len(inst.logger.logged), 1)", " def test_execute_app_do_not_warn_on_head(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [(\"Content-Length\", \"3\")])\n return [b\"\"]", " inst = self._makeOne()\n inst.request.command = \"HEAD\"\n inst.channel.server.application = app\n inst.logger = DummyLogger()\n inst.execute()\n self.assertEqual(inst.close_on_finish, True)\n self.assertEqual(len(inst.logger.logged), 0)", " def test_execute_app_without_body_204_logged(self):\n def app(environ, start_response):\n start_response(\"204 No Content\", [(\"Content-Length\", \"3\")])\n return [b\"abc\"]", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.logger = DummyLogger()\n inst.execute()\n self.assertEqual(inst.close_on_finish, True)\n self.assertNotIn(b\"abc\", inst.channel.written)\n self.assertNotIn(b\"Content-Length\", inst.channel.written)\n self.assertNotIn(b\"Transfer-Encoding\", inst.channel.written)\n self.assertEqual(len(inst.logger.logged), 1)", " def test_execute_app_without_body_304_logged(self):\n def app(environ, start_response):\n start_response(\"304 Not Modified\", [(\"Content-Length\", \"3\")])\n return [b\"abc\"]", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.logger = DummyLogger()\n inst.execute()\n self.assertEqual(inst.close_on_finish, True)\n self.assertNotIn(b\"abc\", inst.channel.written)\n self.assertNotIn(b\"Content-Length\", inst.channel.written)\n self.assertNotIn(b\"Transfer-Encoding\", inst.channel.written)\n self.assertEqual(len(inst.logger.logged), 1)", " def test_execute_app_returns_closeable(self):\n class closeable(list):\n def close(self):\n self.closed = True", " foo = closeable([b\"abc\"])", " def app(environ, start_response):\n start_response(\"200 OK\", [(\"Content-Length\", \"3\")])\n return foo", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.execute()\n self.assertEqual(foo.closed, True)", " def test_execute_app_returns_filewrapper_prepare_returns_True(self):\n from waitress.buffers import ReadOnlyFileBasedBuffer", " f = io.BytesIO(b\"abc\")\n app_iter = ReadOnlyFileBasedBuffer(f, 8192)", " def app(environ, start_response):\n start_response(\"200 OK\", [(\"Content-Length\", \"3\")])\n return app_iter", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.execute()\n self.assertTrue(inst.channel.written) # header\n self.assertEqual(inst.channel.otherdata, [app_iter])", " def test_execute_app_returns_filewrapper_prepare_returns_True_nocl(self):\n from waitress.buffers import ReadOnlyFileBasedBuffer", " f = io.BytesIO(b\"abc\")\n app_iter = ReadOnlyFileBasedBuffer(f, 8192)", " def app(environ, start_response):\n start_response(\"200 OK\", [])\n return app_iter", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.execute()\n self.assertTrue(inst.channel.written) # header\n self.assertEqual(inst.channel.otherdata, [app_iter])\n self.assertEqual(inst.content_length, 3)", " def test_execute_app_returns_filewrapper_prepare_returns_True_badcl(self):\n from waitress.buffers import ReadOnlyFileBasedBuffer", " f = io.BytesIO(b\"abc\")\n app_iter = ReadOnlyFileBasedBuffer(f, 8192)", " def app(environ, start_response):\n start_response(\"200 OK\", [])\n return app_iter", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.content_length = 10\n inst.response_headers = [(\"Content-Length\", \"10\")]\n inst.execute()\n self.assertTrue(inst.channel.written) # header\n self.assertEqual(inst.channel.otherdata, [app_iter])\n self.assertEqual(inst.content_length, 3)\n self.assertEqual(dict(inst.response_headers)[\"Content-Length\"], \"3\")", " def test_get_environment_already_cached(self):\n inst = self._makeOne()\n inst.environ = object()\n self.assertEqual(inst.get_environment(), inst.environ)", " def test_get_environment_path_startswith_more_than_one_slash(self):\n inst = self._makeOne()\n request = DummyParser()\n request.path = \"///abc\"\n inst.request = request\n environ = inst.get_environment()\n self.assertEqual(environ[\"PATH_INFO\"], \"/abc\")", " def test_get_environment_path_empty(self):\n inst = self._makeOne()\n request = DummyParser()\n request.path = \"\"\n inst.request = request\n environ = inst.get_environment()\n self.assertEqual(environ[\"PATH_INFO\"], \"\")", " def test_get_environment_no_query(self):\n inst = self._makeOne()\n request = DummyParser()\n inst.request = request\n environ = inst.get_environment()\n self.assertEqual(environ[\"QUERY_STRING\"], \"\")", " def test_get_environment_with_query(self):\n inst = self._makeOne()\n request = DummyParser()\n request.query = \"abc\"\n inst.request = request\n environ = inst.get_environment()\n self.assertEqual(environ[\"QUERY_STRING\"], \"abc\")", " def test_get_environ_with_url_prefix_miss(self):\n inst = self._makeOne()\n inst.channel.server.adj.url_prefix = \"/foo\"\n request = DummyParser()\n request.path = \"/bar\"\n inst.request = request\n environ = inst.get_environment()\n self.assertEqual(environ[\"PATH_INFO\"], \"/bar\")\n self.assertEqual(environ[\"SCRIPT_NAME\"], \"/foo\")", " def test_get_environ_with_url_prefix_hit(self):\n inst = self._makeOne()\n inst.channel.server.adj.url_prefix = \"/foo\"\n request = DummyParser()\n request.path = \"/foo/fuz\"\n inst.request = request\n environ = inst.get_environment()\n self.assertEqual(environ[\"PATH_INFO\"], \"/fuz\")\n self.assertEqual(environ[\"SCRIPT_NAME\"], \"/foo\")", " def test_get_environ_with_url_prefix_empty_path(self):\n inst = self._makeOne()\n inst.channel.server.adj.url_prefix = \"/foo\"\n request = DummyParser()\n request.path = \"/foo\"\n inst.request = request\n environ = inst.get_environment()\n self.assertEqual(environ[\"PATH_INFO\"], \"\")\n self.assertEqual(environ[\"SCRIPT_NAME\"], \"/foo\")", " def test_get_environment_values(self):\n import sys", " inst = self._makeOne()\n request = DummyParser()\n request.headers = {\n \"CONTENT_TYPE\": \"abc\",\n \"CONTENT_LENGTH\": \"10\",\n \"X_FOO\": \"BAR\",\n \"CONNECTION\": \"close\",\n }\n request.query = \"abc\"\n inst.request = request\n environ = inst.get_environment()", " # nail the keys of environ\n self.assertEqual(\n sorted(environ.keys()),\n [\n \"CONTENT_LENGTH\",\n \"CONTENT_TYPE\",\n \"HTTP_CONNECTION\",\n \"HTTP_X_FOO\",\n \"PATH_INFO\",\n \"QUERY_STRING\",\n \"REMOTE_ADDR\",\n \"REMOTE_HOST\",\n \"REMOTE_PORT\",\n \"REQUEST_METHOD\",\n \"SCRIPT_NAME\",\n \"SERVER_NAME\",\n \"SERVER_PORT\",\n \"SERVER_PROTOCOL\",\n \"SERVER_SOFTWARE\",\n \"wsgi.errors\",\n \"wsgi.file_wrapper\",\n \"wsgi.input\",\n \"wsgi.input_terminated\",\n \"wsgi.multiprocess\",\n \"wsgi.multithread\",\n \"wsgi.run_once\",\n \"wsgi.url_scheme\",\n \"wsgi.version\",\n ],\n )", " self.assertEqual(environ[\"REQUEST_METHOD\"], \"GET\")\n self.assertEqual(environ[\"SERVER_PORT\"], \"80\")\n self.assertEqual(environ[\"SERVER_NAME\"], \"localhost\")\n self.assertEqual(environ[\"SERVER_SOFTWARE\"], \"waitress\")\n self.assertEqual(environ[\"SERVER_PROTOCOL\"], \"HTTP/1.0\")\n self.assertEqual(environ[\"SCRIPT_NAME\"], \"\")\n self.assertEqual(environ[\"HTTP_CONNECTION\"], \"close\")\n self.assertEqual(environ[\"PATH_INFO\"], \"/\")\n self.assertEqual(environ[\"QUERY_STRING\"], \"abc\")\n self.assertEqual(environ[\"REMOTE_ADDR\"], \"127.0.0.1\")\n self.assertEqual(environ[\"REMOTE_HOST\"], \"127.0.0.1\")\n self.assertEqual(environ[\"REMOTE_PORT\"], \"39830\")\n self.assertEqual(environ[\"CONTENT_TYPE\"], \"abc\")\n self.assertEqual(environ[\"CONTENT_LENGTH\"], \"10\")\n self.assertEqual(environ[\"HTTP_X_FOO\"], \"BAR\")\n self.assertEqual(environ[\"wsgi.version\"], (1, 0))\n self.assertEqual(environ[\"wsgi.url_scheme\"], \"http\")\n self.assertEqual(environ[\"wsgi.errors\"], sys.stderr)\n self.assertEqual(environ[\"wsgi.multithread\"], True)\n self.assertEqual(environ[\"wsgi.multiprocess\"], False)\n self.assertEqual(environ[\"wsgi.run_once\"], False)\n self.assertEqual(environ[\"wsgi.input\"], \"stream\")\n self.assertEqual(environ[\"wsgi.input_terminated\"], True)\n self.assertEqual(inst.environ, environ)", "\nclass TestErrorTask(unittest.TestCase):\n def _makeOne(self, channel=None, request=None):\n if channel is None:\n channel = DummyChannel()\n if request is None:\n request = DummyParser()\n request.error = self._makeDummyError()\n from waitress.task import ErrorTask", " return ErrorTask(channel, request)", " def _makeDummyError(self):\n from waitress.utilities import Error", " e = Error(\"body\")\n e.code = 432\n e.reason = \"Too Ugly\"\n return e", " def test_execute_http_10(self):\n inst = self._makeOne()\n inst.execute()\n lines = filter_lines(inst.channel.written)\n self.assertEqual(len(lines), 9)\n self.assertEqual(lines[0], b\"HTTP/1.0 432 Too Ugly\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertEqual(lines[2], b\"Content-Length: 43\")\n self.assertEqual(lines[3], b\"Content-Type: text/plain\")\n self.assertTrue(lines[4])\n self.assertEqual(lines[5], b\"Server: waitress\")\n self.assertEqual(lines[6], b\"Too Ugly\")\n self.assertEqual(lines[7], b\"body\")\n self.assertEqual(lines[8], b\"(generated by waitress)\")", " def test_execute_http_11(self):\n inst = self._makeOne()\n inst.version = \"1.1\"\n inst.execute()\n lines = filter_lines(inst.channel.written)", " self.assertEqual(len(lines), 8)\n self.assertEqual(lines[0], b\"HTTP/1.1 432 Too Ugly\")\n self.assertEqual(lines[1], b\"Content-Length: 43\")\n self.assertEqual(lines[2], b\"Content-Type: text/plain\")\n self.assertTrue(lines[3])\n self.assertEqual(lines[4], b\"Server: waitress\")\n self.assertEqual(lines[5], b\"Too Ugly\")\n self.assertEqual(lines[6], b\"body\")\n self.assertEqual(lines[7], b\"(generated by waitress)\")", " def test_execute_http_11_close(self):\n inst = self._makeOne()\n inst.version = \"1.1\"\n inst.request.headers[\"CONNECTION\"] = \"close\"\n inst.execute()\n lines = filter_lines(inst.channel.written)", " self.assertEqual(len(lines), 9)\n self.assertEqual(lines[0], b\"HTTP/1.1 432 Too Ugly\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertEqual(lines[2], b\"Content-Length: 43\")\n self.assertEqual(lines[3], b\"Content-Type: text/plain\")\n self.assertTrue(lines[4])\n self.assertEqual(lines[5], b\"Server: waitress\")\n self.assertEqual(lines[6], b\"Too Ugly\")\n self.assertEqual(lines[7], b\"body\")\n self.assertEqual(lines[8], b\"(generated by waitress)\")\n", " def test_execute_http_11_keep(self):", " inst = self._makeOne()\n inst.version = \"1.1\"\n inst.request.headers[\"CONNECTION\"] = \"keep-alive\"\n inst.execute()\n lines = filter_lines(inst.channel.written)", " self.assertEqual(len(lines), 8)", " self.assertEqual(lines[0], b\"HTTP/1.1 432 Too Ugly\")", " self.assertEqual(lines[1], b\"Content-Length: 43\")\n self.assertEqual(lines[2], b\"Content-Type: text/plain\")\n self.assertTrue(lines[3])\n self.assertEqual(lines[4], b\"Server: waitress\")\n self.assertEqual(lines[5], b\"Too Ugly\")\n self.assertEqual(lines[6], b\"body\")\n self.assertEqual(lines[7], b\"(generated by waitress)\")", "", "class DummyTask(object):\n serviced = False\n cancelled = False", " def service(self):\n self.serviced = True", " def cancel(self):\n self.cancelled = True", "\nclass DummyAdj(object):\n log_socket_errors = True\n ident = \"waitress\"\n host = \"127.0.0.1\"\n port = 80\n url_prefix = \"\"", "\nclass DummyServer(object):\n server_name = \"localhost\"\n effective_port = 80", " def __init__(self):\n self.adj = DummyAdj()", "\nclass DummyChannel(object):\n closed_when_done = False\n adj = DummyAdj()\n creation_time = 0\n addr = (\"127.0.0.1\", 39830)", " def __init__(self, server=None):\n if server is None:\n server = DummyServer()\n self.server = server\n self.written = b\"\"\n self.otherdata = []", " def write_soon(self, data):\n if isinstance(data, bytes):\n self.written += data\n else:\n self.otherdata.append(data)\n return len(data)", "\nclass DummyParser(object):\n version = \"1.0\"\n command = \"GET\"\n path = \"/\"\n query = \"\"\n url_scheme = \"http\"\n expect_continue = False\n headers_finished = False", " def __init__(self):\n self.headers = {}", " def get_body_stream(self):\n return \"stream\"", "\ndef filter_lines(s):\n return list(filter(None, s.split(b\"\\r\\n\")))", "\nclass DummyLogger(object):\n def __init__(self):\n self.logged = []", " def warning(self, msg, *args):\n self.logged.append(msg % args)", " def exception(self, msg, *args):\n self.logged.append(msg % args)" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "import unittest\nimport io", "\nclass TestThreadedTaskDispatcher(unittest.TestCase):\n def _makeOne(self):\n from waitress.task import ThreadedTaskDispatcher", " return ThreadedTaskDispatcher()", " def test_handler_thread_task_raises(self):\n inst = self._makeOne()\n inst.threads.add(0)\n inst.logger = DummyLogger()", " class BadDummyTask(DummyTask):\n def service(self):\n super(BadDummyTask, self).service()\n inst.stop_count += 1\n raise Exception", " task = BadDummyTask()\n inst.logger = DummyLogger()\n inst.queue.append(task)\n inst.active_count += 1\n inst.handler_thread(0)\n self.assertEqual(inst.stop_count, 0)\n self.assertEqual(inst.active_count, 0)\n self.assertEqual(inst.threads, set())\n self.assertEqual(len(inst.logger.logged), 1)", " def test_set_thread_count_increase(self):\n inst = self._makeOne()\n L = []\n inst.start_new_thread = lambda *x: L.append(x)\n inst.set_thread_count(1)\n self.assertEqual(L, [(inst.handler_thread, (0,))])", " def test_set_thread_count_increase_with_existing(self):\n inst = self._makeOne()\n L = []\n inst.threads = {0}\n inst.start_new_thread = lambda *x: L.append(x)\n inst.set_thread_count(2)\n self.assertEqual(L, [(inst.handler_thread, (1,))])", " def test_set_thread_count_decrease(self):\n inst = self._makeOne()\n inst.threads = {0, 1}\n inst.set_thread_count(1)\n self.assertEqual(inst.stop_count, 1)", " def test_set_thread_count_same(self):\n inst = self._makeOne()\n L = []\n inst.start_new_thread = lambda *x: L.append(x)\n inst.threads = {0}\n inst.set_thread_count(1)\n self.assertEqual(L, [])", " def test_add_task_with_idle_threads(self):\n task = DummyTask()\n inst = self._makeOne()\n inst.threads.add(0)\n inst.queue_logger = DummyLogger()\n inst.add_task(task)\n self.assertEqual(len(inst.queue), 1)\n self.assertEqual(len(inst.queue_logger.logged), 0)", " def test_add_task_with_all_busy_threads(self):\n task = DummyTask()\n inst = self._makeOne()\n inst.queue_logger = DummyLogger()\n inst.add_task(task)\n self.assertEqual(len(inst.queue_logger.logged), 1)\n inst.add_task(task)\n self.assertEqual(len(inst.queue_logger.logged), 2)", " def test_shutdown_one_thread(self):\n inst = self._makeOne()\n inst.threads.add(0)\n inst.logger = DummyLogger()\n task = DummyTask()\n inst.queue.append(task)\n self.assertEqual(inst.shutdown(timeout=0.01), True)\n self.assertEqual(\n inst.logger.logged,\n [\"1 thread(s) still running\", \"Canceling 1 pending task(s)\",],\n )\n self.assertEqual(task.cancelled, True)", " def test_shutdown_no_threads(self):\n inst = self._makeOne()\n self.assertEqual(inst.shutdown(timeout=0.01), True)", " def test_shutdown_no_cancel_pending(self):\n inst = self._makeOne()\n self.assertEqual(inst.shutdown(cancel_pending=False, timeout=0.01), False)", "\nclass TestTask(unittest.TestCase):\n def _makeOne(self, channel=None, request=None):\n if channel is None:\n channel = DummyChannel()\n if request is None:\n request = DummyParser()\n from waitress.task import Task", " return Task(channel, request)", " def test_ctor_version_not_in_known(self):\n request = DummyParser()\n request.version = \"8.4\"\n inst = self._makeOne(request=request)\n self.assertEqual(inst.version, \"1.0\")", " def test_build_response_header_bad_http_version(self):\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.version = \"8.4\"\n self.assertRaises(AssertionError, inst.build_response_header)", " def test_build_response_header_v10_keepalive_no_content_length(self):\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.request.headers[\"CONNECTION\"] = \"keep-alive\"\n inst.version = \"1.0\"\n result = inst.build_response_header()\n lines = filter_lines(result)\n self.assertEqual(len(lines), 4)\n self.assertEqual(lines[0], b\"HTTP/1.0 200 OK\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertTrue(lines[2].startswith(b\"Date:\"))\n self.assertEqual(lines[3], b\"Server: waitress\")\n self.assertEqual(inst.close_on_finish, True)\n self.assertTrue((\"Connection\", \"close\") in inst.response_headers)", " def test_build_response_header_v10_keepalive_with_content_length(self):\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.request.headers[\"CONNECTION\"] = \"keep-alive\"\n inst.response_headers = [(\"Content-Length\", \"10\")]\n inst.version = \"1.0\"\n inst.content_length = 0\n result = inst.build_response_header()\n lines = filter_lines(result)\n self.assertEqual(len(lines), 5)\n self.assertEqual(lines[0], b\"HTTP/1.0 200 OK\")\n self.assertEqual(lines[1], b\"Connection: Keep-Alive\")\n self.assertEqual(lines[2], b\"Content-Length: 10\")\n self.assertTrue(lines[3].startswith(b\"Date:\"))\n self.assertEqual(lines[4], b\"Server: waitress\")\n self.assertEqual(inst.close_on_finish, False)", " def test_build_response_header_v11_connection_closed_by_client(self):\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.version = \"1.1\"\n inst.request.headers[\"CONNECTION\"] = \"close\"\n result = inst.build_response_header()\n lines = filter_lines(result)\n self.assertEqual(len(lines), 5)\n self.assertEqual(lines[0], b\"HTTP/1.1 200 OK\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertTrue(lines[2].startswith(b\"Date:\"))\n self.assertEqual(lines[3], b\"Server: waitress\")\n self.assertEqual(lines[4], b\"Transfer-Encoding: chunked\")\n self.assertTrue((\"Connection\", \"close\") in inst.response_headers)\n self.assertEqual(inst.close_on_finish, True)", " def test_build_response_header_v11_connection_keepalive_by_client(self):\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.request.headers[\"CONNECTION\"] = \"keep-alive\"\n inst.version = \"1.1\"\n result = inst.build_response_header()\n lines = filter_lines(result)\n self.assertEqual(len(lines), 5)\n self.assertEqual(lines[0], b\"HTTP/1.1 200 OK\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertTrue(lines[2].startswith(b\"Date:\"))\n self.assertEqual(lines[3], b\"Server: waitress\")\n self.assertEqual(lines[4], b\"Transfer-Encoding: chunked\")\n self.assertTrue((\"Connection\", \"close\") in inst.response_headers)\n self.assertEqual(inst.close_on_finish, True)", " def test_build_response_header_v11_200_no_content_length(self):\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.version = \"1.1\"\n result = inst.build_response_header()\n lines = filter_lines(result)\n self.assertEqual(len(lines), 5)\n self.assertEqual(lines[0], b\"HTTP/1.1 200 OK\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertTrue(lines[2].startswith(b\"Date:\"))\n self.assertEqual(lines[3], b\"Server: waitress\")\n self.assertEqual(lines[4], b\"Transfer-Encoding: chunked\")\n self.assertEqual(inst.close_on_finish, True)\n self.assertTrue((\"Connection\", \"close\") in inst.response_headers)", " def test_build_response_header_v11_204_no_content_length_or_transfer_encoding(self):\n # RFC 7230: MUST NOT send Transfer-Encoding or Content-Length\n # for any response with a status code of 1xx or 204.\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.version = \"1.1\"\n inst.status = \"204 No Content\"\n result = inst.build_response_header()\n lines = filter_lines(result)\n self.assertEqual(len(lines), 4)\n self.assertEqual(lines[0], b\"HTTP/1.1 204 No Content\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertTrue(lines[2].startswith(b\"Date:\"))\n self.assertEqual(lines[3], b\"Server: waitress\")\n self.assertEqual(inst.close_on_finish, True)\n self.assertTrue((\"Connection\", \"close\") in inst.response_headers)", " def test_build_response_header_v11_1xx_no_content_length_or_transfer_encoding(self):\n # RFC 7230: MUST NOT send Transfer-Encoding or Content-Length\n # for any response with a status code of 1xx or 204.\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.version = \"1.1\"\n inst.status = \"100 Continue\"\n result = inst.build_response_header()\n lines = filter_lines(result)\n self.assertEqual(len(lines), 4)\n self.assertEqual(lines[0], b\"HTTP/1.1 100 Continue\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertTrue(lines[2].startswith(b\"Date:\"))\n self.assertEqual(lines[3], b\"Server: waitress\")\n self.assertEqual(inst.close_on_finish, True)\n self.assertTrue((\"Connection\", \"close\") in inst.response_headers)", " def test_build_response_header_v11_304_no_content_length_or_transfer_encoding(self):\n # RFC 7230: MUST NOT send Transfer-Encoding or Content-Length\n # for any response with a status code of 1xx, 204 or 304.\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.version = \"1.1\"\n inst.status = \"304 Not Modified\"\n result = inst.build_response_header()\n lines = filter_lines(result)\n self.assertEqual(len(lines), 4)\n self.assertEqual(lines[0], b\"HTTP/1.1 304 Not Modified\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertTrue(lines[2].startswith(b\"Date:\"))\n self.assertEqual(lines[3], b\"Server: waitress\")\n self.assertEqual(inst.close_on_finish, True)\n self.assertTrue((\"Connection\", \"close\") in inst.response_headers)", " def test_build_response_header_via_added(self):\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.version = \"1.0\"\n inst.response_headers = [(\"Server\", \"abc\")]\n result = inst.build_response_header()\n lines = filter_lines(result)\n self.assertEqual(len(lines), 5)\n self.assertEqual(lines[0], b\"HTTP/1.0 200 OK\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertTrue(lines[2].startswith(b\"Date:\"))\n self.assertEqual(lines[3], b\"Server: abc\")\n self.assertEqual(lines[4], b\"Via: waitress\")", " def test_build_response_header_date_exists(self):\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.version = \"1.0\"\n inst.response_headers = [(\"Date\", \"date\")]\n result = inst.build_response_header()\n lines = filter_lines(result)\n self.assertEqual(len(lines), 4)\n self.assertEqual(lines[0], b\"HTTP/1.0 200 OK\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertTrue(lines[2].startswith(b\"Date:\"))\n self.assertEqual(lines[3], b\"Server: waitress\")", " def test_build_response_header_preexisting_content_length(self):\n inst = self._makeOne()\n inst.request = DummyParser()\n inst.version = \"1.1\"\n inst.content_length = 100\n result = inst.build_response_header()\n lines = filter_lines(result)\n self.assertEqual(len(lines), 4)\n self.assertEqual(lines[0], b\"HTTP/1.1 200 OK\")\n self.assertEqual(lines[1], b\"Content-Length: 100\")\n self.assertTrue(lines[2].startswith(b\"Date:\"))\n self.assertEqual(lines[3], b\"Server: waitress\")", " def test_remove_content_length_header(self):\n inst = self._makeOne()\n inst.response_headers = [(\"Content-Length\", \"70\")]\n inst.remove_content_length_header()\n self.assertEqual(inst.response_headers, [])", " def test_remove_content_length_header_with_other(self):\n inst = self._makeOne()\n inst.response_headers = [\n (\"Content-Length\", \"70\"),\n (\"Content-Type\", \"text/html\"),\n ]\n inst.remove_content_length_header()\n self.assertEqual(inst.response_headers, [(\"Content-Type\", \"text/html\")])", " def test_start(self):\n inst = self._makeOne()\n inst.start()\n self.assertTrue(inst.start_time)", " def test_finish_didnt_write_header(self):\n inst = self._makeOne()\n inst.wrote_header = False\n inst.complete = True\n inst.finish()\n self.assertTrue(inst.channel.written)", " def test_finish_wrote_header(self):\n inst = self._makeOne()\n inst.wrote_header = True\n inst.finish()\n self.assertFalse(inst.channel.written)", " def test_finish_chunked_response(self):\n inst = self._makeOne()\n inst.wrote_header = True\n inst.chunked_response = True\n inst.finish()\n self.assertEqual(inst.channel.written, b\"0\\r\\n\\r\\n\")", " def test_write_wrote_header(self):\n inst = self._makeOne()\n inst.wrote_header = True\n inst.complete = True\n inst.content_length = 3\n inst.write(b\"abc\")\n self.assertEqual(inst.channel.written, b\"abc\")", " def test_write_header_not_written(self):\n inst = self._makeOne()\n inst.wrote_header = False\n inst.complete = True\n inst.write(b\"abc\")\n self.assertTrue(inst.channel.written)\n self.assertEqual(inst.wrote_header, True)", " def test_write_start_response_uncalled(self):\n inst = self._makeOne()\n self.assertRaises(RuntimeError, inst.write, b\"\")", " def test_write_chunked_response(self):\n inst = self._makeOne()\n inst.wrote_header = True\n inst.chunked_response = True\n inst.complete = True\n inst.write(b\"abc\")\n self.assertEqual(inst.channel.written, b\"3\\r\\nabc\\r\\n\")", " def test_write_preexisting_content_length(self):\n inst = self._makeOne()\n inst.wrote_header = True\n inst.complete = True\n inst.content_length = 1\n inst.logger = DummyLogger()\n inst.write(b\"abc\")\n self.assertTrue(inst.channel.written)\n self.assertEqual(inst.logged_write_excess, True)\n self.assertEqual(len(inst.logger.logged), 1)", "\nclass TestWSGITask(unittest.TestCase):\n def _makeOne(self, channel=None, request=None):\n if channel is None:\n channel = DummyChannel()\n if request is None:\n request = DummyParser()\n from waitress.task import WSGITask", " return WSGITask(channel, request)", " def test_service(self):\n inst = self._makeOne()", " def execute():\n inst.executed = True", " inst.execute = execute\n inst.complete = True\n inst.service()\n self.assertTrue(inst.start_time)\n self.assertTrue(inst.close_on_finish)\n self.assertTrue(inst.channel.written)\n self.assertEqual(inst.executed, True)", " def test_service_server_raises_socket_error(self):\n import socket", " inst = self._makeOne()", " def execute():\n raise socket.error", " inst.execute = execute\n self.assertRaises(socket.error, inst.service)\n self.assertTrue(inst.start_time)\n self.assertTrue(inst.close_on_finish)\n self.assertFalse(inst.channel.written)", " def test_execute_app_calls_start_response_twice_wo_exc_info(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [])\n start_response(\"200 OK\", [])", " inst = self._makeOne()\n inst.channel.server.application = app\n self.assertRaises(AssertionError, inst.execute)", " def test_execute_app_calls_start_response_w_exc_info_complete(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [], [ValueError, ValueError(), None])\n return [b\"a\"]", " inst = self._makeOne()\n inst.complete = True\n inst.channel.server.application = app\n inst.execute()\n self.assertTrue(inst.complete)\n self.assertEqual(inst.status, \"200 OK\")\n self.assertTrue(inst.channel.written)", " def test_execute_app_calls_start_response_w_excinf_headers_unwritten(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [], [ValueError, None, None])\n return [b\"a\"]", " inst = self._makeOne()\n inst.wrote_header = False\n inst.channel.server.application = app\n inst.response_headers = [(\"a\", \"b\")]\n inst.execute()\n self.assertTrue(inst.complete)\n self.assertEqual(inst.status, \"200 OK\")\n self.assertTrue(inst.channel.written)\n self.assertFalse((\"a\", \"b\") in inst.response_headers)", " def test_execute_app_calls_start_response_w_excinf_headers_written(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [], [ValueError, ValueError(), None])", " inst = self._makeOne()\n inst.complete = True\n inst.wrote_header = True\n inst.channel.server.application = app\n self.assertRaises(ValueError, inst.execute)", " def test_execute_bad_header_key(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [(None, \"a\")])", " inst = self._makeOne()\n inst.channel.server.application = app\n self.assertRaises(AssertionError, inst.execute)", " def test_execute_bad_header_value(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [(\"a\", None)])", " inst = self._makeOne()\n inst.channel.server.application = app\n self.assertRaises(AssertionError, inst.execute)", " def test_execute_hopbyhop_header(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [(\"Connection\", \"close\")])", " inst = self._makeOne()\n inst.channel.server.application = app\n self.assertRaises(AssertionError, inst.execute)", " def test_execute_bad_header_value_control_characters(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [(\"a\", \"\\n\")])", " inst = self._makeOne()\n inst.channel.server.application = app\n self.assertRaises(ValueError, inst.execute)", " def test_execute_bad_header_name_control_characters(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [(\"a\\r\", \"value\")])", " inst = self._makeOne()\n inst.channel.server.application = app\n self.assertRaises(ValueError, inst.execute)", " def test_execute_bad_status_control_characters(self):\n def app(environ, start_response):\n start_response(\"200 OK\\r\", [])", " inst = self._makeOne()\n inst.channel.server.application = app\n self.assertRaises(ValueError, inst.execute)", " def test_preserve_header_value_order(self):\n def app(environ, start_response):\n write = start_response(\"200 OK\", [(\"C\", \"b\"), (\"A\", \"b\"), (\"A\", \"a\")])\n write(b\"abc\")\n return []", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.execute()\n self.assertTrue(b\"A: b\\r\\nA: a\\r\\nC: b\\r\\n\" in inst.channel.written)", " def test_execute_bad_status_value(self):\n def app(environ, start_response):\n start_response(None, [])", " inst = self._makeOne()\n inst.channel.server.application = app\n self.assertRaises(AssertionError, inst.execute)", " def test_execute_with_content_length_header(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [(\"Content-Length\", \"1\")])\n return [b\"a\"]", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.execute()\n self.assertEqual(inst.content_length, 1)", " def test_execute_app_calls_write(self):\n def app(environ, start_response):\n write = start_response(\"200 OK\", [(\"Content-Length\", \"3\")])\n write(b\"abc\")\n return []", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.execute()\n self.assertEqual(inst.channel.written[-3:], b\"abc\")", " def test_execute_app_returns_len1_chunk_without_cl(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [])\n return [b\"abc\"]", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.execute()\n self.assertEqual(inst.content_length, 3)", " def test_execute_app_returns_empty_chunk_as_first(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [])\n return [\"\", b\"abc\"]", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.execute()\n self.assertEqual(inst.content_length, None)", " def test_execute_app_returns_too_many_bytes(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [(\"Content-Length\", \"1\")])\n return [b\"abc\"]", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.logger = DummyLogger()\n inst.execute()\n self.assertEqual(inst.close_on_finish, True)\n self.assertEqual(len(inst.logger.logged), 1)", " def test_execute_app_returns_too_few_bytes(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [(\"Content-Length\", \"3\")])\n return [b\"a\"]", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.logger = DummyLogger()\n inst.execute()\n self.assertEqual(inst.close_on_finish, True)\n self.assertEqual(len(inst.logger.logged), 1)", " def test_execute_app_do_not_warn_on_head(self):\n def app(environ, start_response):\n start_response(\"200 OK\", [(\"Content-Length\", \"3\")])\n return [b\"\"]", " inst = self._makeOne()\n inst.request.command = \"HEAD\"\n inst.channel.server.application = app\n inst.logger = DummyLogger()\n inst.execute()\n self.assertEqual(inst.close_on_finish, True)\n self.assertEqual(len(inst.logger.logged), 0)", " def test_execute_app_without_body_204_logged(self):\n def app(environ, start_response):\n start_response(\"204 No Content\", [(\"Content-Length\", \"3\")])\n return [b\"abc\"]", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.logger = DummyLogger()\n inst.execute()\n self.assertEqual(inst.close_on_finish, True)\n self.assertNotIn(b\"abc\", inst.channel.written)\n self.assertNotIn(b\"Content-Length\", inst.channel.written)\n self.assertNotIn(b\"Transfer-Encoding\", inst.channel.written)\n self.assertEqual(len(inst.logger.logged), 1)", " def test_execute_app_without_body_304_logged(self):\n def app(environ, start_response):\n start_response(\"304 Not Modified\", [(\"Content-Length\", \"3\")])\n return [b\"abc\"]", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.logger = DummyLogger()\n inst.execute()\n self.assertEqual(inst.close_on_finish, True)\n self.assertNotIn(b\"abc\", inst.channel.written)\n self.assertNotIn(b\"Content-Length\", inst.channel.written)\n self.assertNotIn(b\"Transfer-Encoding\", inst.channel.written)\n self.assertEqual(len(inst.logger.logged), 1)", " def test_execute_app_returns_closeable(self):\n class closeable(list):\n def close(self):\n self.closed = True", " foo = closeable([b\"abc\"])", " def app(environ, start_response):\n start_response(\"200 OK\", [(\"Content-Length\", \"3\")])\n return foo", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.execute()\n self.assertEqual(foo.closed, True)", " def test_execute_app_returns_filewrapper_prepare_returns_True(self):\n from waitress.buffers import ReadOnlyFileBasedBuffer", " f = io.BytesIO(b\"abc\")\n app_iter = ReadOnlyFileBasedBuffer(f, 8192)", " def app(environ, start_response):\n start_response(\"200 OK\", [(\"Content-Length\", \"3\")])\n return app_iter", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.execute()\n self.assertTrue(inst.channel.written) # header\n self.assertEqual(inst.channel.otherdata, [app_iter])", " def test_execute_app_returns_filewrapper_prepare_returns_True_nocl(self):\n from waitress.buffers import ReadOnlyFileBasedBuffer", " f = io.BytesIO(b\"abc\")\n app_iter = ReadOnlyFileBasedBuffer(f, 8192)", " def app(environ, start_response):\n start_response(\"200 OK\", [])\n return app_iter", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.execute()\n self.assertTrue(inst.channel.written) # header\n self.assertEqual(inst.channel.otherdata, [app_iter])\n self.assertEqual(inst.content_length, 3)", " def test_execute_app_returns_filewrapper_prepare_returns_True_badcl(self):\n from waitress.buffers import ReadOnlyFileBasedBuffer", " f = io.BytesIO(b\"abc\")\n app_iter = ReadOnlyFileBasedBuffer(f, 8192)", " def app(environ, start_response):\n start_response(\"200 OK\", [])\n return app_iter", " inst = self._makeOne()\n inst.channel.server.application = app\n inst.content_length = 10\n inst.response_headers = [(\"Content-Length\", \"10\")]\n inst.execute()\n self.assertTrue(inst.channel.written) # header\n self.assertEqual(inst.channel.otherdata, [app_iter])\n self.assertEqual(inst.content_length, 3)\n self.assertEqual(dict(inst.response_headers)[\"Content-Length\"], \"3\")", " def test_get_environment_already_cached(self):\n inst = self._makeOne()\n inst.environ = object()\n self.assertEqual(inst.get_environment(), inst.environ)", " def test_get_environment_path_startswith_more_than_one_slash(self):\n inst = self._makeOne()\n request = DummyParser()\n request.path = \"///abc\"\n inst.request = request\n environ = inst.get_environment()\n self.assertEqual(environ[\"PATH_INFO\"], \"/abc\")", " def test_get_environment_path_empty(self):\n inst = self._makeOne()\n request = DummyParser()\n request.path = \"\"\n inst.request = request\n environ = inst.get_environment()\n self.assertEqual(environ[\"PATH_INFO\"], \"\")", " def test_get_environment_no_query(self):\n inst = self._makeOne()\n request = DummyParser()\n inst.request = request\n environ = inst.get_environment()\n self.assertEqual(environ[\"QUERY_STRING\"], \"\")", " def test_get_environment_with_query(self):\n inst = self._makeOne()\n request = DummyParser()\n request.query = \"abc\"\n inst.request = request\n environ = inst.get_environment()\n self.assertEqual(environ[\"QUERY_STRING\"], \"abc\")", " def test_get_environ_with_url_prefix_miss(self):\n inst = self._makeOne()\n inst.channel.server.adj.url_prefix = \"/foo\"\n request = DummyParser()\n request.path = \"/bar\"\n inst.request = request\n environ = inst.get_environment()\n self.assertEqual(environ[\"PATH_INFO\"], \"/bar\")\n self.assertEqual(environ[\"SCRIPT_NAME\"], \"/foo\")", " def test_get_environ_with_url_prefix_hit(self):\n inst = self._makeOne()\n inst.channel.server.adj.url_prefix = \"/foo\"\n request = DummyParser()\n request.path = \"/foo/fuz\"\n inst.request = request\n environ = inst.get_environment()\n self.assertEqual(environ[\"PATH_INFO\"], \"/fuz\")\n self.assertEqual(environ[\"SCRIPT_NAME\"], \"/foo\")", " def test_get_environ_with_url_prefix_empty_path(self):\n inst = self._makeOne()\n inst.channel.server.adj.url_prefix = \"/foo\"\n request = DummyParser()\n request.path = \"/foo\"\n inst.request = request\n environ = inst.get_environment()\n self.assertEqual(environ[\"PATH_INFO\"], \"\")\n self.assertEqual(environ[\"SCRIPT_NAME\"], \"/foo\")", " def test_get_environment_values(self):\n import sys", " inst = self._makeOne()\n request = DummyParser()\n request.headers = {\n \"CONTENT_TYPE\": \"abc\",\n \"CONTENT_LENGTH\": \"10\",\n \"X_FOO\": \"BAR\",\n \"CONNECTION\": \"close\",\n }\n request.query = \"abc\"\n inst.request = request\n environ = inst.get_environment()", " # nail the keys of environ\n self.assertEqual(\n sorted(environ.keys()),\n [\n \"CONTENT_LENGTH\",\n \"CONTENT_TYPE\",\n \"HTTP_CONNECTION\",\n \"HTTP_X_FOO\",\n \"PATH_INFO\",\n \"QUERY_STRING\",\n \"REMOTE_ADDR\",\n \"REMOTE_HOST\",\n \"REMOTE_PORT\",\n \"REQUEST_METHOD\",\n \"SCRIPT_NAME\",\n \"SERVER_NAME\",\n \"SERVER_PORT\",\n \"SERVER_PROTOCOL\",\n \"SERVER_SOFTWARE\",\n \"wsgi.errors\",\n \"wsgi.file_wrapper\",\n \"wsgi.input\",\n \"wsgi.input_terminated\",\n \"wsgi.multiprocess\",\n \"wsgi.multithread\",\n \"wsgi.run_once\",\n \"wsgi.url_scheme\",\n \"wsgi.version\",\n ],\n )", " self.assertEqual(environ[\"REQUEST_METHOD\"], \"GET\")\n self.assertEqual(environ[\"SERVER_PORT\"], \"80\")\n self.assertEqual(environ[\"SERVER_NAME\"], \"localhost\")\n self.assertEqual(environ[\"SERVER_SOFTWARE\"], \"waitress\")\n self.assertEqual(environ[\"SERVER_PROTOCOL\"], \"HTTP/1.0\")\n self.assertEqual(environ[\"SCRIPT_NAME\"], \"\")\n self.assertEqual(environ[\"HTTP_CONNECTION\"], \"close\")\n self.assertEqual(environ[\"PATH_INFO\"], \"/\")\n self.assertEqual(environ[\"QUERY_STRING\"], \"abc\")\n self.assertEqual(environ[\"REMOTE_ADDR\"], \"127.0.0.1\")\n self.assertEqual(environ[\"REMOTE_HOST\"], \"127.0.0.1\")\n self.assertEqual(environ[\"REMOTE_PORT\"], \"39830\")\n self.assertEqual(environ[\"CONTENT_TYPE\"], \"abc\")\n self.assertEqual(environ[\"CONTENT_LENGTH\"], \"10\")\n self.assertEqual(environ[\"HTTP_X_FOO\"], \"BAR\")\n self.assertEqual(environ[\"wsgi.version\"], (1, 0))\n self.assertEqual(environ[\"wsgi.url_scheme\"], \"http\")\n self.assertEqual(environ[\"wsgi.errors\"], sys.stderr)\n self.assertEqual(environ[\"wsgi.multithread\"], True)\n self.assertEqual(environ[\"wsgi.multiprocess\"], False)\n self.assertEqual(environ[\"wsgi.run_once\"], False)\n self.assertEqual(environ[\"wsgi.input\"], \"stream\")\n self.assertEqual(environ[\"wsgi.input_terminated\"], True)\n self.assertEqual(inst.environ, environ)", "\nclass TestErrorTask(unittest.TestCase):\n def _makeOne(self, channel=None, request=None):\n if channel is None:\n channel = DummyChannel()\n if request is None:\n request = DummyParser()\n request.error = self._makeDummyError()\n from waitress.task import ErrorTask", " return ErrorTask(channel, request)", " def _makeDummyError(self):\n from waitress.utilities import Error", " e = Error(\"body\")\n e.code = 432\n e.reason = \"Too Ugly\"\n return e", " def test_execute_http_10(self):\n inst = self._makeOne()\n inst.execute()\n lines = filter_lines(inst.channel.written)\n self.assertEqual(len(lines), 9)\n self.assertEqual(lines[0], b\"HTTP/1.0 432 Too Ugly\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertEqual(lines[2], b\"Content-Length: 43\")\n self.assertEqual(lines[3], b\"Content-Type: text/plain\")\n self.assertTrue(lines[4])\n self.assertEqual(lines[5], b\"Server: waitress\")\n self.assertEqual(lines[6], b\"Too Ugly\")\n self.assertEqual(lines[7], b\"body\")\n self.assertEqual(lines[8], b\"(generated by waitress)\")", " def test_execute_http_11(self):\n inst = self._makeOne()\n inst.version = \"1.1\"\n inst.execute()\n lines = filter_lines(inst.channel.written)", "", " self.assertEqual(len(lines), 9)\n self.assertEqual(lines[0], b\"HTTP/1.1 432 Too Ugly\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertEqual(lines[2], b\"Content-Length: 43\")\n self.assertEqual(lines[3], b\"Content-Type: text/plain\")\n self.assertTrue(lines[4])\n self.assertEqual(lines[5], b\"Server: waitress\")\n self.assertEqual(lines[6], b\"Too Ugly\")\n self.assertEqual(lines[7], b\"body\")\n self.assertEqual(lines[8], b\"(generated by waitress)\")\n", " def test_execute_http_11_close(self):\n inst = self._makeOne()\n inst.version = \"1.1\"\n inst.request.headers[\"CONNECTION\"] = \"close\"\n inst.execute()\n lines = filter_lines(inst.channel.written)\n self.assertEqual(len(lines), 9)\n self.assertEqual(lines[0], b\"HTTP/1.1 432 Too Ugly\")\n self.assertEqual(lines[1], b\"Connection: close\")\n self.assertEqual(lines[2], b\"Content-Length: 43\")\n self.assertEqual(lines[3], b\"Content-Type: text/plain\")\n self.assertTrue(lines[4])\n self.assertEqual(lines[5], b\"Server: waitress\")\n self.assertEqual(lines[6], b\"Too Ugly\")\n self.assertEqual(lines[7], b\"body\")\n self.assertEqual(lines[8], b\"(generated by waitress)\")", " def test_execute_http_11_keep_forces_close(self):", " inst = self._makeOne()\n inst.version = \"1.1\"\n inst.request.headers[\"CONNECTION\"] = \"keep-alive\"\n inst.execute()\n lines = filter_lines(inst.channel.written)", " self.assertEqual(len(lines), 9)", " self.assertEqual(lines[0], b\"HTTP/1.1 432 Too Ugly\")", " self.assertEqual(lines[1], b\"Connection: close\")\n self.assertEqual(lines[2], b\"Content-Length: 43\")\n self.assertEqual(lines[3], b\"Content-Type: text/plain\")\n self.assertTrue(lines[4])\n self.assertEqual(lines[5], b\"Server: waitress\")\n self.assertEqual(lines[6], b\"Too Ugly\")\n self.assertEqual(lines[7], b\"body\")\n self.assertEqual(lines[8], b\"(generated by waitress)\")", "", "class DummyTask(object):\n serviced = False\n cancelled = False", " def service(self):\n self.serviced = True", " def cancel(self):\n self.cancelled = True", "\nclass DummyAdj(object):\n log_socket_errors = True\n ident = \"waitress\"\n host = \"127.0.0.1\"\n port = 80\n url_prefix = \"\"", "\nclass DummyServer(object):\n server_name = \"localhost\"\n effective_port = 80", " def __init__(self):\n self.adj = DummyAdj()", "\nclass DummyChannel(object):\n closed_when_done = False\n adj = DummyAdj()\n creation_time = 0\n addr = (\"127.0.0.1\", 39830)", " def __init__(self, server=None):\n if server is None:\n server = DummyServer()\n self.server = server\n self.written = b\"\"\n self.otherdata = []", " def write_soon(self, data):\n if isinstance(data, bytes):\n self.written += data\n else:\n self.otherdata.append(data)\n return len(data)", "\nclass DummyParser(object):\n version = \"1.0\"\n command = \"GET\"\n path = \"/\"\n query = \"\"\n url_scheme = \"http\"\n expect_continue = False\n headers_finished = False", " def __init__(self):\n self.headers = {}", " def get_body_stream(self):\n return \"stream\"", "\ndef filter_lines(s):\n return list(filter(None, s.split(b\"\\r\\n\")))", "\nclass DummyLogger(object):\n def __init__(self):\n self.logged = []", " def warning(self, msg, *args):\n self.logged.append(msg % args)", " def exception(self, msg, *args):\n self.logged.append(msg % args)" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "##############################################################################\n#\n# Copyright (c) 2002 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################", "import unittest", "\nclass Test_parse_http_date(unittest.TestCase):\n def _callFUT(self, v):\n from waitress.utilities import parse_http_date", " return parse_http_date(v)", " def test_rfc850(self):\n val = \"Tuesday, 08-Feb-94 14:15:29 GMT\"\n result = self._callFUT(val)\n self.assertEqual(result, 760716929)", " def test_rfc822(self):\n val = \"Sun, 08 Feb 1994 14:15:29 GMT\"\n result = self._callFUT(val)\n self.assertEqual(result, 760716929)", " def test_neither(self):\n val = \"\"\n result = self._callFUT(val)\n self.assertEqual(result, 0)", "\nclass Test_build_http_date(unittest.TestCase):\n def test_rountdrip(self):\n from waitress.utilities import build_http_date, parse_http_date\n from time import time", " t = int(time())\n self.assertEqual(t, parse_http_date(build_http_date(t)))", "\nclass Test_unpack_rfc850(unittest.TestCase):\n def _callFUT(self, val):\n from waitress.utilities import unpack_rfc850, rfc850_reg", " return unpack_rfc850(rfc850_reg.match(val.lower()))", " def test_it(self):\n val = \"Tuesday, 08-Feb-94 14:15:29 GMT\"\n result = self._callFUT(val)\n self.assertEqual(result, (1994, 2, 8, 14, 15, 29, 0, 0, 0))", "\nclass Test_unpack_rfc_822(unittest.TestCase):\n def _callFUT(self, val):\n from waitress.utilities import unpack_rfc822, rfc822_reg", " return unpack_rfc822(rfc822_reg.match(val.lower()))", " def test_it(self):\n val = \"Sun, 08 Feb 1994 14:15:29 GMT\"\n result = self._callFUT(val)\n self.assertEqual(result, (1994, 2, 8, 14, 15, 29, 0, 0, 0))", "\nclass Test_find_double_newline(unittest.TestCase):\n def _callFUT(self, val):\n from waitress.utilities import find_double_newline", " return find_double_newline(val)", " def test_empty(self):\n self.assertEqual(self._callFUT(b\"\"), -1)", " def test_one_linefeed(self):\n self.assertEqual(self._callFUT(b\"\\n\"), -1)", " def test_double_linefeed(self):", " self.assertEqual(self._callFUT(b\"\\n\\n\"), 2)", "\n def test_one_crlf(self):\n self.assertEqual(self._callFUT(b\"\\r\\n\"), -1)", " def test_double_crfl(self):\n self.assertEqual(self._callFUT(b\"\\r\\n\\r\\n\"), 4)", " def test_mixed(self):", " self.assertEqual(self._callFUT(b\"\\n\\n00\\r\\n\\r\\n\"), 2)", "", "class TestBadRequest(unittest.TestCase):\n def _makeOne(self):\n from waitress.utilities import BadRequest", " return BadRequest(1)", " def test_it(self):\n inst = self._makeOne()\n self.assertEqual(inst.body, 1)", "\nclass Test_undquote(unittest.TestCase):\n def _callFUT(self, value):\n from waitress.utilities import undquote", " return undquote(value)", " def test_empty(self):\n self.assertEqual(self._callFUT(\"\"), \"\")", " def test_quoted(self):\n self.assertEqual(self._callFUT('\"test\"'), \"test\")", " def test_unquoted(self):\n self.assertEqual(self._callFUT(\"test\"), \"test\")", " def test_quoted_backslash_quote(self):\n self.assertEqual(self._callFUT('\"\\\\\"\"'), '\"')", " def test_quoted_htab(self):\n self.assertEqual(self._callFUT('\"\\t\"'), \"\\t\")", " def test_quoted_backslash_htab(self):\n self.assertEqual(self._callFUT('\"\\\\\\t\"'), \"\\t\")", " def test_quoted_backslash_invalid(self):\n self.assertRaises(ValueError, self._callFUT, '\"\\\\\"')", " def test_invalid_quoting(self):\n self.assertRaises(ValueError, self._callFUT, '\"test')", " def test_invalid_quoting_single_quote(self):\n self.assertRaises(ValueError, self._callFUT, '\"')" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "##############################################################################\n#\n# Copyright (c) 2002 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################", "import unittest", "\nclass Test_parse_http_date(unittest.TestCase):\n def _callFUT(self, v):\n from waitress.utilities import parse_http_date", " return parse_http_date(v)", " def test_rfc850(self):\n val = \"Tuesday, 08-Feb-94 14:15:29 GMT\"\n result = self._callFUT(val)\n self.assertEqual(result, 760716929)", " def test_rfc822(self):\n val = \"Sun, 08 Feb 1994 14:15:29 GMT\"\n result = self._callFUT(val)\n self.assertEqual(result, 760716929)", " def test_neither(self):\n val = \"\"\n result = self._callFUT(val)\n self.assertEqual(result, 0)", "\nclass Test_build_http_date(unittest.TestCase):\n def test_rountdrip(self):\n from waitress.utilities import build_http_date, parse_http_date\n from time import time", " t = int(time())\n self.assertEqual(t, parse_http_date(build_http_date(t)))", "\nclass Test_unpack_rfc850(unittest.TestCase):\n def _callFUT(self, val):\n from waitress.utilities import unpack_rfc850, rfc850_reg", " return unpack_rfc850(rfc850_reg.match(val.lower()))", " def test_it(self):\n val = \"Tuesday, 08-Feb-94 14:15:29 GMT\"\n result = self._callFUT(val)\n self.assertEqual(result, (1994, 2, 8, 14, 15, 29, 0, 0, 0))", "\nclass Test_unpack_rfc_822(unittest.TestCase):\n def _callFUT(self, val):\n from waitress.utilities import unpack_rfc822, rfc822_reg", " return unpack_rfc822(rfc822_reg.match(val.lower()))", " def test_it(self):\n val = \"Sun, 08 Feb 1994 14:15:29 GMT\"\n result = self._callFUT(val)\n self.assertEqual(result, (1994, 2, 8, 14, 15, 29, 0, 0, 0))", "\nclass Test_find_double_newline(unittest.TestCase):\n def _callFUT(self, val):\n from waitress.utilities import find_double_newline", " return find_double_newline(val)", " def test_empty(self):\n self.assertEqual(self._callFUT(b\"\"), -1)", " def test_one_linefeed(self):\n self.assertEqual(self._callFUT(b\"\\n\"), -1)", " def test_double_linefeed(self):", " self.assertEqual(self._callFUT(b\"\\n\\n\"), -1)", "\n def test_one_crlf(self):\n self.assertEqual(self._callFUT(b\"\\r\\n\"), -1)", " def test_double_crfl(self):\n self.assertEqual(self._callFUT(b\"\\r\\n\\r\\n\"), 4)", " def test_mixed(self):", " self.assertEqual(self._callFUT(b\"\\n\\n00\\r\\n\\r\\n\"), 8)", "", "class TestBadRequest(unittest.TestCase):\n def _makeOne(self):\n from waitress.utilities import BadRequest", " return BadRequest(1)", " def test_it(self):\n inst = self._makeOne()\n self.assertEqual(inst.body, 1)", "\nclass Test_undquote(unittest.TestCase):\n def _callFUT(self, value):\n from waitress.utilities import undquote", " return undquote(value)", " def test_empty(self):\n self.assertEqual(self._callFUT(\"\"), \"\")", " def test_quoted(self):\n self.assertEqual(self._callFUT('\"test\"'), \"test\")", " def test_unquoted(self):\n self.assertEqual(self._callFUT(\"test\"), \"test\")", " def test_quoted_backslash_quote(self):\n self.assertEqual(self._callFUT('\"\\\\\"\"'), '\"')", " def test_quoted_htab(self):\n self.assertEqual(self._callFUT('\"\\t\"'), \"\\t\")", " def test_quoted_backslash_htab(self):\n self.assertEqual(self._callFUT('\"\\\\\\t\"'), \"\\t\")", " def test_quoted_backslash_invalid(self):\n self.assertRaises(ValueError, self._callFUT, '\"\\\\\"')", " def test_invalid_quoting(self):\n self.assertRaises(ValueError, self._callFUT, '\"test')", " def test_invalid_quoting_single_quote(self):\n self.assertRaises(ValueError, self._callFUT, '\"')" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "##############################################################################\n#\n# Copyright (c) 2004 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Utility functions\n\"\"\"", "import calendar\nimport errno\nimport logging\nimport os\nimport re\nimport stat\nimport time", "logger = logging.getLogger(\"waitress\")\nqueue_logger = logging.getLogger(\"waitress.queue\")", "\ndef find_double_newline(s):\n \"\"\"Returns the position just after a double newline in the given string.\"\"\"", " pos1 = s.find(b\"\\n\\r\\n\") # One kind of double newline\n if pos1 >= 0:\n pos1 += 3\n pos2 = s.find(b\"\\n\\n\") # Another kind of double newline\n if pos2 >= 0:\n pos2 += 2", " if pos1 >= 0:\n if pos2 >= 0:\n return min(pos1, pos2)\n else:\n return pos1\n else:\n return pos2", "", "def concat(*args):\n return \"\".join(args)", "\ndef join(seq, field=\" \"):\n return field.join(seq)", "\ndef group(s):\n return \"(\" + s + \")\"", "\nshort_days = [\"sun\", \"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\"]\nlong_days = [\n \"sunday\",\n \"monday\",\n \"tuesday\",\n \"wednesday\",\n \"thursday\",\n \"friday\",\n \"saturday\",\n]", "short_day_reg = group(join(short_days, \"|\"))\nlong_day_reg = group(join(long_days, \"|\"))", "daymap = {}\nfor i in range(7):\n daymap[short_days[i]] = i\n daymap[long_days[i]] = i", "hms_reg = join(3 * [group(\"[0-9][0-9]\")], \":\")", "months = [\n \"jan\",\n \"feb\",\n \"mar\",\n \"apr\",\n \"may\",\n \"jun\",\n \"jul\",\n \"aug\",\n \"sep\",\n \"oct\",\n \"nov\",\n \"dec\",\n]", "monmap = {}\nfor i in range(12):\n monmap[months[i]] = i + 1", "months_reg = group(join(months, \"|\"))", "# From draft-ietf-http-v11-spec-07.txt/3.3.1\n# Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123\n# Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036\n# Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format", "# rfc822 format\nrfc822_date = join(\n [\n concat(short_day_reg, \",\"), # day\n group(\"[0-9][0-9]?\"), # date\n months_reg, # month\n group(\"[0-9]+\"), # year\n hms_reg, # hour minute second\n \"gmt\",\n ],\n \" \",\n)", "rfc822_reg = re.compile(rfc822_date)", "\ndef unpack_rfc822(m):\n g = m.group\n return (\n int(g(4)), # year\n monmap[g(3)], # month\n int(g(2)), # day\n int(g(5)), # hour\n int(g(6)), # minute\n int(g(7)), # second\n 0,\n 0,\n 0,\n )", "\n# rfc850 format\nrfc850_date = join(\n [\n concat(long_day_reg, \",\"),\n join([group(\"[0-9][0-9]?\"), months_reg, group(\"[0-9]+\")], \"-\"),\n hms_reg,\n \"gmt\",\n ],\n \" \",\n)", "rfc850_reg = re.compile(rfc850_date)\n# they actually unpack the same way\ndef unpack_rfc850(m):\n g = m.group\n yr = g(4)\n if len(yr) == 2:\n yr = \"19\" + yr\n return (\n int(yr), # year\n monmap[g(3)], # month\n int(g(2)), # day\n int(g(5)), # hour\n int(g(6)), # minute\n int(g(7)), # second\n 0,\n 0,\n 0,\n )", "\n# parsdate.parsedate - ~700/sec.\n# parse_http_date - ~1333/sec.", "weekdayname = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"]\nmonthname = [\n None,\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n]", "\ndef build_http_date(when):\n year, month, day, hh, mm, ss, wd, y, z = time.gmtime(when)\n return \"%s, %02d %3s %4d %02d:%02d:%02d GMT\" % (\n weekdayname[wd],\n day,\n monthname[month],\n year,\n hh,\n mm,\n ss,\n )", "\ndef parse_http_date(d):\n d = d.lower()\n m = rfc850_reg.match(d)\n if m and m.end() == len(d):\n retval = int(calendar.timegm(unpack_rfc850(m)))\n else:\n m = rfc822_reg.match(d)\n if m and m.end() == len(d):\n retval = int(calendar.timegm(unpack_rfc822(m)))\n else:\n return 0\n return retval", "\n# RFC 5234 Appendix B.1 \"Core Rules\":\n# VCHAR = %x21-7E\n# ; visible (printing) characters\nvchar_re = \"\\x21-\\x7e\"", "# RFC 7230 Section 3.2.6 \"Field Value Components\":\n# quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE\n# qdtext = HTAB / SP /%x21 / %x23-5B / %x5D-7E / obs-text\n# obs-text = %x80-FF\n# quoted-pair = \"\\\" ( HTAB / SP / VCHAR / obs-text )\nobs_text_re = \"\\x80-\\xff\"", "# The '\\\\' between \\x5b and \\x5d is needed to escape \\x5d (']')\nqdtext_re = \"[\\t \\x21\\x23-\\x5b\\\\\\x5d-\\x7e\" + obs_text_re + \"]\"", "quoted_pair_re = r\"\\\\\" + \"([\\t \" + vchar_re + obs_text_re + \"])\"\nquoted_string_re = '\"(?:(?:' + qdtext_re + \")|(?:\" + quoted_pair_re + '))*\"'", "quoted_string = re.compile(quoted_string_re)\nquoted_pair = re.compile(quoted_pair_re)", "\ndef undquote(value):\n if value.startswith('\"') and value.endswith('\"'):\n # So it claims to be DQUOTE'ed, let's validate that\n matches = quoted_string.match(value)", " if matches and matches.end() == len(value):\n # Remove the DQUOTE's from the value\n value = value[1:-1]", " # Remove all backslashes that are followed by a valid vchar or\n # obs-text\n value = quoted_pair.sub(r\"\\1\", value)", " return value\n elif not value.startswith('\"') and not value.endswith('\"'):\n return value", " raise ValueError(\"Invalid quoting in value\")", "\ndef cleanup_unix_socket(path):\n try:\n st = os.stat(path)\n except OSError as exc:\n if exc.errno != errno.ENOENT:\n raise # pragma: no cover\n else:\n if stat.S_ISSOCK(st.st_mode):\n try:\n os.remove(path)\n except OSError: # pragma: no cover\n # avoid race condition error during tests\n pass", "\nclass Error(object):", "", " def __init__(self, body):\n self.body = body", " def to_response(self):\n status = \"%s %s\" % (self.code, self.reason)\n body = \"%s\\r\\n\\r\\n%s\" % (self.reason, self.body)\n tag = \"\\r\\n\\r\\n(generated by waitress)\"\n body = body + tag\n headers = [(\"Content-Type\", \"text/plain\")]", "", " return status, headers, body", " def wsgi_response(self, environ, start_response):\n status, headers, body = self.to_response()\n start_response(status, headers)\n yield body", "\nclass BadRequest(Error):\n code = 400\n reason = \"Bad Request\"", "\nclass RequestHeaderFieldsTooLarge(BadRequest):\n code = 431\n reason = \"Request Header Fields Too Large\"", "\nclass RequestEntityTooLarge(BadRequest):\n code = 413\n reason = \"Request Entity Too Large\"", "\nclass InternalServerError(Error):\n code = 500\n reason = \"Internal Server Error\"", "" ]
[ 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "##############################################################################\n#\n# Copyright (c) 2004 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Utility functions\n\"\"\"", "import calendar\nimport errno\nimport logging\nimport os\nimport re\nimport stat\nimport time", "logger = logging.getLogger(\"waitress\")\nqueue_logger = logging.getLogger(\"waitress.queue\")", "\ndef find_double_newline(s):\n \"\"\"Returns the position just after a double newline in the given string.\"\"\"", " pos = s.find(b\"\\r\\n\\r\\n\")", " if pos >= 0:\n pos += 4", " return pos", "", "def concat(*args):\n return \"\".join(args)", "\ndef join(seq, field=\" \"):\n return field.join(seq)", "\ndef group(s):\n return \"(\" + s + \")\"", "\nshort_days = [\"sun\", \"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\"]\nlong_days = [\n \"sunday\",\n \"monday\",\n \"tuesday\",\n \"wednesday\",\n \"thursday\",\n \"friday\",\n \"saturday\",\n]", "short_day_reg = group(join(short_days, \"|\"))\nlong_day_reg = group(join(long_days, \"|\"))", "daymap = {}\nfor i in range(7):\n daymap[short_days[i]] = i\n daymap[long_days[i]] = i", "hms_reg = join(3 * [group(\"[0-9][0-9]\")], \":\")", "months = [\n \"jan\",\n \"feb\",\n \"mar\",\n \"apr\",\n \"may\",\n \"jun\",\n \"jul\",\n \"aug\",\n \"sep\",\n \"oct\",\n \"nov\",\n \"dec\",\n]", "monmap = {}\nfor i in range(12):\n monmap[months[i]] = i + 1", "months_reg = group(join(months, \"|\"))", "# From draft-ietf-http-v11-spec-07.txt/3.3.1\n# Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123\n# Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036\n# Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format", "# rfc822 format\nrfc822_date = join(\n [\n concat(short_day_reg, \",\"), # day\n group(\"[0-9][0-9]?\"), # date\n months_reg, # month\n group(\"[0-9]+\"), # year\n hms_reg, # hour minute second\n \"gmt\",\n ],\n \" \",\n)", "rfc822_reg = re.compile(rfc822_date)", "\ndef unpack_rfc822(m):\n g = m.group\n return (\n int(g(4)), # year\n monmap[g(3)], # month\n int(g(2)), # day\n int(g(5)), # hour\n int(g(6)), # minute\n int(g(7)), # second\n 0,\n 0,\n 0,\n )", "\n# rfc850 format\nrfc850_date = join(\n [\n concat(long_day_reg, \",\"),\n join([group(\"[0-9][0-9]?\"), months_reg, group(\"[0-9]+\")], \"-\"),\n hms_reg,\n \"gmt\",\n ],\n \" \",\n)", "rfc850_reg = re.compile(rfc850_date)\n# they actually unpack the same way\ndef unpack_rfc850(m):\n g = m.group\n yr = g(4)\n if len(yr) == 2:\n yr = \"19\" + yr\n return (\n int(yr), # year\n monmap[g(3)], # month\n int(g(2)), # day\n int(g(5)), # hour\n int(g(6)), # minute\n int(g(7)), # second\n 0,\n 0,\n 0,\n )", "\n# parsdate.parsedate - ~700/sec.\n# parse_http_date - ~1333/sec.", "weekdayname = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"]\nmonthname = [\n None,\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n]", "\ndef build_http_date(when):\n year, month, day, hh, mm, ss, wd, y, z = time.gmtime(when)\n return \"%s, %02d %3s %4d %02d:%02d:%02d GMT\" % (\n weekdayname[wd],\n day,\n monthname[month],\n year,\n hh,\n mm,\n ss,\n )", "\ndef parse_http_date(d):\n d = d.lower()\n m = rfc850_reg.match(d)\n if m and m.end() == len(d):\n retval = int(calendar.timegm(unpack_rfc850(m)))\n else:\n m = rfc822_reg.match(d)\n if m and m.end() == len(d):\n retval = int(calendar.timegm(unpack_rfc822(m)))\n else:\n return 0\n return retval", "\n# RFC 5234 Appendix B.1 \"Core Rules\":\n# VCHAR = %x21-7E\n# ; visible (printing) characters\nvchar_re = \"\\x21-\\x7e\"", "# RFC 7230 Section 3.2.6 \"Field Value Components\":\n# quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE\n# qdtext = HTAB / SP /%x21 / %x23-5B / %x5D-7E / obs-text\n# obs-text = %x80-FF\n# quoted-pair = \"\\\" ( HTAB / SP / VCHAR / obs-text )\nobs_text_re = \"\\x80-\\xff\"", "# The '\\\\' between \\x5b and \\x5d is needed to escape \\x5d (']')\nqdtext_re = \"[\\t \\x21\\x23-\\x5b\\\\\\x5d-\\x7e\" + obs_text_re + \"]\"", "quoted_pair_re = r\"\\\\\" + \"([\\t \" + vchar_re + obs_text_re + \"])\"\nquoted_string_re = '\"(?:(?:' + qdtext_re + \")|(?:\" + quoted_pair_re + '))*\"'", "quoted_string = re.compile(quoted_string_re)\nquoted_pair = re.compile(quoted_pair_re)", "\ndef undquote(value):\n if value.startswith('\"') and value.endswith('\"'):\n # So it claims to be DQUOTE'ed, let's validate that\n matches = quoted_string.match(value)", " if matches and matches.end() == len(value):\n # Remove the DQUOTE's from the value\n value = value[1:-1]", " # Remove all backslashes that are followed by a valid vchar or\n # obs-text\n value = quoted_pair.sub(r\"\\1\", value)", " return value\n elif not value.startswith('\"') and not value.endswith('\"'):\n return value", " raise ValueError(\"Invalid quoting in value\")", "\ndef cleanup_unix_socket(path):\n try:\n st = os.stat(path)\n except OSError as exc:\n if exc.errno != errno.ENOENT:\n raise # pragma: no cover\n else:\n if stat.S_ISSOCK(st.st_mode):\n try:\n os.remove(path)\n except OSError: # pragma: no cover\n # avoid race condition error during tests\n pass", "\nclass Error(object):", " code = 500\n reason = \"Internal Server Error\"\n", " def __init__(self, body):\n self.body = body", " def to_response(self):\n status = \"%s %s\" % (self.code, self.reason)\n body = \"%s\\r\\n\\r\\n%s\" % (self.reason, self.body)\n tag = \"\\r\\n\\r\\n(generated by waitress)\"\n body = body + tag\n headers = [(\"Content-Type\", \"text/plain\")]", "", " return status, headers, body", " def wsgi_response(self, environ, start_response):\n status, headers, body = self.to_response()\n start_response(status, headers)\n yield body", "\nclass BadRequest(Error):\n code = 400\n reason = \"Bad Request\"", "\nclass RequestHeaderFieldsTooLarge(BadRequest):\n code = 431\n reason = \"Request Header Fields Too Large\"", "\nclass RequestEntityTooLarge(BadRequest):\n code = 413\n reason = \"Request Entity Too Large\"", "\nclass InternalServerError(Error):\n code = 500\n reason = \"Internal Server Error\"", "", "class ServerNotImplemented(Error):\n code = 501\n reason = \"Not Implemented\"" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [79, 0, 38, 303, 143, 364, 536, 1586, 478, 155, 921, 96, 308], "buggy_code_start_loc": [1, 0, 37, 22, 17, 356, 426, 182, 18, 86, 879, 86, 31], "filenames": ["CHANGES.txt", "HISTORY.txt", "setup.py", "waitress/parser.py", "waitress/receiver.py", "waitress/task.py", "waitress/tests/test_channel.py", "waitress/tests/test_functional.py", "waitress/tests/test_parser.py", "waitress/tests/test_receiver.py", "waitress/tests/test_task.py", "waitress/tests/test_utilities.py", "waitress/utilities.py"], "fixing_code_end_loc": [78, 80, 38, 358, 180, 360, 522, 1611, 579, 227, 923, 96, 310], "fixing_code_start_loc": [1, 1, 37, 21, 17, 356, 426, 182, 18, 86, 878, 86, 31], "message": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:agendaless:waitress:*:*:*:*:*:*:*:*", "matchCriteriaId": "6CAB3F2E-7A4C-4F03-8848-E03D4E028F59", "versionEndExcluding": "1.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:communications_cloud_native_core_network_function_cloud_native_environment:1.10.0:*:*:*:*:*:*:*", "matchCriteriaId": "C2A5B24D-BDF2-423C-98EA-A40778C01A05", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:30:*:*:*:*:*:*:*", "matchCriteriaId": "97A4B8DF-58DA-4AB6-A1F9-331B36409BA3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:31:*:*:*:*:*:*:*", "matchCriteriaId": "80F0FA5D-8D3B-4C0E-81E2-87998286AF33", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redhat:openstack:15:*:*:*:*:*:*:*", "matchCriteriaId": "70108B60-8817-40B4-8412-796A592E4E5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Waitress through version 1.3.1 would parse the Transfer-Encoding header and only look for a single string value, if that value was not chunked it would fall through and use the Content-Length header instead. According to the HTTP standard Transfer-Encoding should be a comma separated list, with the inner-most encoding first, followed by any further transfer codings, ending with chunked. Requests sent with: \"Transfer-Encoding: gzip, chunked\" would incorrectly get ignored, and the request would use a Content-Length header instead to determine the body size of the HTTP message. This could allow for Waitress to treat a single request as multiple requests in the case of HTTP pipelining. This issue is fixed in Waitress 1.4.0."}, {"lang": "es", "value": "Waitress versi\u00f3n hasta 1.3.1 analizar\u00eda el encabezado Transfer-Encoding y solo buscar\u00eda un \u00fanico valor de cadena, si ese valor no se dividiera, caer\u00eda y usar\u00eda en su lugar el encabezado Content-Length. De acuerdo con el est\u00e1ndar HTTP, Transfer-Encoding debe ser una lista separada por comas, con la codificaci\u00f3n m\u00e1s interna primero, seguida de cualquier otra codificaci\u00f3n de transferencia, que termine en fragmentos. Las peticiones enviadas con: \"Transfer-Encoding: gzip, chunked\" se ignorar\u00edan incorrectamente, y la petici\u00f3n utilizar\u00eda un encabezado Content-Length para determinar el tama\u00f1o del cuerpo del mensaje HTTP. Esto podr\u00eda permitir que Waitress trate una petici\u00f3n \u00fanica como peticiones m\u00faltiples en el caso de la canalizaci\u00f3n HTTP. Este problema fue corregido en Waitress versi\u00f3n 1.4.0."}], "evaluatorComment": null, "id": "CVE-2019-16786", "lastModified": "2022-09-23T18:58:17.537", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2019-12-20T23:15:11.277", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://access.redhat.com/errata/RHSA-2020:0720"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://docs.pylonsproject.org/projects/waitress/en/latest/#security-fixes"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Pylons/waitress/security/advisories/GHSA-g2xc-35jw-c63p"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2022/05/msg00011.html"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/GVDHR2DNKCNQ7YQXISJ45NT4IQDX3LJ7/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/LYEOTGWJZVKPRXX2HBNVIYWCX73QYPM5/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-444"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Pylons/waitress/commit/f11093a6b3240fc26830b6111e826128af7771c3"}, "type": "CWE-444"}
323
Determine whether the {function_name} code is vulnerable or not.
[ "import { Meteor } from \"meteor/meteor\";\nimport nodemailer from \"nodemailer\";\nimport smtpPool from \"nodemailer-smtp-pool\";", "const Future = Npm.require(\"fibers/future\");", "const getSmtpConfig = function () {\n const config = Settings.findOne({ _id: \"smtpConfig\" });\n return config && config.value;\n};", "const makePool = function (mailConfig) {\n if (!mailConfig.hostname) {\n throw new Error(\"This Sandstorm server has not been configured to send email.\");\n }", " let auth = false;\n if (mailConfig.auth && (mailConfig.auth.user || mailConfig.auth.pass)) {\n auth = mailConfig.auth;\n }", " const secure = (mailConfig.port === 465);\n const tlsOptions = {\n // Previously, node 0.10 did not attempt to validate certificates received when connecting\n // with STARTTLS, so to avoid regressing we need to preserve that behavior here for now.\n rejectUnauthorized: false,\n };", " const pool = nodemailer.createTransport(smtpPool({\n host: mailConfig.hostname,\n port: mailConfig.port,\n secure,\n tls: tlsOptions,\n auth,\n // TODO(someday): allow maxConnections to be configured?\n }));", " pool._futureWrappedSendMail = _.bind(Future.wrap(pool.sendMail), pool);\n return pool;\n};", "// We construct the SMTP pool at the first call to Email.send, so that\n// other code like migrations can modify the SMTP configuration.\nlet pool;\nlet configured = false;", "Meteor.startup(function () {\n Settings.find({ _id: \"smtpConfig\" }).observeChanges({\n removed: function () {\n configured = false;\n },", " changed: function () {\n configured = false;\n },", " added: function () {\n configured = false;\n },\n });\n});", "const getPool = function (smtpConfig) {\n if (smtpConfig) {\n return makePool(smtpConfig);\n } else if (!configured) {\n configured = true;\n const config = getSmtpConfig();\n if (config) {\n pool = makePool(config);\n }\n }", " return pool;\n};", "const smtpSend = function (pool, mailOptions) {", "", " pool._futureWrappedSendMail(mailOptions).wait();\n};", "", "\nconst rawSend = function (mailOptions, smtpConfig) {\n // Sends an email mailOptions object structured as described in\n // https://github.com/nodemailer/mailcomposer#e-mail-message-fields\n // across the transport described by smtpConfig.", "", " const pool = getPool(smtpConfig);\n if (pool) {\n smtpSend(pool, mailOptions);\n } else {\n throw new Error(\"SMTP pool is misconfigured.\");\n }\n};", "// Old comment below\n/**\n * Send an email.\n *\n * Connects to the mail server configured via the MAIL_URL environment\n * variable. If unset, prints formatted message to stdout. The \"from\" option\n * is required, and at least one of \"to\", \"cc\", and \"bcc\" must be provided;\n * all other options are optional.\n *\n * @param options\n * @param options.from {String} RFC5322 \"From:\" address\n * @param options.to {String|String[]} RFC5322 \"To:\" address[es]\n * @param options.cc {String|String[]} RFC5322 \"Cc:\" address[es]\n * @param options.bcc {String|String[]} RFC5322 \"Bcc:\" address[es]\n * @param options.replyTo {String|String[]} RFC5322 \"Reply-To:\" address[es]\n * @param options.subject {String} RFC5322 \"Subject:\" line\n * @param options.text {String} RFC5322 mail body (plain text)\n * @param options.html {String} RFC5322 mail body (HTML)\n * @param options.headers {Object} custom RFC5322 headers (dictionary)\n */", "// New API doc comment below\n/**\n * @summary Send an email. Throws an `Error` on failure to contact mail server\n * or if mail server returns an error. All fields should match\n * [RFC5322](http://tools.ietf.org/html/rfc5322) specification.\n * @locus Server\n * @param {Object} options\n * @param {String} options.from \"From:\" address (required)\n * @param {String|String[]} options.to,cc,bcc,replyTo\n * \"To:\", \"Cc:\", \"Bcc:\", and \"Reply-To:\" addresses\n * @param {String} [options.subject] \"Subject:\" line\n * @param {String} [options.text|html] Mail body (in plain text or HTML)\n * @param {Object} [options.headers] Dictionary of custom headers\n * @param {Object} [options.smtpConfig] SMTP server to use. Otherwise defaults to configured one.\n * @param {String} [options.smtpConfig.hostname] SMTP server hostname.\n * @param {Number} [options.smtpConfig.port] SMTP server port.\n * @param {Object} [options.smtpConfig.auth] SMTP server authentication tokens. Optional.\n * @param {String} [options.smtpConfig.auth.user] Username of user to log in to SMTP server as. Optional.\n * @param {String} [options.smtpConfig.auth.pass] Password of user to log in to SMTP server as. Optional.\n * @param {Object} [options.attachments] Attachments. See:\n * https://github.com/nodemailer/mailcomposer/tree/v0.1.15#add-attachments\n * @param {String} [options.envelopeFrom] Envelope sender.\n */\nconst send = function (options) {\n // Unpack options\n const {\n from,\n to,\n cc,\n bcc,\n replyTo,\n subject,\n text,\n html,\n envelopeFrom,\n headers,\n attachments,\n smtpConfig,\n } = options;", " const opts = {\n from,\n to,\n cc,\n bcc,\n replyTo,\n subject,\n text,\n html,\n headers,\n attachments,\n };", " if (envelopeFrom) {\n opts.envelope = {\n from: envelopeFrom,\n to,\n cc,\n bcc,\n };\n }", " rawSend(opts, smtpConfig);\n};", "export { send, rawSend };", "// TODO(cleanup): Remove this once BlackrockPayments code finds a better way to import it.\nglobal.SandstormEmail = { send };" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [84, 1522, 203, 231], "buggy_code_start_loc": [77, 1518, 202, 188], "filenames": ["shell/imports/server/email.js", "shell/packages/sandstorm-db/db.js", "shell/server/accounts/email-token/token-server.js", "shell/server/admin-server.js"], "fixing_code_end_loc": [121, 1524, 203, 232], "fixing_code_start_loc": [78, 1519, 202, 188], "message": "A remote attacker could bypass the Sandstorm organization restriction before build 0.203 via a comma in an email-address field.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sandstorm:sandstorm:*:*:*:*:*:*:*:*", "matchCriteriaId": "683ED5F0-D297-4A47-ADF9-186832F3A3AD", "versionEndExcluding": "0.203", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A remote attacker could bypass the Sandstorm organization restriction before build 0.203 via a comma in an email-address field."}, {"lang": "es", "value": "Un atacante remoto podr\u00eda omitir la restricci\u00f3n de organizaci\u00f3n de Sandstorm antes de la build 0.203 mediante una coma en un campo email-address."}], "evaluatorComment": null, "id": "CVE-2017-6199", "lastModified": "2018-03-13T19:27:30.200", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-02-06T16:29:00.730", "references": [{"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://devco.re/blog/2018/01/26/Sandstorm-Security-Review-CVE-2017-6200-en/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/sandstorm-io/sandstorm/blob/v0.202/shell/packages/sandstorm-db/db.js#L1112"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/sandstorm-io/sandstorm/commit/37bd9a7f4eb776cdc2d3615f0bfea1254b66f59d"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://sandstorm.io/news/2017-03-02-security-review"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-287"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/sandstorm-io/sandstorm/commit/37bd9a7f4eb776cdc2d3615f0bfea1254b66f59d"}, "type": "CWE-287"}
324
Determine whether the {function_name} code is vulnerable or not.
[ "import { Meteor } from \"meteor/meteor\";\nimport nodemailer from \"nodemailer\";\nimport smtpPool from \"nodemailer-smtp-pool\";", "const Future = Npm.require(\"fibers/future\");", "const getSmtpConfig = function () {\n const config = Settings.findOne({ _id: \"smtpConfig\" });\n return config && config.value;\n};", "const makePool = function (mailConfig) {\n if (!mailConfig.hostname) {\n throw new Error(\"This Sandstorm server has not been configured to send email.\");\n }", " let auth = false;\n if (mailConfig.auth && (mailConfig.auth.user || mailConfig.auth.pass)) {\n auth = mailConfig.auth;\n }", " const secure = (mailConfig.port === 465);\n const tlsOptions = {\n // Previously, node 0.10 did not attempt to validate certificates received when connecting\n // with STARTTLS, so to avoid regressing we need to preserve that behavior here for now.\n rejectUnauthorized: false,\n };", " const pool = nodemailer.createTransport(smtpPool({\n host: mailConfig.hostname,\n port: mailConfig.port,\n secure,\n tls: tlsOptions,\n auth,\n // TODO(someday): allow maxConnections to be configured?\n }));", " pool._futureWrappedSendMail = _.bind(Future.wrap(pool.sendMail), pool);\n return pool;\n};", "// We construct the SMTP pool at the first call to Email.send, so that\n// other code like migrations can modify the SMTP configuration.\nlet pool;\nlet configured = false;", "Meteor.startup(function () {\n Settings.find({ _id: \"smtpConfig\" }).observeChanges({\n removed: function () {\n configured = false;\n },", " changed: function () {\n configured = false;\n },", " added: function () {\n configured = false;\n },\n });\n});", "const getPool = function (smtpConfig) {\n if (smtpConfig) {\n return makePool(smtpConfig);\n } else if (!configured) {\n configured = true;\n const config = getSmtpConfig();\n if (config) {\n pool = makePool(config);\n }\n }", " return pool;\n};", "const smtpSend = function (pool, mailOptions) {", " console.log(mailOptions);", " pool._futureWrappedSendMail(mailOptions).wait();\n};", "\n// From http://emailregex.com/, which claims this is the W3C standard for the HTML input element,\n// although their link is broken and I can find no evidence that this is a standard. The page\n// lists several regexes, ostensibly in syntaxes intended for different programming languages,\n// but each regex is in fact substantially different for no apparent reason.\n//\n// The most important thing here is that we disallow separators that might allow a user to confuse\n// nodemailer into thinking the address is a list. Unfortunately, nodemailer will happily separate\n// strings into lists splitting on all kinds of separator characters, such as commas, semicolons,\n// etc. This regex should accomplish that both by disallowing the separators, and by disallowing\n// multiple @ signs. The rest is for show.\nconst EMAIL_REGEX = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$/;", "function validateEmail(email) {\n if (email instanceof Array) {\n email.forEach(validateEmail);\n } else if (typeof email === \"object\" && \"address\" in email) {\n validateEmail(email.address);\n } else if (email) {\n check(email, String);", " if (!email.match(EMAIL_REGEX)) {\n console.log(email);\n throw new Meteor.Error(400, \"invalid e-mail address\");\n }\n }\n}", "\nconst rawSend = function (mailOptions, smtpConfig) {\n // Sends an email mailOptions object structured as described in\n // https://github.com/nodemailer/mailcomposer#e-mail-message-fields\n // across the transport described by smtpConfig.", "\n // For fields that are supposed to be lists of addresses, if only a single string is provided,\n // wrap it in an array. This prevents nodemailer from interpreting the address as a\n // comma-separated list.\n [\"from\", \"to\", \"cc\", \"bcc\", \"replyTo\"].forEach(field => {\n validateEmail(mailOptions[field]);\n });\n", " const pool = getPool(smtpConfig);\n if (pool) {\n smtpSend(pool, mailOptions);\n } else {\n throw new Error(\"SMTP pool is misconfigured.\");\n }\n};", "// Old comment below\n/**\n * Send an email.\n *\n * Connects to the mail server configured via the MAIL_URL environment\n * variable. If unset, prints formatted message to stdout. The \"from\" option\n * is required, and at least one of \"to\", \"cc\", and \"bcc\" must be provided;\n * all other options are optional.\n *\n * @param options\n * @param options.from {String} RFC5322 \"From:\" address\n * @param options.to {String|String[]} RFC5322 \"To:\" address[es]\n * @param options.cc {String|String[]} RFC5322 \"Cc:\" address[es]\n * @param options.bcc {String|String[]} RFC5322 \"Bcc:\" address[es]\n * @param options.replyTo {String|String[]} RFC5322 \"Reply-To:\" address[es]\n * @param options.subject {String} RFC5322 \"Subject:\" line\n * @param options.text {String} RFC5322 mail body (plain text)\n * @param options.html {String} RFC5322 mail body (HTML)\n * @param options.headers {Object} custom RFC5322 headers (dictionary)\n */", "// New API doc comment below\n/**\n * @summary Send an email. Throws an `Error` on failure to contact mail server\n * or if mail server returns an error. All fields should match\n * [RFC5322](http://tools.ietf.org/html/rfc5322) specification.\n * @locus Server\n * @param {Object} options\n * @param {String} options.from \"From:\" address (required)\n * @param {String|String[]} options.to,cc,bcc,replyTo\n * \"To:\", \"Cc:\", \"Bcc:\", and \"Reply-To:\" addresses\n * @param {String} [options.subject] \"Subject:\" line\n * @param {String} [options.text|html] Mail body (in plain text or HTML)\n * @param {Object} [options.headers] Dictionary of custom headers\n * @param {Object} [options.smtpConfig] SMTP server to use. Otherwise defaults to configured one.\n * @param {String} [options.smtpConfig.hostname] SMTP server hostname.\n * @param {Number} [options.smtpConfig.port] SMTP server port.\n * @param {Object} [options.smtpConfig.auth] SMTP server authentication tokens. Optional.\n * @param {String} [options.smtpConfig.auth.user] Username of user to log in to SMTP server as. Optional.\n * @param {String} [options.smtpConfig.auth.pass] Password of user to log in to SMTP server as. Optional.\n * @param {Object} [options.attachments] Attachments. See:\n * https://github.com/nodemailer/mailcomposer/tree/v0.1.15#add-attachments\n * @param {String} [options.envelopeFrom] Envelope sender.\n */\nconst send = function (options) {\n // Unpack options\n const {\n from,\n to,\n cc,\n bcc,\n replyTo,\n subject,\n text,\n html,\n envelopeFrom,\n headers,\n attachments,\n smtpConfig,\n } = options;", " const opts = {\n from,\n to,\n cc,\n bcc,\n replyTo,\n subject,\n text,\n html,\n headers,\n attachments,\n };", " if (envelopeFrom) {\n opts.envelope = {\n from: envelopeFrom,\n to,\n cc,\n bcc,\n };\n }", " rawSend(opts, smtpConfig);\n};", "export { send, rawSend };", "// TODO(cleanup): Remove this once BlackrockPayments code finds a better way to import it.\nglobal.SandstormEmail = { send };" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [84, 1522, 203, 231], "buggy_code_start_loc": [77, 1518, 202, 188], "filenames": ["shell/imports/server/email.js", "shell/packages/sandstorm-db/db.js", "shell/server/accounts/email-token/token-server.js", "shell/server/admin-server.js"], "fixing_code_end_loc": [121, 1524, 203, 232], "fixing_code_start_loc": [78, 1519, 202, 188], "message": "A remote attacker could bypass the Sandstorm organization restriction before build 0.203 via a comma in an email-address field.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sandstorm:sandstorm:*:*:*:*:*:*:*:*", "matchCriteriaId": "683ED5F0-D297-4A47-ADF9-186832F3A3AD", "versionEndExcluding": "0.203", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A remote attacker could bypass the Sandstorm organization restriction before build 0.203 via a comma in an email-address field."}, {"lang": "es", "value": "Un atacante remoto podr\u00eda omitir la restricci\u00f3n de organizaci\u00f3n de Sandstorm antes de la build 0.203 mediante una coma en un campo email-address."}], "evaluatorComment": null, "id": "CVE-2017-6199", "lastModified": "2018-03-13T19:27:30.200", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-02-06T16:29:00.730", "references": [{"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://devco.re/blog/2018/01/26/Sandstorm-Security-Review-CVE-2017-6200-en/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/sandstorm-io/sandstorm/blob/v0.202/shell/packages/sandstorm-db/db.js#L1112"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/sandstorm-io/sandstorm/commit/37bd9a7f4eb776cdc2d3615f0bfea1254b66f59d"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://sandstorm.io/news/2017-03-02-security-review"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-287"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/sandstorm-io/sandstorm/commit/37bd9a7f4eb776cdc2d3615f0bfea1254b66f59d"}, "type": "CWE-287"}
324
Determine whether the {function_name} code is vulnerable or not.
[ "// Sandstorm - Personal Cloud Sandbox\n// Copyright (c) 2014 Sandstorm Development Group, Inc. and contributors\n// All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.", "// This file defines the database schema.", "// Useful for debugging: Set the env variable LOG_MONGO_QUERIES to have the server write every\n// query it makes, so you can see if it's doing queries too often, etc.\nif (Meteor.isServer && process.env.LOG_MONGO_QUERIES) {\n const oldFind = Mongo.Collection.prototype.find;\n Mongo.Collection.prototype.find = function () {\n console.log(this._prefix, arguments);\n return oldFind.apply(this, arguments);\n };\n}", "// Helper so that we don't have to if (Meteor.isServer) before declaring indexes.\nif (Meteor.isServer) {\n Mongo.Collection.prototype.ensureIndexOnServer = Mongo.Collection.prototype._ensureIndex;\n} else {\n Mongo.Collection.prototype.ensureIndexOnServer = function () {};\n}", "// TODO(soon): Systematically go through this file and add ensureIndexOnServer() as needed.", "const collectionOptions = { defineMutationMethods: Meteor.isClient };\n// Set to `true` on the client so that method simulation works. Set to `false` on the server\n// so that we can be extra certain that all mutations must go through methods.", "// Users = new Mongo.Collection(\"users\");\n// The users collection is special and can be accessed through `Meteor.users`.\n// See https://docs.meteor.com/#/full/meteor_users.\n//\n// There are two distinct types of entries in the users collection: identities and accounts. An\n// identity contains personal profile information and typically includes some intrinsic method for\n// authenticating as the owner of that information.\n//\n// An account is an owner of app actions, grains, contacts, notifications, and payment info.\n// Each account can have multiple identities linked to it. To log in as an account you must first\n// authenticate as one of its linked identities.\n//\n// Every user contains the following fields:\n// _id: Unique string ID. For accounts, this is random. For identities, this is the globally\n// stable SHA-256 ID of this identity, hex-encoded.\n// createdAt: Date when this entry was added to the collection.\n// lastActive: Date of the user's most recent interaction with this Sandstorm server.\n// services: Object containing login data used by Meteor authentication services.\n// expires: Date when this user should be deleted. Only present for demo users.\n// upgradedFromDemo: If present, the date when this user was upgraded from being a demo user.\n// TODO(cleanup): Unlike other dates in our database, this is stored as a number\n// rather than as a Date object. We should fix that.\n// appDemoId: If present and non-null, then the user is a demo user who arrived via an /appdemo/\n// link. This field contains the app ID of the app that the user started out demoing.\n// Unlike the `expires` field, this field is not cleared when the user upgrades from\n// being a demo user.\n// suspended: If this exists, this account/identity is supsended. Both accounts and identities\n// can be suspended. After some amount of time, the user will be completely deleted\n// and removed from the DB.\n// It is an object with fields:\n// voluntary: Boolean. This is true if the user initiated it. They will have the\n// chance to still login and reverse the suspension/deletion.\n// admin: The userId of the admin who suspended the account.\n// timestamp: Date object. When the suspension occurred.\n// willDelete: Boolean. If true, this account will be deleted after some time.\n//\n// Identity users additionally contain the following fields:\n// profile: Object containing the data that will be shared with users and grains that come into\n// contact with this identity. Includes the following fields:\n// service: String containing the name of this identity's authentication method.\n// name: String containing the chosen display name of the identity.\n// handle: String containing the identity's preferred handle.\n// picture: _id into the StaticAssets table for the identity's picture. If not present,\n// an identicon will be used.\n// pronoun: One of \"male\", \"female\", \"neutral\", or \"robot\".\n// unverifiedEmail: If present, a string containing an email address specified by the user.\n// referredBy: ID of the Account that referred this Identity.\n//\n// Account users additionally contain the following fields:\n// loginIdentities: Array of identity objects, each of which may include the following fields.\n// id: The globally-stable SHA-256 ID of this identity, hex-encoded.\n// nonloginIdentities: Array of identity objects, of the same form as `loginIdentities`. We use\n// a separate array here so that we can use a Mongo index to enforce the\n// invariant that an identity only be a login identity for a single account.\n// primaryEmail: String containing this account's primary email address. Must be a verified adress\n// of one of this account's linked identities. Call SandstormDb.getUserEmails()\n// to do this checking automatically.\n// isAdmin: Boolean indicating whether this account is allowed to access the Sandstorm admin panel.\n// signupKey: If this is an invited user, then this field contains their signup key.\n// signupNote: If the user was invited through a link, then this field contains the note that the\n// inviter admin attached to the key.\n// signupEmail: If the user was invited by email, then this field contains the email address that\n// the invite was sent to.\n// hasCompletedSignup: True if this account has confirmed its profile and agreed to this server's\n// terms of service.\n// plan: _id of an entry in the Plans table which determines the user's quota.\n// planBonus: {storage, compute, grains} bonus amounts to add to the user's plan. The payments\n// module writes data here; we merely read it. Missing fields should be treated as\n// zeroes. Does not yet include referral bonus, which is calculated separately.\n// TODO(cleanup): Use for referral bonus too.\n// storageUsage: Number of bytes this user is currently storing.\n// payments: Object defined by payments module, if loaded.\n// dailySentMailCount: Number of emails sent by this user today; used to limit spam.\n// accessRequests: Object containing the following fields; used to limit spam.\n// count: Number of \"request access\" emails during sent during the current interval.\n// resetOn: Date when the count should be reset.\n// referredByComplete: ID of the Account that referred this Account. If this is set, we\n// stop writing new referredBy values onto Identities for this account.\n// referredCompleteDate: The Date at which the completed referral occurred.\n// referredIdentityIds: List of Identity IDs that this Account has referred. This is used for\n// reliably determining which Identity's names are safe to display.\n// experiments: Object where each field is an experiment that the user is in, and each value\n// is the parameters for that experiment. Typically, the value simply names which\n// experiment group which the user is in, where \"control\" is one group. If an experiment\n// is not listed, then the user should not be considered at all for the purpose of that\n// experiment. Each experiment may define a point in time where users not already in the\n// experiment may be added to it and assigned to a group (for example, at user creation\n// time). Current experiments:\n// firstTimeBillingPrompt: Value is \"control\" or \"test\". Users are assigned to groups at\n// account creation on servers where billing is enabled (i.e. Oasis). Users in the\n// test group will see a plan selection dialog and asked to make an explitic choice\n// (possibly \"free\") before they can create grains (but not when opening someone\n// else's shared grain). The goal of the experiment is to determine whether this\n// prompt scares users away -- and also whether it increases paid signups.\n// freeGrainLimit: Value is \"control\" or or a number indicating the grain limit that the\n// user should receive when on the \"free\" plan, e.g. \"Infinity\".\n// stashedOldUser: A complete copy of this user from before the accounts/identities migration.\n// TODO(cleanup): Delete this field once we're sure it's safe to do so.", "Meteor.users.ensureIndexOnServer(\"services.google.email\", { sparse: 1 });\nMeteor.users.ensureIndexOnServer(\"services.github.emails.email\", { sparse: 1 });\nMeteor.users.ensureIndexOnServer(\"services.email.email\", { unique: 1, sparse: 1 });\nMeteor.users.ensureIndexOnServer(\"loginIdentities.id\", { unique: 1, sparse: 1 });\nMeteor.users.ensureIndexOnServer(\"nonloginIdentities.id\", { sparse: 1 });\nMeteor.users.ensureIndexOnServer(\"services.google.id\", { unique: 1, sparse: 1 });\nMeteor.users.ensureIndexOnServer(\"services.github.id\", { unique: 1, sparse: 1 });\nMeteor.users.ensureIndexOnServer(\"suspended.willDelete\", { sparse: 1 });", "// TODO(cleanup): This index is obsolete; delete it.\nMeteor.users.ensureIndexOnServer(\"identities.id\", { unique: 1, sparse: 1 });", "Packages = new Mongo.Collection(\"packages\", collectionOptions);\n// Packages which are installed or downloading.\n//\n// Each contains:\n// _id: 128-bit prefix of SHA-256 hash of spk file, hex-encoded.\n// status: String. One of \"download\", \"verify\", \"unpack\", \"analyze\", \"ready\", \"failed\", \"delete\"\n// progress: Float. -1 = N/A, 0-1 = fractional progress (e.g. download percentage),\n// >1 = download byte count.\n// error: If status is \"failed\", error message string.\n// manifest: If status is \"ready\", the package manifest. See \"Manifest\" in package.capnp.\n// appId: If status is \"ready\", the application ID string. Packages representing different\n// versions of the same app have the same appId. The spk tool defines the app ID format\n// and can cryptographically verify that a package belongs to a particular app ID.\n// shouldCleanup: If true, a reference to this package was recently dropped, and the package\n// collector should at some point check whether there are any other references and, if not,\n// delete the package.\n// url: When status is \"download\", the URL from which the SPK can be obtained, if provided.\n// isAutoUpdated: This package was downloaded as part of an auto-update. We shouldn't clean it up\n// even if it has no users.\n// authorPgpKeyFingerprint: Verified PGP key fingerprint (SHA-1, hex, all-caps) of the app\n// packager.", "DevPackages = new Mongo.Collection(\"devpackages\", collectionOptions);\n// List of packages currently made available via the dev tools running on the local machine.\n// This is normally empty; the only time it is non-empty is when a developer is using the spk tool\n// on the local machine to publish an under-development app to this server. That should only ever\n// happen on developers' desktop machines.\n//\n// While a dev package is published, it automatically appears as installed by every user of the\n// server, and it overrides all packages with the same application ID. If any instances of those\n// packages are currently open, they are killed and reset on publish.\n//\n// When the dev tool disconnects, the package is automatically unpublished, and any open instances\n// are again killed and refreshed.\n//\n// Each contains:\n// _id: The package ID string (as with Packages._id).\n// appId: The app ID this package is intended to override (as with Packages.appId).\n// timestamp: Time when the package was last updated. If this changes while the package is\n// published, all running instances are reset. This is used e.g. to reset the app each time\n// changes are made to the source code.\n// manifest: The app's manifest, as with Packages.manifest.\n// mountProc: True if the supervisor should mount /proc.", "UserActions = new Mongo.Collection(\"userActions\", collectionOptions);\n// List of actions that each user has installed which create new grains. Each app may install\n// some number of actions (usually, one).\n//\n// Each contains:\n// _id: random\n// userId: Account ID of the user who has installed this action.\n// packageId: Package used to run this action.\n// appId: Same as Packages.findOne(packageId).appId; denormalized for searchability.\n// appTitle: Same as Packages.findOne(packageId).manifest.appTitle; denormalized so\n// that clients can access it without subscribing to the Packages collection.\n// appVersion: Same as Packages.findOne(packageId).manifest.appVersion; denormalized for\n// searchability.\n// appMarketingVersion: Human-readable presentation of the app version, e.g. \"2.9.17\"\n// title: JSON-encoded LocalizedText title for this action, e.g.\n// `{defaultText: \"New Spreadsheet\"}`.\n// nounPhrase: JSON-encoded LocalizedText describing what is created when this action is run.\n// command: Manifest.Command to run this action (see package.capnp).", "Grains = new Mongo.Collection(\"grains\", collectionOptions);\n// Grains belonging to users.\n//\n// Each contains:\n// _id: random\n// packageId: _id of the package of which this grain is an instance.\n// packageSalt: If present, a random string that will used in session ID generation. This field\n// is usually updated when `packageId` is updated, triggering automatic refreshes for\n// clients with active sessions.\n// appId: Same as Packages.findOne(packageId).appId; denormalized for searchability.\n// appVersion: Same as Packages.findOne(packageId).manifest.appVersion; denormalized for\n// searchability.\n// userId: The _id of the account that owns this grain.\n// identityId: The identity with which the owning account prefers to open this grain.\n// title: Human-readable string title, as chosen by the user.\n// lastUsed: Date when the grain was last used by a user.\n// private: If true, then knowledge of `_id` does not suffice to open this grain.\n// cachedViewInfo: The JSON-encoded result of `UiView.getViewInfo()`, cached from the most recent\n// time a session to this grain was opened.\n// trashed: If present, the Date when this grain was moved to the trash bin. Thirty days after\n// this date, the grain will be automatically deleted.\n// suspended: If true, the owner of this grain has been suspended. They will soon be deleted,\n// so treat this grain the same as \"trashed\". It is denormalized out of Users for ease\n// of querying.\n// ownerSeenAllActivity: True if the owner has viewed the grain since the last activity event\n// occurred. See also ApiTokenOwner.user.seenAllActivity.\n// size: On-disk size of the grain in bytes.\n//\n// The following fields *might* also exist. These are temporary hacks used to implement e-mail and\n// web publishing functionality without powerbox support; they will be replaced once the powerbox\n// is implemented.\n// publicId: An id used to publicly identify this grain. Used e.g. to route incoming e-mail and\n// web publishing. This field is initialized when first requested by the app.", "Grains.ensureIndexOnServer(\"cachedViewInfo.matchRequests.tags.id\", { sparse: 1 });", "RoleAssignments = new Mongo.Collection(\"roleAssignments\", collectionOptions);\n// *OBSOLETE* Before `user` was a variant of ApiTokenOwner, this collection was used to store edges\n// in the permissions sharing graph. This functionality has been subsumed by the ApiTokens\n// collection.", "Contacts = new Mongo.Collection(\"contacts\", collectionOptions);\n// Edges in the social graph.\n//\n// If Alice has Bob as a contact, then she is allowed to see Bob's profile information and Bob\n// will show up in her user-picker UI for actions like share-by-identity.\n//\n// Contacts are not symmetric. Bob might be one of Alice's contacts even if Alice is not one of\n// Bob's.\n//\n// Each contains:\n// _id: random\n// ownerId: The accountId of the user account who owns this contact.\n// petname: Human-readable label chosen by and only visible to the owner. Uniquely identifies\n// the contact to the owner.\n// created: Date when this contact was created.\n// identityId: The `_id` of the user whose contact info this contains.", "Sessions = new Mongo.Collection(\"sessions\", collectionOptions);\n// UI sessions open to particular grains. A new session is created each time a user opens a grain.\n//\n// Each contains:\n// _id: String generated as a SHA256 hash of the grain ID, the user ID, a salt generated by the\n// client, and the grain's `packageSalt`.\n// grainId: _id of the grain to which this session is connected.\n// hostId: ID part of the hostname from which this grain is being served. I.e. this replaces the\n// '*' in WILDCARD_HOST.\n// tabId: Random value unique to the grain tab in which this session is displayed. Typically\n// every session has a different `tabId`, but embedded sessions (including in the powerbox)\n// have the same `tabId` as the outer session.\n// timestamp: Time of last keep-alive message to this session. Sessions time out after some\n// period.\n// userId: Account ID of the user who owns this session.\n// identityId: Identity ID of the user who owns this session.\n// hashedToken: If the session is owned by an anonymous user, the _id of the entry in ApiTokens\n// that was used to open it. Note that for old-style sharing (i.e. when !grain.private),\n// anonymous users can get access without an API token and so neither userId nor hashedToken\n// are present.\n// powerboxView: Information about a server-initiated powerbox interaction taking place in this\n// session. When the client sees a `powerboxView` appear on the session, it opens the\n// powerbox popup according to the contents. This field is an object containing one of:\n// offer: A capability is being offered to the user by the app. This is an object containing:\n// token: For a non-UiView capability, the API token that can be used to restore this\n// capability.\n// uiView: A UiView capability. This object contains one of:\n// tokenId: The _id of an ApiToken belonging to the current user.\n// token: A full webkey token which can be opened by an anonymous user.\n// fulfill: A capability is being offered which fulfills the active powerbox request. This\n// is an object with members:\n// token: The SturdyRef of the fulfilling capability. This token can only be used in a call\n// to claimRequest() by the requesting\n// grain.\n// descriptor: Packed-base64 PowerboxDescriptor for the capability.\n// powerboxRequest: If present, this session is a powerbox request session. Object containing:\n// descriptors: Array of PowerboxDescriptors representing the request.\n// requestingSession: Session ID of the session initiating the request.\n// viewInfo: The UiView.ViewInfo corresponding to the underlying UiSession. This isn't populated\n// until newSession is called on the UiView.\n// permissions: The permissions for the current identity on this UiView. This isn't populated\n// until newSession is called on the UiView.\n// hasLoaded: Marked as true by the proxy when the underlying UiSession has responded to its first\n// request", "SignupKeys = new Mongo.Collection(\"signupKeys\", collectionOptions);\n// Invite keys which may be used by users to get access to Sandstorm.\n//\n// Each contains:\n// _id: random\n// used: Boolean indicating whether this key has already been consumed.\n// note: Text note assigned when creating key, to keep track of e.g. whom the key was for.\n// email: If this key was sent as an email invite, the email address to which it was sent.", "ActivityStats = new Mongo.Collection(\"activityStats\", collectionOptions);\n// Contains usage statistics taken on a regular interval. Each entry is a data point.\n//\n// Each contains:\n// timestamp: Date when measurements were taken.\n// daily: Contains stats counts pertaining to the last day before the sample time.\n// weekly: Contains stats counts pertaining to the last seven days before the sample time.\n// monthly: Contains stats counts pertaining to the last thirty days before the timestamp.\n//\n// Each of daily, weekly, and monthly contains:\n// activeUsers: The number of unique users who have used a grain on the server in the time\n// interval. Only counts logged-in users.\n// demoUsers: Demo users.\n// appDemoUsers: Users that came in through \"app demo\".\n// activeGrains: The number of unique grains that have been used in the time interval.\n// apps: An object indexed by app ID recording, for each app:\n// owners: Number of unique owners of this app (counting only grains that still exist).\n// sharedUsers: Number of users who have accessed other people's grains of this app (counting\n// only grains that still exist).\n// grains: Number of active grains of this app (that still exist).\n// deleted: Number of non-demo grains of this app that were deleted.\n// demoed: Number of demo grains created and expired.\n// appDemoUsers: Number of app demos initiated with this app.", "DeleteStats = new Mongo.Collection(\"deleteStats\", collectionOptions);\n// Contains records of objects that were deleted, for stat-keeping purposes.\n//\n// Each contains:\n// type: \"grain\" or \"user\" or \"demoGrain\" or \"demoUser\" or \"appDemoUser\"\n// lastActive: Date of the user's or grain's last activity.\n// appId: For type = \"grain\", the app ID of the grain. For type = \"appDemoUser\", the app ID they\n// arrived to demo. For others, undefined.\n// experiments: The experiments the user (or owner of the grain) was in. See user.experiments.", "FileTokens = new Mongo.Collection(\"fileTokens\", collectionOptions);\n// Tokens corresponding to backup files that are currently stored on the server. A user receives\n// a token when they create a backup file (either by uploading it, or by backing up one of their\n// grains) and may use the token to read the file (either to download it, or to restore a new\n// grain from it).\n//\n// Each contains:\n// _id: The unguessable token string.\n// name: Suggested filename.\n// timestamp: File creation time. Used to figure out when the token and file should be wiped.", "ApiTokens = new Mongo.Collection(\"apiTokens\", collectionOptions);\n// Access tokens for APIs exported by apps.\n//\n// Originally API tokens were only used by external users through the HTTP API endpoint. However,\n// now they are also used to implement SturdyRefs, not just held by external users, but also when\n// an app holds a SturdyRef to another app within the same server. See the various `save()`,\n// `restore()`, and `drop()` methods in `grain.capnp` (on `SandstormApi`, `AppPersistent`, and\n// `MainView`) -- the fields of type `Data` are API tokens.\n//\n// Each contains:\n// _id: A SHA-256 hash of the token, base64-encoded.\n// grainId: The grain servicing this API. (Not present if the API isn't serviced by a grain.)\n// identityId: For UiView capabilities, this is the identity for which the view is attenuated.\n// That is, the UiView's newSession() method will intersect the requested permissions\n// with this identity's permissions before forwarding on to the underlying app. If\n// `identityId` is not present, then no identity attenuation is applied, i.e. this is\n// a raw UiView as implemented by the app. (The `roleAssignment` field, below, may\n// still apply. For non-UiView capabilities, `identityId` is never present. Note that\n// this is NOT the identity against which the `requiredPermissions` parameter of\n// `SandstormApi.restore()` is checked; that would be `owner.grain.introducerIdentity`.\n// accountId: For tokens where `identityId` is set, the `_id` (in the Users table) of the account\n// that created the token.\n// roleAssignment: If this API token represents a UiView, this field contains a JSON-encoded\n// Grain.ViewSharingLink.RoleAssignment representing the permissions it carries. These\n// permissions will be intersected with those held by `identityId` when the view is\n// opened.\n// forSharing: If true, requests sent to the HTTP API endpoint with this token will be treated as\n// anonymous rather than as directly associated with `identityId`. This has no effect\n// on the permissions granted.\n// objectId: If present, this token represents an arbitrary Cap'n Proto capability exported by\n// the app or its supervisor (whereas without this it strictly represents UiView).\n// sturdyRef is the JSON-encoded SupervisorObjectId (defined in `supervisor.capnp`).\n// Note that if the SupervisorObjectId contains an AppObjectId, that field is\n// treated as type AnyPointer, and so encoded as a raw Cap'n Proto message.\n// frontendRef: If present, this token actually refers to an object implemented by the front-end,\n// not a particular grain. (`grainId` and `identityId` are not set.) This is an object\n// containing exactly one of the following fields:\n// notificationHandle: A `Handle` for an ongoing notification, as returned by\n// `NotificationTarget.addOngoing`. The value is an `_id` from the\n// `Notifications` collection.\n// ipNetwork: An IpNetwork capability that is implemented by the frontend. Eventually, this\n// will be moved out of the frontend and into the backend, but we'll migrate the\n// database when that happens. This field contains the boolean true to signify that\n// it has been set.\n// ipInterface: Ditto IpNetwork, except it's an IpInterface.\n// emailVerifier: An EmailVerifier capability that is implemented by the frontend. The\n// value is an object containing the fields `id` and `services`. `id` is the\n// value returned by `EmailVerifier.getId()` and is used as part of a\n// powerbox query for matching verified emails. `services` is a\n// list of names of identity providers that are trusted to verify addresses.\n// If `services` is omitted or falsy, all configured identity providers are\n// trusted. Note that a malicious user could specify invalid names in the\n// list; they should be ignored.\n// verifiedEmail: An VerifiedEmail capability that is implemented by the frontend.\n// An object containing `verifierId`, `tabId`, and `address`.\n// identity: An Identity capability. The field is the identity ID.\n// http: An ApiSession capability pointing to an external HTTP service. Object containing:\n// url: Base URL of the external service.\n// auth: Authentication mechanism. Object containing one of:\n// none: Value \"null\". Indicates no authorization.\n// bearer: A bearer token to pass in the `Authorization: Bearer` header on all\n// requests. Encrypted with nonce 0.\n// basic: A `{username, password}` object. The password is encrypted with nonce 0.\n// Before encryption, the password is padded to 32 bytes by appending NUL bytes,\n// in order to mask the length of small passwords.\n// refresh: An OAuth refresh token, which can be exchanged for an access token.\n// Encrypted with nonce 0.\n// TODO(security): How do we protect URLs that directly embed their secret? We don't\n// want to encrypt the full URL since this would make it hard to show a\n// meaningful audit UI, but maybe we could figure out a way to extract the key\n// part and encrypt it separately?\n// parentToken: If present, then this token represents exactly the capability represented by\n// the ApiToken with _id = parentToken, except possibly (if it is a UiView) attenuated\n// by `roleAssignment` (if present). To facilitate permissions computations, if the\n// capability is a UiView, then `grainId` is set to the backing grain, `identityId`\n// is set to the identity that shared the view, and `accountId` is set to the account\n// that shared the view. Neither `objectId` nor `frontendRef` is present when\n// `parentToken` is present.\n// parentTokenKey: The actual parent token -- whereas `parentToken` is only the parent token ID\n// (hash). `parentTokenFull` is encrypted with nonce 0 (see below). This is needed\n// in particular when the parent contains encrypted fields, since those would need to\n// be decrypted using this key. If the parent contains no encrypted fields then\n// `parentTokenKey` may be omitted from the child.\n// petname: Human-readable label for this access token, useful for identifying tokens for\n// revocation. This should be displayed when visualizing incoming capabilities to\n// the grain identified by `grainId`.\n// created: Date when this token was created.\n// revoked: If true, then this sturdyref has been revoked and can no longer be restored. It may\n// become un-revoked in the future.\n// trashed: If present, the Date when this token was moved to the trash bin. Thirty days after\n// this date, the token will be automatically deleted.\n// suspended: If true, the owner of this token has been suspended. They will soon be deleted,\n// so treat this token the same as \"trashed\". It is denormalized out of Users for\n// ease of querying.\n// expires: Optional expiration Date. If undefined, the token does not expire.\n// lastUsed: Optional Date when this token was last used.\n// owner: A `ApiTokenOwner` (defined in `supervisor.capnp`, stored as a JSON object)\n// as passed to the `save()` call that created this token. If not present, treat\n// as `webkey` (the default for `ApiTokenOwner`).\n// expiresIfUnused:\n// Optional Date after which the token, if it has not been used yet, expires.\n// This field should be cleared on a token's first use.\n// requirements: List of conditions which must hold for this token to be considered valid.\n// Semantically, this list specifies the powers which were *used* to originally\n// create the token. If any condition in the list becomes untrue, then the token must\n// be considered revoked, and all live refs and sturdy refs obtained transitively\n// through it must also become revoked. Each item is the JSON serialization of the\n// `MembraneRequirement` structure defined in `supervisor.capnp`.\n// hasApiHost: If true, there is an entry in ApiHosts for this token, which will need to be\n// cleaned up when the token is.\n//\n// It is important to note that a token's owner and provider are independent from each other. To\n// illustrate, here is an approximate definition of ApiToken in pseudo Cap'n Proto schema language:\n//\n// struct ApiToken {\n// owner :ApiTokenOwner;\n// provider :union {\n// grain :group {\n// grainId :Text;\n// union {\n// uiView :group {\n// identityId :Text;\n// roleAssignment :RoleAssignment;\n// forSharing :Bool;\n// }\n// objectId :SupervisorObjectId;\n// }\n// }\n// frontendRef :union {\n// notificationHandle :Text;\n// ipNetwork :Bool;\n// ipInterface :Bool;\n// emailVerifier :group {\n// id :Text;\n// services :List(String);\n// }\n// verifiedEmail :group {\n// verifierId :Text;\n// tabId :Text;\n// address :Text;\n// }\n// identity :Text;\n// http :group {\n// url :Text;\n// auth :union {\n// none :Void;\n// bearer :Text;\n// basic :group { username :Text; password :Text; }\n// refresh :Text;\n// }\n// }\n// }\n// child :group {\n// parentToken :Text;\n// union {\n// uiView :group {\n// grainId :Text;\n// identityId :Text;\n// roleAssignment :RoleAssignment = (allAccess = ());\n// }\n// other :Void;\n// }\n// }\n// }\n// requirements: List(Supervisor.MembraneRequirement);\n// ...\n// }\n//\n// ENCRYPTION\n//\n// We want to make sure that someone who obtains a copy of the database cannot use it to gain live\n// credentials.\n//\n// The actual token corresponding to an ApiToken entry is not stored in the entry itself. Instead,\n// the ApiToken's `_id` is constructed as a SHA256 hash of the actual token. To use an ApiToken\n// in the live system, you must present the original token.\n//\n// Additionally, some ApiToken entries contain tokens to third-party services, e.g. OAuth tokens\n// or even passwords. Such tokens are encrypted, using the ApiToken entry's own full token (which,\n// again, is not stored in the database) as the encryption key.\n//\n// When such encryption is applied, the cipher used is ChaCha20. All API tokens are 256-bit base64\n// strings, hence can be used directly as the key. No MAC is applied, because this scheme is not\n// intended to protect against attackers who have write access to the database -- such an attacker\n// could almost certainly do more damage by modifying the non-encrypted fields anyway. (Put another\n// way, if we wanted to MAC something, we'd need to MAC the entire ApiToken structure, not just\n// the encrypted key. But we don't have a way to do that at present.)\n//\n// ChaCha20 requires a nonce. Luckily, all of the fields we wish to encrypt are immutable, so we\n// don't have to worry about tracking nonces over time -- we can just assign a static nonce to each\n// field. Moreover, many (currently, all) of these fields are mutually exclusive, so can even share\n// nonces. Currently, nonces map to fields as follows:\n//\n// nonce 0:\n// parentTokenKey\n// frontendRef.http.auth.basic.password\n// frontendRef.http.auth.bearer\n// frontendRef.http.auth.refresh", "ApiTokens.ensureIndexOnServer(\"grainId\", { sparse: 1 });\nApiTokens.ensureIndexOnServer(\"owner.user.identityId\", { sparse: 1 });\nApiTokens.ensureIndexOnServer(\"frontendRef.emailVerifier.id\", { sparse: 1 });", "ApiHosts = new Mongo.Collection(\"apiHosts\", collectionOptions);\n// Allows defining some limited static behavior for an API host when accessed unauthenticated. This\n// mainly exists to allow backwards-compatibility with client applications that expect to be able\n// to probe an API host without authentication to determine capabilities such as DAV protocols\n// supported, before authenticating to perform real requests. An app can specify these properties\n// when creating an offerTemplate.\n//\n// Each contains:\n// _id: apiHostIdHashForToken() of the corresponding API token.\n// hash2: hash(hash(token)), aka hash(ApiToken._id). Used to allow ApiHosts to be cleaned\n// up when ApiTokens are deleted.\n// options: Specifies how to respond to unauthenticated OPTIONS requests on this host.\n// This is an object containing fields:\n// dav: List of strings specifying DAV header `compliance-class`es, e.g. \"1\" or\n// \"calendar-access\". https://tools.ietf.org/html/rfc4918#section-10.1\n// resources: Object mapping URL paths (including initial '/') to static HTTP responses to\n// give when those paths are accessed unauthenticated. Due to Mongo disliking '.'\n// and '$' in keys, these characters must be escaped as '\\uFF0E' and '\\uFF04'\n// (see SandstormDb.escapeMongoKey). Each value in this map is an object with\n// fields:\n// type: Content-Type.\n// language: Content-Language.\n// encoding: Content-Encoding.\n// body: Entity-body as a string or buffer.", "Notifications = new Mongo.Collection(\"notifications\", collectionOptions);\n// Notifications for a user.\n//\n// Each contains:\n// _id: random\n// grainId: The grain originating this notification, if any.\n// userId: Account ID of the user receiving the notification.\n// text: The JSON-ified LocalizedText to display in the notification.\n// isUnread: Boolean indicating if this notification is unread.\n// timestamp: Date when this notification was last updated\n// eventType: If this notification is due to an activity event, this is the numeric index\n// of the event type on the grain's ViewInfo.\n// count: The number of times this exact event has repeated. Identical events are\n// aggregated by incrementing the count.\n// initiatingIdentity: Identity ID of the user who initiated this notification.\n// initiatorAnonymous: True if the initiator is an anonymous user. If neither this nor\n// initiatingIdentity is present, the notification is not from a user.\n// path: Path inside the grain to which the user should be directed if they click on\n// the notification.\n// ongoing: If present, this is an ongoing notification, and this field contains an\n// ApiToken referencing the `OngoingNotification` capability.\n// admin: If present, this is a notification intended for an admin.\n// action: If present, this is a (string) link that the notification should direct the\n// admin to.\n// type: The type of notification -- currently can only be \"reportStats\".\n// appUpdates: If present, this is an app update notification. It is an object with the appIds\n// as keys.\n// $appId: The appId that has an outstanding update.\n// packageId: The packageId that it will update to.\n// name: The name of the app. (appTitle from package.manifest)\n// version: The app's version number. (appVersion from package.manifest)\n// marketingVersion: String marketing version of this app. (appMarketingVersion from package.manifest)\n// referral: If this boolean field is true, then treat this notification as a referral\n// notification. This causes text to be ignored, since we need custom logic.\n// mailingListBonus: Like `referral`, but notify the user about the mailing list bonus. This is\n// a one-time notification only to Oasis users who existed when the bonus program\n// was implemented.", "ActivitySubscriptions = new Mongo.Collection(\"activitySubscriptions\", collectionOptions);\n// Activity events to which a user is subscribed.\n//\n// Each contains:\n// _id: random\n// identityId: Who is subscribed.\n// grainId: Grain to which subscription applies.\n// threadPath: If present, the subscription is on a specific thread. Otherwise, it is on the\n// whole grain.\n// mute: If true, this is an anti-subscription -- matching events should NOT notify.\n// This allows is useful to express:\n// - A user wants to subscribe to a grain but mute a specific thread.\n// - The owner of a grain does not want notifications (normally, they are\n// implicitly subscribed).\n// - A user no longer wishes to be implicitly subscribed to threads in a grain on\n// which they comment, so they mute the grain.", "ActivitySubscriptions.ensureIndexOnServer(\"identityId\");\nActivitySubscriptions.ensureIndexOnServer({ \"grainId\": 1, \"threadPath\": 1 });", "StatsTokens = new Mongo.Collection(\"statsTokens\", collectionOptions);\n// Access tokens for the Stats collection\n//\n// These tokens are used for accessing the ActivityStats collection remotely\n// (ie. from a dashboard webapp)\n//\n// Each contains:\n// _id: The token. At least 128 bits entropy (Random.id(22)).", "Misc = new Mongo.Collection(\"misc\", collectionOptions);\n// Miscellaneous configuration and other settings\n//\n// This table is currently only used for persisting BASE_URL from one session to the next,\n// but in general any miscellaneous settings should go in here\n//\n// Each contains:\n// _id: The name of the setting. eg. \"BASE_URL\"\n// value: The value of the setting.", "Settings = new Mongo.Collection(\"settings\", collectionOptions);\n// Settings for this Sandstorm instance go here. They are configured through the adminSettings\n// route. This collection differs from misc in that any admin user can update it through the admin\n// interface.\n//\n// Each contains:\n// _id: The name of the setting. eg. \"smtpConfig\"\n// value: The value of the setting.\n// automaticallyReset: Sometimes the server needs to automatically reset a setting. When it does\n// so, it will also write an object to this field indicating why the reset was\n// needed. That object can have the following variants:\n// baseUrlChangedFrom: The reset was due to BASE_URL changing. This field contains a string\n// with the old BASE_URL.\n// preinstalledApps: A list of objects:\n// appId: The Packages.appId of the app to install\n// status: packageId\n// packageId: The Packages._id of the app to install\n//\n// potentially other fields that are unique to the setting", "Migrations = new Mongo.Collection(\"migrations\", collectionOptions);\n// This table tracks which migrations we have applied to this instance.\n// It contains a single entry:\n// _id: \"migrations_applied\"\n// value: The number of migrations this instance has successfully completed.", "StaticAssets = new Mongo.Collection(\"staticAssets\", collectionOptions);\n// Collection of static assets served up from the Sandstorm server's \"static\" host. We only\n// support relatively small assets: under 1MB each.\n//\n// Each contains:\n// _id: Random ID; will be used in the URL.\n// hash: A base64-encoded SHA-256 hash of the data, used to de-dupe.\n// mimeType: MIME type of the asset, suitable for Content-Type header.\n// encoding: Either \"gzip\" or not present, suitable for Content-Encoding header.\n// content: The asset content (byte buffer).\n// refcount: Number of places where this asset's ID appears in the database. Since Mongo doesn't\n// have transactions, this needs to bias towards over-counting; a backup GC could be used\n// to catch leaked assets, although it's probably not a big deal in practice.", "AssetUploadTokens = new Mongo.Collection(\"assetUploadTokens\", collectionOptions);\n// Collection of tokens representing a single-use permission to upload an asset, such as a new\n// profile picture.\n//\n// Each contains:\n// _id: Random ID.\n// purpose: Contains one of the following, indicating how the asset is to be used:\n// profilePicture: Indicates that the upload is a new profile picture. Contains fields:\n// userId: Account ID of user whose picture shall be replaced.\n// identityId: Which of the user's identities shall be updated.\n// expires: Time when this token will go away if unused.", "Plans = new Mongo.Collection(\"plans\", collectionOptions);\n// Subscription plans, which determine quota.\n//\n// Each contains:\n// _id: Plan ID, usually a short string like \"free\", \"standard\", \"large\", \"mega\", ...\n// storage: Number of bytes this user is allowed to store.\n// compute: Number of kilobyte-RAM-seconds this user is allowed to consume.\n// computeLabel: Label to display to the user describing this plan's compute units.\n// grains: Total number of grains this user can create (often `Infinity`).\n// price: Price per month in US cents.\n// hidden: If true, a user cannot switch to this plan, but some users may be on it and are\n// allowed to switch away.\n// title: Title from display purposes. If missing, default to capitalizing _id.", "AppIndex = new Mongo.Collection(\"appIndex\", collectionOptions);\n// A mirror of the data from the App Market index\n//\n// Each contains:\n// _id: the appId of the app\n// The rest of the fields are defined in src/sandstorm/app-index/app-index.capnp:AppIndexForMarket", "KeybaseProfiles = new Mongo.Collection(\"keybaseProfiles\", collectionOptions);\n// Cache of Keybase profile information. The profile for a user is re-fetched every time a package\n// by that user is installed, as well as if the keybase profile is requested and not already\n// present for some reason.\n//\n// Each contains:\n// _id: PGP key fingerprint (SHA-1, hex, all-caps)\n// displayName: Display name from Keybase. (NOT VERIFIED AT ALL.)\n// handle: Keybase handle.\n// proofs: The \"proofs_summary.all\" array from the Keybase lookup. See the non-existent Keybase\n// docs for details. We also add a boolean \"status\" field to each proof indicating whether\n// we have directly verified the proof ourselves. Its values may be \"unverified\" (Keybase\n// returned this but we haven't checked it directly), \"verified\" (we verified the proof and it\n// is valid), \"invalid\" (we checked the proof and it was definitely bogus), or \"checking\" (the\n// server is currently actively checking this proof). Note that if a check fails due to network\n// errors, the status goes back to \"unverified\".\n//\n// WARNING: Currently verification is NOT IMPLEMENTED, so all proofs will be \"unverified\"\n// for now and we just trust Keybase.", "FeatureKey = new Mongo.Collection(\"featureKey\", collectionOptions);\n// OBSOLETE: This was used to implement the Sandstorm for Work paywall, which has been removed.\n// Collection object still defined because it could have old data in it, for servers that used\n// to have a feature key.", "SetupSession = new Mongo.Collection(\"setupSession\", collectionOptions);\n// Responsible for storing information about setup sessions. Contains a single document with three\n// keys:\n//\n// _id: \"current-session\"\n// creationDate: Date object indicating when this session was created.\n// hashedSessionId: the sha256 of the secret session id that was returned to the client", "const DesktopNotifications = new Mongo.Collection(\"desktopNotifications\", collectionOptions);\n// Responsible for very short-lived queueing of desktop notification information.\n// Entries are removed when they are ~30 seconds old. This collection is a bit\n// odd in that it is intended primarily for edge-triggered communications, but\n// Meteor's collections aren't really designed to support that organization.\n// Fields for each :\n//\n// _id: String. Used as the tag to coordinate notification merging between browser tabs.\n// creationDate: Date object. indicating when this notification was posted.\n// userId: String. Account id to which this notification was published.\n// notificationId: String. ID of the matching event in the Notifications table to dismiss if this\n// notification is activated.\n// appActivity: Object with fields:\n// user: Optional Object. Not present if this notification wasn't generated by a user. If\n// present, it will have one of the following shapes:\n// { anonymous: true } if this notification was generated by an anonymous user. Otherwise:\n// {\n// identityId: String The user's identity ID.\n// name: String The user's display name.\n// avatarUrl: String The URL for the user's profile picture.\n// },\n// grainId: String, Which grain this action took place on\n// path: String, The path of the notification.\n// body: Util.LocalizedText, The main body of the activity event.\n// actionText: Util.LocalizedText, What action the user took, e.g.\n// { defaultText: \"added a comment\" }", "const StandaloneDomains = new Mongo.Collection(\"standaloneDomains\", collectionOptions);\n// A standalone domain that points to a single share link. These domains act a little different\n// than a normal shared Sandstorm grain. They completely drop any Sandstorm topbar/sidebar, and at\n// first glance look completely like a non-Sandstorm hosted webserver. The apps instead act in\n// concert with Sandstorm through the postMessage API, which allows it to do things like prompt for\n// login.\n// Fields for each :\n//\n// _id: String. The domain name to use.\n// token: String. _id of a sharing token (it must be a webkey).", "if (Meteor.isServer) {\n Meteor.publish(\"credentials\", function () {\n // Data needed for isSignedUp() and isAdmin() to work.", " if (this.userId) {\n const db = this.connection.sandstormDb;\n return [\n Meteor.users.find({ _id: this.userId },\n { fields: { signupKey: 1, isAdmin: 1, expires: 1, storageUsage: 1,\n plan: 1, planBonus: 1, hasCompletedSignup: 1, experiments: 1,\n referredIdentityIds: 1, cachedStorageQuota: 1, suspended: 1, }, }),\n db.collections.plans.find(),\n ];\n } else {\n return [];\n }\n });\n}", "const countReferrals = function (user) {\n const referredIdentityIds = user.referredIdentityIds;\n return (referredIdentityIds && referredIdentityIds.length || 0);\n};", "const calculateReferralBonus = function (user) {\n // This function returns an object of the form:\n //\n // - {grains: 0, storage: 0}\n //\n // which are extra resources this account gets as part of participating in the referral\n // program. (Storage is measured in bytes, as usual for plans.)", " // TODO(cleanup): Consider moving referral bonus logic into Oasis payments module (since it's\n // payments-specific) and aggregating into `planBonus`.", " // Authorization note: Only call this if accountId is the current user!\n const isPaid = (user.plan && user.plan !== \"free\");", " successfulReferralsCount = countReferrals(user);\n if (isPaid) {\n const maxPaidStorageBonus = 30 * 1e9;\n return { grains: 0,\n storage: Math.min(\n successfulReferralsCount * 2 * 1e9,\n maxPaidStorageBonus), };\n } else {\n const maxFreeStorageBonus = 2 * 1e9;\n const bonus = {\n storage: Math.min(\n successfulReferralsCount * 50 * 1e6,\n maxFreeStorageBonus),\n };\n if (successfulReferralsCount > 0) {\n bonus.grains = Infinity;\n } else {\n bonus.grains = 0;\n }", " return bonus;\n }\n};", "isAdmin = function () {\n // Returns true if the user is the administrator.", " const user = Meteor.user();\n if (user && user.isAdmin) {\n return true;\n } else {\n return false;\n }\n};", "isAdminById = function (id) {\n // Returns true if the user's id is the administrator.", " const user = Meteor.users.findOne({ _id: id }, { fields: { isAdmin: 1 } });\n if (user && user.isAdmin) {\n return true;\n } else {\n return false;\n }\n};", "findAdminUserForToken = function (token) {\n if (!token.requirements) {\n return;\n }", " const requirements = token.requirements.filter(function (requirement) {\n return \"userIsAdmin\" in requirement;\n });", " if (requirements.length > 1) {\n return;\n }", " if (requirements.length === 0) {\n return;\n }", " return requirements[0].userIsAdmin;\n};", "const wildcardHost = Meteor.settings.public.wildcardHost.toLowerCase().split(\"*\");", "if (wildcardHost.length != 2) {\n throw new Error(\"Wildcard host must contain exactly one asterisk.\");\n}", "matchWildcardHost = function (host) {\n // See if the hostname is a member of our wildcard. If so, extract the ID.", " // We remove everything after the first \":\" character so that our\n // comparison logic ignores port numbers.\n const prefix = wildcardHost[0];\n const suffix = wildcardHost[1].split(\":\")[0];\n const hostSansPort = host.split(\":\")[0];", " if (hostSansPort.lastIndexOf(prefix, 0) >= 0 &&\n hostSansPort.indexOf(suffix, -suffix.length) >= 0 &&\n hostSansPort.length >= prefix.length + suffix.length) {\n const id = hostSansPort.slice(prefix.length, -suffix.length);\n if (id.match(/^[-a-z0-9]*$/)) {\n return id;\n }\n }", " return null;\n};", "makeWildcardHost = function (id) {\n return wildcardHost[0] + id + wildcardHost[1];\n};", "const isApiHostId = function (hostId) {\n if (hostId) {\n const split = hostId.split(\"-\");\n if (split[0] === \"api\") return split[1] || \"*\";\n }", " return false;\n};", "const isTokenSpecificHostId = function (hostId) {\n return hostId.lastIndexOf(\"api-\", 0) === 0;\n};", "let apiHostIdHashForToken;\nif (Meteor.isServer) {\n const Crypto = Npm.require(\"crypto\");\n apiHostIdHashForToken = function (token) {\n // Given an API token, compute the host ID that must be used when requesting this token.", " // We add a leading 'x' to the hash so that knowing the hostname alone is not sufficient to\n // find the corresponding API token in the ApiTokens table (whose _id values are also hashes\n // of tokens). This doesn't technically add any security, but helps prove that we don't have\n // any bugs which would allow someone who knows only the hostname to access the app API.\n return Crypto.createHash(\"sha256\").update(\"x\" + token).digest(\"hex\").slice(0, 32);\n };\n} else {\n apiHostIdHashForToken = function (token) {\n // Given an API token, compute the host ID that must be used when requesting this token.", " // We add a leading 'x' to the hash so that knowing the hostname alone is not sufficient to\n // find the corresponding API token in the ApiTokens table (whose _id values are also hashes\n // of tokens). This doesn't technically add any security, but helps prove that we don't have\n // any bugs which would allow someone who knows only the hostname to access the app API.\n return SHA256(\"x\" + token).slice(0, 32);\n };\n}", "const apiHostIdForToken = function (token) {\n return \"api-\" + apiHostIdHashForToken(token);\n};", "const makeApiHost = function (token) {\n return makeWildcardHost(apiHostIdForToken(token));\n};", "if (Meteor.isServer) {\n const Url = Npm.require(\"url\");\n getWildcardOrigin = function () {\n // The wildcard URL can be something like \"foo-*-bar.example.com\", but sometimes when we're\n // trying to specify a pattern matching hostnames (say, a Content-Security-Policy directive),\n // an astrisk is only allowed as the first character and must be followed by a period. So we need\n // \"*.example.com\" instead -- which matches more than we actually want, but is the best we can\n // really do. We also add the protocol to the front (again, that's what CSP wants).", " // TODO(cleanup): `protocol` is computed in other files, like proxy.js. Put it somewhere common.\n const protocol = Url.parse(process.env.ROOT_URL).protocol;", " const dotPos = wildcardHost[1].indexOf(\".\");\n if (dotPos < 0) {\n return protocol + \"//*\";\n } else {\n return protocol + \"//*\" + wildcardHost[1].slice(dotPos);\n }\n };\n}", "SandstormDb = function (quotaManager) {\n // quotaManager is an object with the following method:\n // updateUserQuota: It is provided two arguments\n // db: This SandstormDb object\n // user: A collections.users account object\n // and returns a quota object:\n // storage: A number (can be Infinity)\n // compute: A number (can be Infinity)\n // grains: A number (can be Infinity)", " this.quotaManager = quotaManager;\n this.collections = {\n // Direct access to underlying collections. DEPRECATED, but better than accessing the top-level\n // collection globals directly.\n //\n // TODO(cleanup): Over time, we will provide methods covering each supported query and remove\n // direct access to the collections.\n users: Meteor.users,", " packages: Packages,\n devPackages: DevPackages,\n userActions: UserActions,\n grains: Grains,\n roleAssignments: RoleAssignments, // Deprecated, only used by the migration that eliminated it.\n contacts: Contacts,\n sessions: Sessions,\n signupKeys: SignupKeys,\n activityStats: ActivityStats,\n deleteStats: DeleteStats,\n fileTokens: FileTokens,\n apiTokens: ApiTokens,\n apiHosts: ApiHosts,\n notifications: Notifications,\n activitySubscriptions: ActivitySubscriptions,\n statsTokens: StatsTokens,\n misc: Misc,\n settings: Settings,\n migrations: Migrations,\n staticAssets: StaticAssets,\n assetUploadTokens: AssetUploadTokens,\n plans: Plans,\n appIndex: AppIndex,\n keybaseProfiles: KeybaseProfiles,\n setupSession: SetupSession,\n desktopNotifications: DesktopNotifications,\n standaloneDomains: StandaloneDomains,\n };\n};", "// TODO(cleanup): These methods should not be defined freestanding and should use collection\n// objects created in SandstormDb's constructor rather than globals.", "_.extend(SandstormDb.prototype, {\n isAdmin: isAdmin,\n isAdminById: isAdminById,\n findAdminUserForToken: findAdminUserForToken,\n matchWildcardHost: matchWildcardHost,\n makeWildcardHost: makeWildcardHost,\n isApiHostId: isApiHostId,\n isTokenSpecificHostId: isTokenSpecificHostId,\n apiHostIdHashForToken: apiHostIdHashForToken,\n apiHostIdForToken: apiHostIdForToken,\n makeApiHost: makeApiHost,\n allowDevAccounts() {\n const setting = this.collections.settings.findOne({ _id: \"devAccounts\" });\n if (setting) {\n return setting.value;\n } else {\n return Meteor.settings && Meteor.settings.public &&\n Meteor.settings.public.allowDevAccounts;\n }\n },", " roleAssignmentPattern: {\n none: Match.Optional(null),\n allAccess: Match.Optional(null),\n roleId: Match.Optional(Match.Integer),\n addPermissions: Match.Optional([Boolean]),\n removePermissions: Match.Optional([Boolean]),\n },", " isDemoUser() {\n // Returns true if this is a demo user.", " const user = Meteor.user();\n if (user && user.expires) {\n return true;\n } else {\n return false;\n }\n },", " isSignedUp() {\n const user = Meteor.user();\n return this.isAccountSignedUp(user);\n },", " isAccountSignedUp(user) {\n // Returns true if the user has presented an invite key.", " if (!user) return false; // not signed in", " if (!user.loginIdentities) return false; // not an account", " if (user.expires) return false; // demo user.", " if (Meteor.settings.public.allowUninvited) return true; // all accounts qualify", " if (user.signupKey) return true; // user is invited", " if (this.isUserInOrganization(user)) return true;", " return false;\n },", " isSignedUpOrDemo() {\n const user = Meteor.user();\n return this.isAccountSignedUpOrDemo(user);\n },", " isAccountSignedUpOrDemo(user) {\n if (!user) return false; // not signed in", " if (!user.loginIdentities) return false; // not an account", " if (user.expires) return true; // demo user.", " if (Meteor.settings.public.allowUninvited) return true; // all accounts qualify", " if (user.signupKey) return true; // user is invited", " if (this.isUserInOrganization(user)) return true;", " return false;\n },", " isIdentityInOrganization(identity) {\n if (!identity || !identity.services) {\n return false;\n }", " const orgMembership = this.getOrganizationMembership();\n const googleEnabled = orgMembership && orgMembership.google && orgMembership.google.enabled;\n const googleDomain = orgMembership && orgMembership.google && orgMembership.google.domain;\n const emailEnabled = orgMembership && orgMembership.emailToken && orgMembership.emailToken.enabled;\n const emailDomain = orgMembership && orgMembership.emailToken && orgMembership.emailToken.domain;\n const ldapEnabled = orgMembership && orgMembership.ldap && orgMembership.ldap.enabled;\n const samlEnabled = orgMembership && orgMembership.saml && orgMembership.saml.enabled;\n if (emailEnabled && emailDomain && identity.services.email) {\n const domainSuffixes = emailDomain.split(/\\s*,\\s*/);\n for (let i = 0; i < domainSuffixes.length; i++) {\n const suffix = domainSuffixes[i];\n const domain = identity.services.email.email.toLowerCase().split(\"@\").pop();\n if (suffix.startsWith(\"*.\")) {\n if (domain.endsWith(suffix.substr(1))) {\n return true;\n }\n } else if (domain === suffix) {\n return true;\n }\n }\n } else if (ldapEnabled && identity.services.ldap) {\n return true;\n } else if (samlEnabled && identity.services.saml) {\n return true;\n } else if (googleEnabled && googleDomain && identity.services.google && identity.services.google.hd) {\n if (identity.services.google.hd.toLowerCase() === googleDomain) {\n return true;\n }\n }", " return false;\n },", " isUserInOrganization(user) {\n for (let i = 0; i < user.loginIdentities.length; i++) {\n let identity = Meteor.users.findOne({ _id: user.loginIdentities[i].id });\n if (this.isIdentityInOrganization(identity)) {\n return true;\n }\n }", " return false;\n },\n});", "if (Meteor.isServer) {\n SandstormDb.prototype.getWildcardOrigin = getWildcardOrigin;", " const Crypto = Npm.require(\"crypto\");\n SandstormDb.prototype.removeApiTokens = function (query) {\n // Remove all API tokens matching the query, making sure to clean up ApiHosts as well.", " this.collections.apiTokens.find(query).forEach((token) => {\n // Clean up ApiHosts for webkey tokens.\n if (token.hasApiHost) {\n const hash2 = Crypto.createHash(\"sha256\").update(token._id).digest(\"base64\");\n this.collections.apiHosts.remove({ hash2: hash2 });\n }", " // TODO(soon): Drop remote OAuth tokens for frontendRef.http. Unfortunately the way to do\n // this is different for every service. :( Also we may need to clarify with the \"bearer\"\n // type whether or not the token is \"owned\" by us...\n });", " this.collections.apiTokens.remove(query);\n };\n}", "// TODO(someday): clean this up. Logic for building static asset urls on client and server\n// appears all over the codebase.\nlet httpProtocol;\nif (Meteor.isServer) {\n const Url = Npm.require(\"url\");\n httpProtocol = Url.parse(process.env.ROOT_URL).protocol;\n} else {\n httpProtocol = window.location.protocol;\n}", "// =======================================================================================\n// Below this point are newly-written or refactored functions.", "_.extend(SandstormDb.prototype, {\n getUser(userId) {\n check(userId, Match.OneOf(String, undefined, null));\n if (userId) {\n return Meteor.users.findOne(userId);\n }\n },", " getIdentity(identityId) {\n check(identityId, String);\n const identity = Meteor.users.findOne({ _id: identityId });\n if (identity) {\n SandstormDb.fillInProfileDefaults(identity);\n SandstormDb.fillInIntrinsicName(identity);\n SandstormDb.fillInPictureUrl(identity);\n return identity;\n }\n },", " userHasIdentity(userId, identityId) {\n check(userId, String);\n check(identityId, String);", " if (userId === identityId) return true;", " const user = Meteor.users.findOne(userId);\n return SandstormDb.getUserIdentityIds(user).indexOf(identityId) != -1;\n },", " userGrains(userId, options) {\n check(userId, Match.OneOf(String, undefined, null));\n check(options, Match.OneOf(undefined, null,\n { includeTrashOnly: Match.Optional(Boolean), includeTrash: Match.Optional(Boolean), }));", " const query = { userId: userId };\n if (options && options.includeTrashOnly) {\n query.trashed = { $exists: true };\n } else if (options && options.includeTrash) {\n // Keep query as-is.\n } else {\n query.trashed = { $exists: false };\n }", " return this.collections.grains.find(query);\n },", " currentUserGrains(options) {\n return this.userGrains(Meteor.userId(), options);\n },", " getGrain(grainId) {\n check(grainId, String);\n return this.collections.grains.findOne(grainId);\n },", " userApiTokens(userId, trashed) {\n check(userId, Match.OneOf(String, undefined, null));\n check(trashed, Match.OneOf(Boolean, undefined, null));\n const identityIds = SandstormDb.getUserIdentityIds(this.getUser(userId));\n return this.collections.apiTokens.find({\n \"owner.user.identityId\": { $in: identityIds },\n trashed: { $exists: !!trashed },\n });\n },", " currentUserApiTokens(trashed) {\n return this.userApiTokens(Meteor.userId(), trashed);\n },", " userActions(user) {\n return this.collections.userActions.find({ userId: user });\n },", " currentUserActions() {\n return this.userActions(Meteor.userId());\n },", " iconSrcForPackage(pkg, usage) {\n return Identicon.iconSrcForPackage(pkg, usage, httpProtocol + \"//\" + this.makeWildcardHost(\"static\"));\n },", " getDenormalizedGrainInfo(grainId) {\n const grain = this.getGrain(grainId);\n let pkg = this.collections.packages.findOne(grain.packageId);", " if (!pkg) {\n pkg = this.collections.devPackages.findOne(grain.packageId);\n }", " const appTitle = (pkg && pkg.manifest && pkg.manifest.appTitle) || { defaultText: \"\" };\n const grainInfo = { appTitle: appTitle };", " if (pkg && pkg.manifest && pkg.manifest.metadata && pkg.manifest.metadata.icons) {\n const icons = pkg.manifest.metadata.icons;\n const icon = icons.grain || icons.appGrid;\n if (icon) {\n grainInfo.icon = icon;\n }\n }", " // Only provide an app ID if we have no icon asset to provide and need to offer an identicon.\n if (!grainInfo.icon && pkg) {\n grainInfo.appId = pkg.appId;\n }", " return grainInfo;\n },", " getPlan(id, user) {\n check(id, String);", " // `user`, if provided, is the user observing the plan. This matters only for checking if the\n // user is in an experiment.", " const plan = this.collections.plans.findOne(id);\n if (!plan) {\n throw new Error(\"no such plan: \" + id);\n }", " if (plan._id === \"free\") {\n user = user || Meteor.user();\n if (user && user.experiments &&\n typeof user.experiments.freeGrainLimit === \"number\") {\n plan.grains = user.experiments.freeGrainLimit;\n }\n }", " return plan;\n },", " listPlans(user) {\n user = user || Meteor.user();\n if (user && user.experiments &&\n typeof user.experiments.freeGrainLimit === \"number\") {\n return this.collections.plans.find({}, { sort: { price: 1 } })\n .map(plan => {\n if (plan._id === \"free\") {\n plan.grains = user.experiments.freeGrainLimit;\n }", " return plan;\n });\n } else {\n return this.collections.plans.find({}, { sort: { price: 1 } }).fetch();\n }\n },", " getMyPlan() {\n const user = Meteor.user();\n return user && this.collections.plans.findOne(user.plan || \"free\");\n },", " getMyReferralBonus(user) {\n // This function is called from the server and from the client, similar to getMyPlan().\n //\n // The parameter may be omitted in which case the current user is assumed.", " return calculateReferralBonus(user || Meteor.user());\n },", " getMyUsage(user) {\n user = user || Meteor.user();\n if (user && (Meteor.isServer || user.pseudoUsage)) {\n if (Meteor.isClient) {\n // Filled by pseudo-subscription to \"getMyUsage\". WARNING: The subscription is currently\n // not reactive.\n return user.pseudoUsage;\n } else {\n return {\n grains: this.collections.grains.find({ userId: user._id }).count(),\n storage: user.storageUsage || 0,\n compute: 0, // not tracked yet\n };\n }\n } else {\n return { grains: 0, storage: 0, compute: 0 };\n }\n },", " isUninvitedFreeUser() {\n if (!Meteor.settings.public.allowUninvited) return false;", " const user = Meteor.user();\n return user && !user.expires && (!user.plan || user.plan === \"free\");\n },", " getSetting(name) {\n const setting = this.collections.settings.findOne(name);\n return setting && setting.value;\n },", " getSettingWithFallback(name, fallbackValue) {\n const value = this.getSetting(name);\n if (value === undefined) {\n return fallbackValue;\n }", " return value;\n },", " addUserActions(userId, packageId, simulation) {\n check(userId, String);\n check(packageId, String);", " const pack = this.collections.packages.findOne({ _id: packageId });\n if (pack) {\n // Remove old versions.\n const numRemoved = this.collections.userActions.remove({ userId: userId, appId: pack.appId });", " // Install new.\n const actions = pack.manifest.actions;\n for (const i in actions) {\n const action = actions[i];\n if (\"none\" in action.input) {\n const userAction = {\n userId: userId,\n packageId: pack._id,\n appId: pack.appId,\n appTitle: pack.manifest.appTitle,\n appMarketingVersion: pack.manifest.appMarketingVersion,\n appVersion: pack.manifest.appVersion,\n title: action.title,\n nounPhrase: action.nounPhrase,\n command: action.command,\n };\n this.collections.userActions.insert(userAction);\n } else {\n // TODO(someday): Implement actions with capability inputs.\n }\n }", " if (numRemoved > 0 && !simulation) {\n this.deleteUnusedPackages(pack.appId);\n }\n }\n },", " sendAdminNotification(type, action) {\n Meteor.users.find({ isAdmin: true }, { fields: { _id: 1 } }).forEach(function (user) {\n Notifications.insert({\n admin: { action, type },\n userId: user._id,\n timestamp: new Date(),\n isUnread: true,\n });\n });\n },", " getKeybaseProfile(keyFingerprint) {\n return this.collections.keybaseProfiles.findOne(keyFingerprint) || {};\n },", " getServerTitle() {\n const setting = this.collections.settings.findOne({ _id: \"serverTitle\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getSmtpConfig() {\n const setting = this.collections.settings.findOne({ _id: \"smtpConfig\" });\n return setting ? setting.value : undefined; // undefined if subscription is not ready.\n },", " getReturnAddress() {\n const config = this.getSmtpConfig();\n return config && config.returnAddress || \"\"; // empty if subscription is not ready.\n },", " getReturnAddressWithDisplayName(identityId) {\n check(identityId, String);\n const identity = this.getIdentity(identityId);\n const displayName = identity.profile.name + \" (via \" + this.getServerTitle() + \")\";", " // First remove any instances of characters that cause trouble for SimpleSmtp. Ideally,\n // we could escape such characters with a backslash, but that does not seem to help here.", "", " const sanitized = displayName.replace(/\"|<|>|\\\\|\\r/g, \"\");\n", " return \"\\\"\" + sanitized + \"\\\" <\" + this.getReturnAddress() + \">\";", " },", " getPrimaryEmail(accountId, identityId) {\n check(accountId, String);\n check(identityId, String);", " const identity = this.getIdentity(identityId);\n const senderEmails = SandstormDb.getVerifiedEmails(identity);\n const senderPrimaryEmail = _.findWhere(senderEmails, { primary: true });\n const accountPrimaryEmailAddress = this.getUser(accountId).primaryEmail;\n if (_.findWhere(senderEmails, { email: accountPrimaryEmailAddress })) {\n return accountPrimaryEmailAddress;\n } else if (senderPrimaryEmail) {\n return senderPrimaryEmail.email;\n } else {\n return null;\n }\n },", " incrementDailySentMailCount(accountId) {\n check(accountId, String);", " const DAILY_LIMIT = 50;\n const result = Meteor.users.findAndModify({\n query: { _id: accountId },\n update: {\n $inc: {\n dailySentMailCount: 1,\n },\n },\n fields: { dailySentMailCount: 1 },\n });", " if (!result.ok) {\n throw new Error(\"Couldn't update daily sent mail count.\");\n }", " const user = result.value;\n if (user.dailySentMailCount >= DAILY_LIMIT) {\n throw new Error(\n \"Sorry, you've reached your e-mail sending limit for today. Currently, Sandstorm \" +\n \"limits each user to \" + DAILY_LIMIT + \" e-mails per day for spam control reasons. \" +\n \"Please feel free to contact us if this is a problem.\");\n }\n },", " getLdapUrl() {\n const setting = this.collections.settings.findOne({ _id: \"ldapUrl\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getLdapBase() {\n const setting = this.collections.settings.findOne({ _id: \"ldapBase\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getLdapDnPattern() {\n const setting = this.collections.settings.findOne({ _id: \"ldapDnPattern\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getLdapSearchUsername() {\n const setting = this.collections.settings.findOne({ _id: \"ldapSearchUsername\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getLdapNameField() {\n const setting = this.collections.settings.findOne({ _id: \"ldapNameField\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getLdapEmailField() {\n const setting = this.collections.settings.findOne({ _id: \"ldapEmailField\" });\n return setting ? setting.value : \"mail\";\n // default to \"mail\". This setting was added later, and so could potentially be unset.\n },", " getLdapExplicitDnSelected() {\n const setting = this.collections.settings.findOne({ _id: \"ldapExplicitDnSelected\" });\n return setting && setting.value;\n },", " getLdapFilter() {\n const setting = this.collections.settings.findOne({ _id: \"ldapFilter\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getLdapSearchBindDn() {\n const setting = this.collections.settings.findOne({ _id: \"ldapSearchBindDn\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getLdapSearchBindPassword() {\n const setting = this.collections.settings.findOne({ _id: \"ldapSearchBindPassword\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getLdapCaCert() {\n const setting = this.collections.settings.findOne({ _id: \"ldapCaCert\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getOrganizationMembership() {\n const setting = this.collections.settings.findOne({ _id: \"organizationMembership\" });\n return setting && setting.value;\n },", " getOrganizationEmailEnabled() {\n const membership = this.getOrganizationMembership();\n return membership && membership.emailToken && membership.emailToken.enabled;\n },", " getOrganizationEmailDomain() {\n const membership = this.getOrganizationMembership();\n return membership && membership.emailToken && membership.emailToken.domain;\n },", " getOrganizationGoogleEnabled() {\n const membership = this.getOrganizationMembership();\n return membership && membership.google && membership.google.enabled;\n },", " getOrganizationGoogleDomain() {\n const membership = this.getOrganizationMembership();\n return membership && membership.google && membership.google.domain;\n },", " getOrganizationLdapEnabled() {\n const membership = this.getOrganizationMembership();\n return membership && membership.ldap && membership.ldap.enabled;\n },", " getOrganizationSamlEnabled() {\n const membership = this.getOrganizationMembership();\n return membership && membership.saml && membership.saml.enabled;\n },", " getOrganizationDisallowGuests() {\n return this.getOrganizationDisallowGuestsRaw();\n },", " getOrganizationDisallowGuestsRaw() {\n const setting = this.collections.settings.findOne({ _id: \"organizationSettings\" });\n return setting && setting.value && setting.value.disallowGuests;\n },", " getOrganizationShareContacts() {\n return this.getOrganizationShareContactsRaw();\n },", " getOrganizationShareContactsRaw() {\n const setting = this.collections.settings.findOne({ _id: \"organizationSettings\" });\n if (!setting || !setting.value || setting.value.shareContacts === undefined) {\n // default to true if undefined\n return true;\n } else {\n return setting.value.shareContacts;\n }\n },", " getSamlEntryPoint() {\n const setting = this.collections.settings.findOne({ _id: \"samlEntryPoint\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getSamlLogout() {\n const setting = this.collections.settings.findOne({ _id: \"samlLogout\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getSamlPublicCert() {\n const setting = this.collections.settings.findOne({ _id: \"samlPublicCert\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getSamlEntityId() {\n const setting = this.collections.settings.findOne({ _id: \"samlEntityId\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " userHasSamlLoginIdentity() {\n const user = Meteor.user();\n if (!user.loginIdentities) {\n return false;\n }", " let hasSaml = false;\n user.loginIdentities.forEach((identity) => {\n if (Meteor.users.findOne({ _id: identity.id }).services.saml) {\n hasSaml = true;\n }\n });", " return hasSaml;\n },", " getActivitySubscriptions(grainId, threadPath) {\n return this.collections.activitySubscriptions.find({\n grainId: grainId,\n threadPath: threadPath || { $exists: false },\n }, {\n fields: { identityId: 1, mute: 1, _id: 0 },\n }).fetch();\n },", " subscribeToActivity(identityId, grainId, threadPath) {\n // Subscribe the given identity to activity events with the given grainId and (optional)\n // threadPath -- unless the identity has previously muted this grainId/threadPath, in which\n // case do nothing.", " const record = { identityId, grainId };\n if (threadPath) {\n record.threadPath = threadPath;\n }", " // The $set here is redundant since an upsert automatically initializes a new record to contain\n // the fields from the query, but if we try to do { $set: {} } Mongo throws an exception, and\n // if we try to just pass {}, Mongo interprets it as \"replace the record with an empty record\".\n // What a wonderful query language.\n this.collections.activitySubscriptions.upsert(record, { $set: record });\n },", " muteActivity(identityId, grainId, threadPath) {\n // Mute notifications for the given identity originating from the given grainId and\n // (optional) threadPath.", " const record = { identityId, grainId };\n if (threadPath) {\n record.threadPath = threadPath;\n }", " this.collections.activitySubscriptions.upsert(record, { $set: { mute: true } });\n },", " updateAppIndex() {\n const appUpdatesEnabledSetting = this.collections.settings.findOne({ _id: \"appUpdatesEnabled\" });\n const appUpdatesEnabled = appUpdatesEnabledSetting && appUpdatesEnabledSetting.value;\n if (!appUpdatesEnabled) {\n // It's much simpler to check appUpdatesEnabled here rather than reactively deactivate the\n // timer that triggers this call.\n return;\n }", " const appIndexUrl = this.collections.settings.findOne({ _id: \"appIndexUrl\" }).value;\n const appIndex = this.collections.appIndex;\n const data = HTTP.get(appIndexUrl + \"/apps/index.json\").data;\n const preinstalledAppIds = this.getAllPreinstalledAppIds();\n // We make sure to get all preinstalled appIds, even ones that are currently\n // downloading/failed.\n data.apps.forEach((app) => {\n app._id = app.appId;", " const oldApp = appIndex.findOne({ _id: app.appId });\n app.hasSentNotifications = false;\n appIndex.upsert({ _id: app._id }, app);\n const isAppPreinstalled = _.contains(preinstalledAppIds, app.appId);\n if ((!oldApp || app.versionNumber > oldApp.versionNumber) &&\n (this.collections.userActions.findOne({ appId: app.appId }) ||\n isAppPreinstalled)) {\n const pack = this.collections.packages.findOne({ _id: app.packageId });\n const url = appIndexUrl + \"/packages/\" + app.packageId;\n if (pack) {\n if (pack.status === \"ready\") {\n if (pack.appId && pack.appId !== app.appId) {\n console.error(\"app index returned app ID and package ID that don't match:\",\n JSON.stringify(app));\n } else {\n this.sendAppUpdateNotifications(app.appId, app.packageId, app.name, app.versionNumber,\n app.version);\n if (isAppPreinstalled) {\n this.setPreinstallAppAsReady(app.appId, app.packageId);\n }\n }\n } else {\n const result = this.collections.packages.findAndModify({\n query: { _id: app.packageId },\n update: { $set: { isAutoUpdated: true } },\n });", " if (!result.ok) {\n return;\n }", " const newPack = result.value;\n if (newPack.status === \"ready\") {\n // The package was marked as ready before we applied isAutoUpdated=true. We should send\n // notifications ourselves to be sure there's no timing issue (sending more than one is\n // fine, since it will de-dupe).\n if (pack.appId && pack.appId !== app.appId) {\n console.error(\"app index returned app ID and package ID that don't match:\",\n JSON.stringify(app));\n } else {\n this.sendAppUpdateNotifications(app.appId, app.packageId, app.name, app.versionNumber,\n app.version);\n if (isAppPreinstalled) {\n this.setPreinstallAppAsReady(app.appId, app.packageId);\n }\n }\n } else if (newPack.status === \"failed\") {\n // If the package has failed, retry it\n this.startInstall(app.packageId, url, true, true);\n }\n }\n } else {\n this.startInstall(app.packageId, url, false, true);\n }\n }\n });\n },", " isPackagePreinstalled(packageId) {\n return this.collections.settings.find({ _id: \"preinstalledApps\", \"value.packageId\": packageId }).count() === 1;\n },", " getAppIdForPreinstalledPackage(packageId) {\n const setting = this.collections.settings.findOne({ _id: \"preinstalledApps\", \"value.packageId\": packageId },\n { fields: { \"value.$\": 1 } });\n // value.$ causes mongo to transform the result and only return the first matching element in\n // the array\n return setting && setting.value && setting.value[0] && setting.value[0].appId;\n },", " getPackageIdForPreinstalledApp(appId) {\n const setting = this.collections.settings.findOne({ _id: \"preinstalledApps\", \"value.appId\": appId },\n { fields: { \"value.$\": 1 } });\n // value.$ causes mongo to transform the result and only return the first matching element in\n // the array\n return setting && setting.value && setting.value[0] && setting.value[0].packageId;\n },", " getReadyPreinstalledAppIds() {\n const setting = this.collections.settings.findOne({ _id: \"preinstalledApps\" });\n const ret = setting && setting.value || [];\n return _.chain(ret)\n .filter((app) => { return app.status === \"ready\"; })\n .map((app) => { return app.appId; })\n .value();\n },", " getAllPreinstalledAppIds() {\n const setting = this.collections.settings.findOne({ _id: \"preinstalledApps\" });\n const ret = setting && setting.value || [];\n return _.map(ret, (app) => { return app.appId; });\n },", " preinstallAppsForUser(userId) {\n const appIds = this.getReadyPreinstalledAppIds();\n appIds.forEach((appId) => {\n try {\n this.addUserActions(userId, this.getPackageIdForPreinstalledApp(appId));\n } catch (e) {\n console.error(\"failed to install app for user:\", e);\n }\n });\n },", " setPreinstallAppAsDownloading(appId, packageId) {\n this.collections.settings.update(\n { _id: \"preinstalledApps\", \"value.appId\": appId, \"value.packageId\": packageId },\n { $set: { \"value.$.status\": \"downloading\" } });\n },", " setPreinstallAppAsReady(appId, packageId) {\n // This function both sets the appId as ready and updates the packageId for the given appId\n // Setting the packageId is especially useful in installer.js, as it always ensures the\n // latest installed package will be set as ready.\n this.collections.settings.update(\n { _id: \"preinstalledApps\", \"value.appId\": appId },\n { $set: { \"value.$.status\": \"ready\", \"value.$.packageId\": packageId } });\n },", " ensureAppPreinstall(appId, packageId) {\n check(appId, String);\n const appIndexUrl = this.collections.settings.findOne({ _id: \"appIndexUrl\" }).value;\n const pack = this.collections.packages.findOne({ _id: packageId });\n const url = appIndexUrl + \"/packages/\" + packageId;\n if (pack && pack.status === \"ready\") {\n this.setPreinstallAppAsReady(appId, packageId);\n } else if (pack && pack.status === \"failed\") {\n this.setPreinstallAppAsDownloading(appId, packageId);\n this.startInstall(packageId, url, true, false);\n } else {\n this.setPreinstallAppAsDownloading(appId, packageId);\n this.startInstall(packageId, url, false, false);\n }\n },", " setPreinstalledApps(appAndPackageIds) {\n // appAndPackageIds: A List[Object] where each element has fields:\n // appId: The Packages.appId of the app to install\n // packageId: The Packages._id of the app to install\n check(appAndPackageIds, [{ appId: String, packageId: String, }]);", " // Start by clearing out the setting. We'll push appIds one by one to it\n this.collections.settings.upsert({ _id: \"preinstalledApps\" }, { $set: {\n value: appAndPackageIds.map((data) => {\n return {\n appId: data.appId,\n status: \"notReady\",\n packageId: data.packageId,\n };\n }),\n }, });\n appAndPackageIds.forEach((data) => {\n this.ensureAppPreinstall(data.appId, data.packageId);\n });\n },", " getProductivitySuiteAppIds() {\n return [\n \"8aspz4sfjnp8u89000mh2v1xrdyx97ytn8hq71mdzv4p4d8n0n3h\", // Davros\n \"h37dm17aa89yrd8zuqpdn36p6zntumtv08fjpu8a8zrte7q1cn60\", // Etherpad\n \"vfnwptfn02ty21w715snyyczw0nqxkv3jvawcah10c6z7hj1hnu0\", // Rocket.Chat\n \"m86q05rdvj14yvn78ghaxynqz7u2svw6rnttptxx49g1785cdv1h\", // Wekan\n ];\n },", " getSystemSuiteAppIds() {\n return [\n \"s3u2xgmqwznz2n3apf30sm3gw1d85y029enw5pymx734cnk5n78h\", // Collections\n ];\n },", " isPreinstalledAppsReady() {\n const setting = this.collections.settings.findOne({ _id: \"preinstalledApps\" });\n if (!setting || !setting.value) {\n return true;\n }", " const packageIds = _.pluck(setting.value, \"packageId\");\n const readyApps = this.collections.packages.find({\n _id: {\n $in: packageIds,\n },\n status: \"ready\",\n });\n return readyApps.count() === packageIds.length;\n },", " getBillingPromptUrl() {\n const setting = this.collections.settings.findOne({ _id: \"billingPromptUrl\" });\n return setting && setting.value;\n },", " isReferralEnabled() {\n // This function is a bit weird, in that we've transitioned from\n // Meteor.settings.public.quotaEnabled to DB settings. For now,\n // Meteor.settings.public.quotaEnabled implies bothisReferralEnabled and isQuotaEnabled are true.\n return Meteor.settings.public.quotaEnabled;\n },", " isHideAboutEnabled() {\n const setting = this.collections.settings.findOne({ _id: \"whiteLabelHideAbout\" });\n return setting && setting.value;\n },", " isQuotaEnabled() {\n if (Meteor.settings.public.quotaEnabled) return true;", " const setting = this.collections.settings.findOne({ _id: \"quotaEnabled\" });\n return setting && setting.value;\n },", " isQuotaLdapEnabled() {\n const setting = this.collections.settings.findOne({ _id: \"quotaLdapEnabled\" });\n return setting && setting.value;\n },", " updateUserQuota(user) {\n if (this.quotaManager) {\n return this.quotaManager.updateUserQuota(this, user);\n }\n },", " getUserQuota(user) {\n if (this.isQuotaLdapEnabled()) {\n return this.quotaManager.updateUserQuota(this, user);\n } else {\n const plan = this.getPlan(user.plan || \"free\", user);\n const referralBonus = calculateReferralBonus(user);\n const bonus = user.planBonus || {};\n const userQuota = {\n storage: plan.storage + referralBonus.storage + (bonus.storage || 0),\n grains: plan.grains + referralBonus.grains + (bonus.grains || 0),\n compute: plan.compute + (bonus.compute || 0),\n };\n return userQuota;\n }\n },", " isUserOverQuota(user) {\n // Return false if user has quota space remaining, true if it is full. When this returns true,\n // we will not allow the user to create new grains, though they may be able to open existing ones\n // which may still increase their storage usage.\n //\n // (Actually returns a string which can be fed into `billingPrompt` as the reason.)", " if (!this.isQuotaEnabled() || user.isAdmin) return false;", " const plan = this.getUserQuota(user);\n if (plan.grains < Infinity) {\n const count = this.collections.grains.find({ userId: user._id, trashed: { $exists: false } },\n { fields: {}, limit: plan.grains }).count();\n if (count >= plan.grains) return \"outOfGrains\";\n }", " return plan && user.storageUsage && user.storageUsage >= plan.storage && \"outOfStorage\";\n },", " isUserExcessivelyOverQuota(user) {\n // Return true if user is so far over quota that we should prevent their existing grains from\n // running at all.\n //\n // (Actually returns a string which can be fed into `billingPrompt` as the reason.)", " if (!this.isQuotaEnabled() || user.isAdmin) return false;", " const quota = this.getUserQuota(user);", " // quota.grains = Infinity means unlimited grains. IEEE754 defines Infinity == Infinity.\n if (quota.grains < Infinity) {\n const count = this.collections.grains.find({ userId: user._id, trashed: { $exists: false } },\n { fields: {}, limit: quota.grains * 2 }).count();\n if (count >= quota.grains * 2) return \"outOfGrains\";\n }", " return quota && user.storageUsage && user.storageUsage >= quota.storage * 1.2 && \"outOfStorage\";\n },", " suspendIdentity(userId, suspension) {\n check(userId, String);\n check(suspension, {\n timestamp: Date,\n admin: Match.Optional(String),\n voluntary: Match.Optional(Boolean),\n });", " this.collections.users.update({ _id: userId }, { $set: { suspended: suspension } });\n this.collections.apiTokens.update({ \"owner.user.identityId\": userId },\n { $set: { suspended: true } }, { multi: true });\n },", " unsuspendIdentity(userId) {\n check(userId, String);", " this.collections.users.update({ _id: userId }, { $unset: { suspended: 1 } });\n this.collections.apiTokens.update({ \"owner.user.identityId\": userId },\n { $unset: { suspended: true } }, { multi: true });\n },", " suspendAccount(userId, byAdminUserId, willDelete) {\n check(userId, String);\n check(byAdminUserId, Match.OneOf(String, null, undefined));\n check(willDelete, Boolean);", " const user = this.collections.users.findOne({ _id: userId });\n const suspension = {\n timestamp: new Date(),\n willDelete: willDelete || false,\n };\n if (byAdminUserId) {\n suspension.admin = byAdminUserId;\n } else {\n suspension.voluntary = true;\n }", " this.collections.users.update({ _id: userId }, { $set: { suspended: suspension } });\n this.collections.grains.update({ userId: userId }, { $set: { suspended: true } }, { multi: true });", " delete suspension.willDelete;\n // Only mark the parent account for deletion. This makes the query simpler later.", " user.loginIdentities.forEach((identity) => {\n this.suspendIdentity(identity.id, suspension);\n });\n user.nonloginIdentities.forEach((identity) => {\n if (this.collections.users.find({ $or: [\n { \"loginIdentities.id\": identity.id },\n { \"nonloginIdentities.id\": identity.id },\n ], }).count() === 1) {\n // Only suspend non-login identities that are unique to this account.\n this.suspendIdentity(identity.id, suspension);\n }\n });", " // Force logout this user\n this.collections.users.update({ _id: userId },\n { $unset: { \"services.resume.loginTokens\": 1 } });\n if (user && user.loginIdentities) {\n user.loginIdentities.forEach(function (identity) {\n Meteor.users.update({ _id: identity.id }, { $unset: { \"services.resume.loginTokens\": 1 } });\n });\n }\n },", " unsuspendAccount(userId) {\n check(userId, String);", " const user = this.collections.users.findOne({ _id: userId });\n this.collections.users.update({ _id: userId }, { $unset: { suspended: 1 } });\n this.collections.grains.update({ userId: userId }, { $unset: { suspended: 1 } }, { multi: true });", " user.loginIdentities.forEach((identity) => {\n this.unsuspendIdentity(identity.id);\n });", " user.nonloginIdentities.forEach((identity) => {\n this.unsuspendIdentity(identity.id);\n });\n },", " deletePendingAccounts(deletionCoolingOffTime, backend, cb) {\n check(deletionCoolingOffTime, Number);", " const queryDate = new Date(Date.now() - deletionCoolingOffTime);\n this.collections.users.find({\n \"suspended.willDelete\": true,\n \"suspended.timestamp\": { $lt: queryDate },\n }).forEach((user) => {\n if (cb) cb(this, user);\n this.deleteAccount(user._id, backend);\n });\n },", " hostIsStandalone: function (hostname) {\n check(hostname, String);", " return !!this.collections.standaloneDomains.findOne({ _id: hostname, });\n },\n});", "SandstormDb.escapeMongoKey = (key) => {\n // This incredibly poor mechanism for escaping Mongo keys is recommended by the Mongo docs here:\n // https://docs.mongodb.org/manual/faq/developers/#dollar-sign-operator-escaping\n // and seems to be a de facto standard, for example:\n // https://www.npmjs.com/package/mongo-key-escape\n return key.replace(\".\", \"\\uFF0E\").replace(\"$\", \"\\uFF04\");\n};", "const appNameFromPackage = function (packageObj) {\n // This function takes a Package object from Mongo and returns an\n // app title.\n const manifest = packageObj.manifest;\n if (!manifest) return packageObj.appId || packageObj._id || \"unknown\";\n const action = manifest.actions[0];\n appName = (manifest.appTitle && manifest.appTitle.defaultText) ||\n appNameFromActionName(action.title.defaultText);\n return appName;\n};", "const appNameFromActionName = function (name) {\n // Hack: Historically we only had action titles, like \"New Etherpad Document\", not app\n // titles. But for this UI we want app titles. As a transitionary measure, try to\n // derive the app title from the action title.\n // TODO(cleanup): Get rid of this once apps have real titles.\n if (!name) {\n return \"(unnamed)\";\n }", " if (name.lastIndexOf(\"New \", 0) === 0) {\n name = name.slice(4);\n }", " if (name.lastIndexOf(\"Hacker CMS\", 0) === 0) {\n name = \"Hacker CMS\";\n } else {\n const space = name.indexOf(\" \");\n if (space > 0) {\n name = name.slice(0, space);\n }\n }", " return name;\n};", "const appShortDescriptionFromPackage = function (pkg) {\n return pkg && pkg.manifest && pkg.manifest.metadata &&\n pkg.manifest.metadata.shortDescription &&\n pkg.manifest.metadata.shortDescription.defaultText;\n};", "const nounPhraseForActionAndAppTitle = function (action, appTitle) {\n // A hack to deal with legacy apps not including fields in their manifests.\n // I look forward to the day I can remove most of this code.\n // Attempt to figure out the appropriate noun that this action will create.\n // Use an explicit noun phrase is one is available. Apps should add these in the future.\n if (action.nounPhrase) return action.nounPhrase.defaultText;\n // Otherwise, try to guess one from the structure of the action title field\n if (action.title && action.title.defaultText) {\n const text = action.title.defaultText;\n // Strip a leading \"New \"\n if (text.lastIndexOf(\"New \", 0) === 0) {\n const candidate = text.slice(4);\n // Strip a leading appname too, if provided\n if (candidate.lastIndexOf(appTitle, 0) === 0) {\n const newCandidate = candidate.slice(appTitle.length);\n // Unless that leaves you with no noun, in which case, use \"grain\"\n if (newCandidate.length > 0) {\n return newCandidate.toLowerCase();\n } else {\n return \"grain\";\n }\n }", " return candidate.toLowerCase();\n }\n // Some other verb phrase was given. Just use it verbatim, and hope the app author updates\n // the package soon.\n return text;\n } else {\n return \"grain\";\n }\n};", "// Static methods on SandstormDb that don't need an instance.\n// Largely things that deal with backwards-compatibility.\n_.extend(SandstormDb, {\n appNameFromActionName: appNameFromActionName,\n appNameFromPackage: appNameFromPackage,\n appShortDescriptionFromPackage: appShortDescriptionFromPackage,\n nounPhraseForActionAndAppTitle: nounPhraseForActionAndAppTitle,\n});", "if (Meteor.isServer) {\n const Crypto = Npm.require(\"crypto\");\n const ContentType = Npm.require(\"content-type\");\n const Zlib = Npm.require(\"zlib\");\n const Url = Npm.require(\"url\");", " const replicaNumber = Meteor.settings.replicaNumber || 0;", " const computeStagger = function (n) {\n // Compute a fraction in the range [0, 1) such that, for any natural number k, the values\n // of computeStagger(n) for all n in [1, 2^k) are uniformly distributed between 0 and 1.\n // The sequence looks like:\n // 0, 1/2, 1/4, 3/4, 1/8, 3/8, 5/8, 7/8, 1/16, ...\n //\n // We use this to determine how we'll stagger periodic events performed by this replica.\n // Notice that this allows us to compute a stagger which is independent of the number of\n // front-end replicas present; we can add more replicas to the end without affecting how the\n // earlier ones schedule their events.\n let denom = 1;\n while (denom <= n) denom <<= 1;\n const num = n * 2 - denom + 1;\n return num / denom;\n };", " const stagger = computeStagger(replicaNumber);", " SandstormDb.periodicCleanup = function (intervalMs, callback) {\n // Register a database cleanup function than should run periodically, roughly once every\n // interval of the given length.\n //\n // In a blackrock deployment with multiple front-ends, the frequency of the cleanup will be\n // scaled appropriately on the assumption that more data is being generated demanding more\n // frequent cleanups.", " check(intervalMs, Number);\n check(callback, Function);", " if (intervalMs < 120000) {\n throw new Error(\"less than 2-minute cleanup interval seems too fast; \" +\n \"are you using the right units?\");\n }", " // Schedule first cleanup to happen at the next intervalMs interval from the epoch, so that\n // the schedule is independent of the exact startup time.\n let first = intervalMs - Date.now() % intervalMs;", " // Stagger cleanups across replicas so that we don't have all replicas trying to clean the\n // same data at the same time.\n first += Math.floor(intervalMs * computeStagger(replicaNumber));", " // If the stagger put us more than an interval away from now, back up.\n if (first > intervalMs) first -= intervalMs;", " Meteor.setTimeout(function () {\n callback();\n Meteor.setInterval(callback, intervalMs);\n }, first);\n };", " // TODO(cleanup): Node 0.12 has a `gzipSync` but 0.10 (which Meteor still uses) does not.\n const gzipSync = Meteor.wrapAsync(Zlib.gzip, Zlib);", " const BufferSmallerThan = function (limit) {\n return Match.Where(function (buf) {\n check(buf, Buffer);\n return buf.length < limit;\n });\n };", " const DatabaseId = Match.Where(function (s) {\n check(s, String);\n return !!s.match(/^[a-zA-Z0-9_]+$/);\n });", " SandstormDb.prototype.addStaticAsset = function (metadata, content) {\n // Add a new static asset to the database. If `content` is a string rather than a buffer, it\n // will be automatically gzipped before storage; do not specify metadata.encoding in this case.", " if (typeof content === \"string\" && !metadata.encoding) {\n content = gzipSync(new Buffer(content, \"utf8\"));\n metadata.encoding = \"gzip\";\n }", " check(metadata, {\n mimeType: String,\n encoding: Match.Optional(\"gzip\"),\n });\n check(content, BufferSmallerThan(1 << 20));", " // Validate content type.\n metadata.mimeType = ContentType.format(ContentType.parse(metadata.mimeType));", " const hasher = Crypto.createHash(\"sha256\");\n hasher.update(metadata.mimeType + \"\\n\" + metadata.encoding + \"\\n\", \"utf8\");\n hasher.update(content);\n const hash = hasher.digest(\"base64\");", " const result = this.collections.staticAssets.findAndModify({\n query: { hash: hash, refcount: { $gte: 1 } },\n update: { $inc: { refcount: 1 } },\n fields: { _id: 1, refcount: 1 },\n });", " if (!result.ok) {\n throw new Error(`Couldn't increment refcount of asset with hash ${hash}`);\n }", " const existing = result.value;\n if (existing) {\n return existing._id;\n }", " return this.collections.staticAssets.insert(_.extend({\n hash: hash,\n content: content,\n refcount: 1,\n }, metadata));\n };", " SandstormDb.prototype.refStaticAsset = function (id) {\n // Increment the refcount on an existing static asset. Returns the asset on success.\n // If the asset does not exist, returns a falsey value.\n //\n // You must call this BEFORE adding the new reference to the DB, in case of failure between\n // the two calls. (This way, the failure case is a storage leak, which is probably not a big\n // deal and can be fixed by GC, rather than a mysteriously missing asset.)", " check(id, String);", " const result = this.collections.staticAssets.findAndModify({\n query: { hash: hash },\n update: { $inc: { refcount: 1 } },\n fields: { _id: 1, content: 1, mimeType: 1 },\n });", " if (!result.ok) {\n throw new Error(`Couldn't increment refcount of asset with hash ${hash}`);\n }", " const existing = result.value;\n return existing;\n };", " SandstormDb.prototype.unrefStaticAsset = function (id) {\n // Decrement refcount on a static asset and delete if it has reached zero.\n //\n // You must call this AFTER removing the reference from the DB, in case of failure between\n // the two calls. (This way, the failure case is a storage leak, which is probably not a big\n // deal and can be fixed by GC, rather than a mysteriously missing asset.)", " check(id, String);", " const result = this.collections.staticAssets.findAndModify({\n query: { _id: id },\n update: { $inc: { refcount: -1 } },\n fields: { _id: 1, refcount: 1 },\n new: true,\n });", " if (!result.ok) {\n throw new Error(`Couldn't unref static asset ${id}`);\n }", " const existing = result.value;\n if (!existing) {\n console.error(new Error(\"unrefStaticAsset() called on asset that doesn't exist\").stack);\n } else if (existing.refcount <= 0) {\n this.collections.staticAssets.remove({ _id: existing._id });\n }\n };", " SandstormDb.prototype.getStaticAsset = function (id) {\n // Get a static asset's mimeType, encoding, and raw content.", " check(id, String);", " const asset = this.collections.staticAssets.findOne(id, { fields: { _id: 0, mimeType: 1, encoding: 1, content: 1 } });\n if (asset) {\n // TODO(perf): Mongo converts buffers to something else. Figure out a way to avoid a copy\n // here.\n asset.content = new Buffer(asset.content);\n }", " return asset;\n };", " SandstormDb.prototype.newAssetUpload = function (purpose) {\n check(purpose, Match.OneOf(\n { profilePicture: { userId: DatabaseId, identityId: DatabaseId } },\n { loginLogo: {} },\n ));", " return this.collections.assetUploadTokens.insert({\n purpose: purpose,\n expires: new Date(Date.now() + 300000), // in 5 minutes\n });\n };", " SandstormDb.prototype.fulfillAssetUpload = function (id) {\n // Indicates that the given asset upload has completed. It will be removed and its purpose\n // returned. If no matching upload exists, returns undefined.", " check(id, String);", " const result = this.collections.assetUploadTokens.findAndModify({\n query: { _id: id },\n remove: true,\n });", " if (!result.ok) {\n throw new Error(\"Failed to remove asset upload token\");\n }", " const upload = result.value;", " if (upload.expires.valueOf() < Date.now()) {\n return undefined; // already expired\n } else {\n return upload.purpose;\n }\n };", " SandstormDb.prototype.cleanupExpiredAssetUploads = function () {\n this.collections.assetUploadTokens.remove({ expires: { $lt: Date.now() } });\n };", " // TODO(cleanup): lift this out of the package so it can share with the ones in async-helpers.js\n const Future = Npm.require(\"fibers/future\");\n const promiseToFuture = (promise) => {\n const result = new Future();\n promise.then(result.return.bind(result), result.throw.bind(result));\n return result;\n };", " const waitPromise = (promise) => {\n return promiseToFuture(promise).wait();\n };", " SandstormDb.prototype.deleteGrains = function (query, backend, type) {\n // Returns the number of grains deleted.", " check(type, Match.OneOf(\"grain\", \"demoGrain\"));", " let numDeleted = 0;\n this.collections.grains.find(query).forEach((grain) => {\n const user = Meteor.users.findOne(grain.userId);", " waitPromise(backend.deleteGrain(grain._id, grain.userId));\n numDeleted += this.collections.grains.remove({ _id: grain._id });\n this.removeApiTokens({\n grainId: grain._id,\n $or: [\n { owner: { $exists: false } },\n { owner: { webkey: null } },\n ],\n });", " this.removeApiTokens({ \"owner.grain.grainId\": grain._id });", " this.collections.activitySubscriptions.remove({ grainId: grain._id });", " if (grain.lastUsed) {\n const record = {\n type: \"grain\", // Demo grains can never get here!\n lastActive: grain.lastUsed,\n appId: grain.appId,\n };\n if (user && user.experiments) {\n record.experiments = user.experiments;\n }", " this.collections.deleteStats.insert(record);\n }", " this.deleteUnusedPackages(grain.appId);", " if (grain.size) {\n Meteor.users.update(grain.userId, { $inc: { storageUsage: -grain.size } });\n }\n });\n return numDeleted;\n };", " SandstormDb.prototype.userGrainTitle = function (grainId, accountId, identityId) {\n check(grainId, String);\n check(accountId, Match.OneOf(String, undefined, null));\n check(identityId, String);", " const grain = this.getGrain(grainId);\n if (!grain) {\n throw new Error(\"called userGrainTitle() for a grain that doesn't exist\");\n }", " let title = grain.title;\n if (grain.userId !== accountId) {\n const sharerToken = this.collections.apiTokens.findOne({\n grainId: grainId,\n \"owner.user.identityId\": identityId,\n }, {\n sort: {\n lastUsed: -1,\n },\n });\n if (sharerToken) {\n title = sharerToken.owner.user.title;\n } else {\n title = \"shared grain\";\n }\n }", " return title;\n };", " const packageCache = {};\n // Package info is immutable. Let's cache to save on mongo queries.", " SandstormDb.prototype.getPackage = function (packageId) {\n // Get the given package record. Since package info is immutable, cache the data in the server\n // to reduce mongo query overhead, since it turns out we have to fetch specific packages a\n // lot.", " if (packageId in packageCache) {\n return packageCache[packageId];\n }", " const pkg = this.collections.packages.findOne(packageId);\n if (pkg && pkg.status === \"ready\") {\n packageCache[packageId] = pkg;\n }", " return pkg;\n };", " SandstormDb.prototype.deleteUnusedPackages = function (appId) {\n check(appId, String);\n this.collections.packages.find({ appId: appId }).forEach((pkg) => {\n // Mark package for possible deletion;\n this.collections.packages.update({ _id: pkg._id, status: \"ready\" }, { $set: { shouldCleanup: true } });\n });\n };", " SandstormDb.prototype.sendAppUpdateNotifications = function (appId, packageId, name,\n versionNumber, marketingVersion) {\n const actions = this.collections.userActions.find({ appId: appId, appVersion: { $lt: versionNumber } },\n { fields: { userId: 1 } });\n actions.forEach((action) => {\n const userId = action.userId;\n const updater = {\n timestamp: new Date(),\n isUnread: true,\n };\n const inserter = _.extend({ userId, appUpdates: {} }, updater);", " // Set only the appId that we care about. Use mongo's dot notation to specify only a single\n // field inside of an object to update\n inserter.appUpdates[appId] = updater[\"appUpdates.\" + appId] = {\n marketingVersion: marketingVersion,\n packageId: packageId,\n name: name,\n version: versionNumber,\n };", " // We unfortunately cannot upsert because upserts can only have field equality conditions in\n // the query. If we try to upsert, Mongo complaints that \"$exists\" isn't valid to store.\n if (this.collections.notifications.update(\n { userId: userId, appUpdates: { $exists: true } },\n { $set: updater }) == 0) {\n // Update failed; try an insert instead.\n this.collections.notifications.insert(inserter);\n }\n });", " this.collections.appIndex.update({ _id: appId }, { $set: { hasSentNotifications: true } });", " // In the case where we replaced a previous notification and that was the only reference to the\n // package, we need to clean it up\n this.deleteUnusedPackages(appId);\n };", " SandstormDb.prototype.sendReferralProgramNotification = function (userId) {\n this.collections.notifications.upsert({\n userId: userId,\n referral: true,\n }, {\n userId: userId,\n referral: true,\n timestamp: new Date(),\n isUnread: true,\n });\n };", " SandstormDb.prototype.upgradeGrains = function (appId, version, packageId, backend) {\n check(appId, String);\n check(version, Match.Integer);\n check(packageId, String);", " const selector = {\n userId: Meteor.userId(),\n appId: appId,\n appVersion: { $lte: version },\n packageId: { $ne: packageId },\n };", " this.collections.grains.find(selector).forEach(function (grain) {\n backend.shutdownGrain(grain._id, grain.userId);\n });", " this.collections.grains.update(selector, {\n $set: { appVersion: version, packageId: packageId, packageSalt: Random.secret() },\n }, { multi: true });\n };", " SandstormDb.prototype.startInstall = function (packageId, url, retryFailed, isAutoUpdated) {\n // Mark package for possible installation.", " const fields = {\n status: \"download\",\n progress: 0,\n url: url,\n isAutoUpdated: !!isAutoUpdated,\n };", " if (retryFailed) {\n this.collections.packages.update({ _id: packageId, status: \"failed\" }, { $set: fields });\n } else {\n try {\n fields._id = packageId;\n this.collections.packages.insert(fields);\n } catch (err) {\n console.error(\"Simultaneous startInstall()s?\", err.stack);\n }\n }\n };", " const ValidKeyFingerprint = Match.Where(function (keyFingerprint) {\n check(keyFingerprint, String);\n return !!keyFingerprint.match(/^[0-9A-F]{40}$/);\n });", " SandstormDb.prototype.updateKeybaseProfileAsync = function (keyFingerprint) {\n // Asynchronously fetch the given Keybase profile and populate the KeybaseProfiles collection.", " check(keyFingerprint, ValidKeyFingerprint);", " console.log(\"fetching keybase\", keyFingerprint);", " HTTP.get(\n \"https://keybase.io/_/api/1.0/user/lookup.json?key_fingerprint=\" + keyFingerprint +\n \"&fields=basics,profile,proofs_summary\", {\n timeout: 5000,\n }, (err, keybaseResponse) => {\n if (err) {\n console.log(\"keybase lookup error:\", err.stack);\n return;\n }", " if (!keybaseResponse.data) {\n console.log(\"keybase didn't return JSON? Headers:\", keybaseResponse.headers);\n return;\n }", " const profile = (keybaseResponse.data.them || [])[0];", " if (profile) {\n // jscs:disable requireCamelCaseOrUpperCaseIdentifiers\n const record = {\n displayName: (profile.profile || {}).full_name,\n handle: (profile.basics || {}).username,\n proofs: (profile.proofs_summary || {}).all || [],\n };\n // jscs:enable requireCamelCaseOrUpperCaseIdentifiers", " record.proofs.forEach(function (proof) {\n // Remove potentially Mongo-incompatible stuff. (Currently Keybase returns nothing that\n // this would filter.)\n for (let field in proof) {\n // Don't allow field names containing '.' or '$'. Also don't allow sub-objects mainly\n // because I'm too lazy to check the field names recursively (and Keybase doesn't\n // return any objects anyway).\n if (field.match(/[.$]/) || typeof (proof[field]) === \"object\") {\n delete proof[field];\n }\n }", " // Indicate not verified.\n // TODO(security): Asynchronously verify proofs. Presumably we can borrow code from the\n // Keybase node-based CLI.\n proof.status = \"unverified\";\n });", " this.collections.keybaseProfiles.update(keyFingerprint, { $set: record }, { upsert: true });\n } else {\n // Keybase reports no match, so remove what we know of this user. We don't want to remove\n // the item entirely from the cache as this will cause us to repeatedly re-fetch the data\n // from Keybase.\n //\n // TODO(someday): We could perhaps keep the proofs if we can still verify them directly,\n // but at present we don't have the ability to verify proofs.\n this.collections.keybaseProfiles.update(keyFingerprint,\n { $unset: { displayName: \"\", handle: \"\", proofs: \"\" } }, { upsert: true });\n }\n });\n };", " SandstormDb.prototype.deleteUnusedAccount = function (backend, identityId) {\n // If there is an *unused* account that has `identityId` as a login identity, deletes it.", " check(identityId, String);\n const account = this.collections.users.findOne({ \"loginIdentities.id\": identityId });\n if (account &&\n account.loginIdentities.length == 1 &&\n account.nonloginIdentities.length == 0 &&\n !this.collections.grains.findOne({ userId: account._id }) &&\n !this.collections.apiTokens.findOne({ accountId: account._id }) &&\n (!account.plan || account.plan === \"free\") &&\n !(account.payments && account.payments.id) &&\n !this.collections.contacts.findOne({ ownerId: account._id })) {\n this.collections.users.remove({ _id: account._id });\n backend.deleteUser(account._id);\n }\n };", " Meteor.publish(\"keybaseProfile\", function (keyFingerprint) {\n check(keyFingerprint, ValidKeyFingerprint);\n const db = this.connection.sandstormDb;", " const cursor = db.collections.keybaseProfiles.find(keyFingerprint);\n if (cursor.count() === 0) {\n // Fire off async update.\n db.updateKeybaseProfileAsync(keyFingerprint);\n }", " return cursor;\n });", " Meteor.publish(\"appIndex\", function (appId) {\n check(appId, String);\n const db = this.connection.sandstormDb;\n const cursor = db.collections.appIndex.find({ _id: appId });\n return cursor;\n });", " Meteor.publish(\"userPackages\", function () {\n // Users should be able to see packages that are either:\n // 1. referenced by one of their userActions\n // 2. referenced by one of their grains\n const db = this.connection.sandstormDb;", " // Note that package information, once it is in the database, is static. There's no need to\n // reactively subscribe to changes to a package since they don't change. It's also unecessary\n // to reactively remove a package from the client side when it is removed on the server, or\n // when the client stops using it, because the worst case is the client has a small amount\n // of extra info on a no-longer-used package held in memory until they refresh Sandstorm.\n // So, we implement this as a cache: the first time each package ID shows up among the user's\n // stuff, we push the package info to the client, and then we never update it.\n //\n // Alternatively, we could subscribe to each individual package query, but this would waste\n // lots of server-side resources watching for events that will never happen or don't matter.\n const hasPackage = {};\n const refPackage = (packageId) => {\n // Ignore dev apps.\n if (packageId.lastIndexOf(\"dev-\", 0) === 0) return;", " if (!hasPackage[packageId]) {\n hasPackage[packageId] = true;\n const pkg = db.getPackage(packageId);\n if (pkg) {\n this.added(\"packages\", packageId, pkg);\n } else {\n console.error(\n \"shouldn't happen: missing package referenced by user's stuff:\", packageId);\n }\n }\n };", " // package source 1: packages referred to by actions\n const actions = db.userActions(this.userId);\n const actionsHandle = actions.observe({\n added(newAction) {\n refPackage(newAction.packageId);\n },", " changed(newAction, oldAction) {\n refPackage(newAction.packageId);\n },\n });", " // package source 2: packages referred to by grains directly\n const grains = db.userGrains(this.userId, { includeTrash: true });\n const grainsHandle = grains.observe({\n added(newGrain) {\n // Watch out: DevApp grains can lack a packageId.\n if (newGrain.packageId) {\n refPackage(newGrain.packageId);\n }\n },", " changed(newGrain, oldGrain) {\n // Watch out: DevApp grains can lack a packageId.\n if (newGrain.packageId) {\n refPackage(newGrain.packageId);\n }\n },\n });", " this.onStop(function () {\n actionsHandle.stop();\n grainsHandle.stop();\n });", " this.ready();\n });\n}", "if (Meteor.isServer) {\n SandstormDb.prototype.deleteIdentity = function (identityId) {\n check(identityId, String);", " this.removeApiTokens({ \"owner.user.identityId\": identityId });\n this.collections.contacts.remove({ identityId: identityId });\n Meteor.users.remove({ _id: identityId });\n };", " SandstormDb.prototype.deleteAccount = function (userId, backend) {\n check(userId, String);", " const _this = this;\n const user = Meteor.users.findOne({ _id: userId });\n this.deleteGrains({ userId: userId }, backend, \"grain\");\n this.collections.userActions.remove({ userId: userId });\n this.collections.notifications.remove({ userId: userId });\n user.loginIdentities.forEach((identity) => {\n if (Meteor.users.find({ $or: [\n { \"loginIdentities.id\": identity.id },\n { \"nonloginIdentities.id\": identity.id },\n ], }).count() === 1) {\n // If this is the only account with the identity, then delete it\n _this.deleteIdentity(identity.id);\n }\n });\n user.nonloginIdentities.forEach((identity) => {\n if (Meteor.users.find({ $or: [\n { \"loginIdentities.id\": identity.id },\n { \"nonloginIdentities.id\": identity.id },\n ], }).count() === 1) {\n // If this is the only account with the identity, then delete it\n _this.deleteIdentity(identity.id);\n }\n });\n this.collections.contacts.remove({ ownerId: userId });\n backend.deleteUser(userId);\n Meteor.users.remove({ _id: userId });\n };\n}", "Meteor.methods({\n addUserActions(packageId) {\n check(packageId, String);\n if (!this.userId || !Meteor.user().loginIdentities || !isSignedUpOrDemo()) {\n throw new Meteor.Exception(403, \"Must be logged in as a non-guest to add app actions.\");\n }", " if (this.isSimulation) {\n // TODO(cleanup): Appdemo code relies on this being simulated client-side but we don't have\n // a proper DB object to use.\n new SandstormDb().addUserActions(this.userId, packageId, true);\n } else {\n this.connection.sandstormDb.addUserActions(this.userId, packageId);\n }\n },", " removeUserAction(actionId) {\n check(actionId, String);\n if (this.isSimulation) {\n UserActions.remove({ _id: actionId });\n } else {\n if (this.userId) {\n const result = this.connection.sandstormDb.collections.userActions.findAndModify({\n query: { _id: actionId, userId: this.userId },\n remove: true,\n });", " if (!result.ok) {\n throw new Error(`Couldn't remove user action ${actionId}`);\n }", " const action = result.value;\n if (action) {\n this.connection.sandstormDb.deleteUnusedPackages(action.appId);\n }\n }\n }\n },\n});" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [84, 1522, 203, 231], "buggy_code_start_loc": [77, 1518, 202, 188], "filenames": ["shell/imports/server/email.js", "shell/packages/sandstorm-db/db.js", "shell/server/accounts/email-token/token-server.js", "shell/server/admin-server.js"], "fixing_code_end_loc": [121, 1524, 203, 232], "fixing_code_start_loc": [78, 1519, 202, 188], "message": "A remote attacker could bypass the Sandstorm organization restriction before build 0.203 via a comma in an email-address field.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sandstorm:sandstorm:*:*:*:*:*:*:*:*", "matchCriteriaId": "683ED5F0-D297-4A47-ADF9-186832F3A3AD", "versionEndExcluding": "0.203", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A remote attacker could bypass the Sandstorm organization restriction before build 0.203 via a comma in an email-address field."}, {"lang": "es", "value": "Un atacante remoto podr\u00eda omitir la restricci\u00f3n de organizaci\u00f3n de Sandstorm antes de la build 0.203 mediante una coma en un campo email-address."}], "evaluatorComment": null, "id": "CVE-2017-6199", "lastModified": "2018-03-13T19:27:30.200", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-02-06T16:29:00.730", "references": [{"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://devco.re/blog/2018/01/26/Sandstorm-Security-Review-CVE-2017-6200-en/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/sandstorm-io/sandstorm/blob/v0.202/shell/packages/sandstorm-db/db.js#L1112"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/sandstorm-io/sandstorm/commit/37bd9a7f4eb776cdc2d3615f0bfea1254b66f59d"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://sandstorm.io/news/2017-03-02-security-review"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-287"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/sandstorm-io/sandstorm/commit/37bd9a7f4eb776cdc2d3615f0bfea1254b66f59d"}, "type": "CWE-287"}
324
Determine whether the {function_name} code is vulnerable or not.
[ "// Sandstorm - Personal Cloud Sandbox\n// Copyright (c) 2014 Sandstorm Development Group, Inc. and contributors\n// All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.", "// This file defines the database schema.", "// Useful for debugging: Set the env variable LOG_MONGO_QUERIES to have the server write every\n// query it makes, so you can see if it's doing queries too often, etc.\nif (Meteor.isServer && process.env.LOG_MONGO_QUERIES) {\n const oldFind = Mongo.Collection.prototype.find;\n Mongo.Collection.prototype.find = function () {\n console.log(this._prefix, arguments);\n return oldFind.apply(this, arguments);\n };\n}", "// Helper so that we don't have to if (Meteor.isServer) before declaring indexes.\nif (Meteor.isServer) {\n Mongo.Collection.prototype.ensureIndexOnServer = Mongo.Collection.prototype._ensureIndex;\n} else {\n Mongo.Collection.prototype.ensureIndexOnServer = function () {};\n}", "// TODO(soon): Systematically go through this file and add ensureIndexOnServer() as needed.", "const collectionOptions = { defineMutationMethods: Meteor.isClient };\n// Set to `true` on the client so that method simulation works. Set to `false` on the server\n// so that we can be extra certain that all mutations must go through methods.", "// Users = new Mongo.Collection(\"users\");\n// The users collection is special and can be accessed through `Meteor.users`.\n// See https://docs.meteor.com/#/full/meteor_users.\n//\n// There are two distinct types of entries in the users collection: identities and accounts. An\n// identity contains personal profile information and typically includes some intrinsic method for\n// authenticating as the owner of that information.\n//\n// An account is an owner of app actions, grains, contacts, notifications, and payment info.\n// Each account can have multiple identities linked to it. To log in as an account you must first\n// authenticate as one of its linked identities.\n//\n// Every user contains the following fields:\n// _id: Unique string ID. For accounts, this is random. For identities, this is the globally\n// stable SHA-256 ID of this identity, hex-encoded.\n// createdAt: Date when this entry was added to the collection.\n// lastActive: Date of the user's most recent interaction with this Sandstorm server.\n// services: Object containing login data used by Meteor authentication services.\n// expires: Date when this user should be deleted. Only present for demo users.\n// upgradedFromDemo: If present, the date when this user was upgraded from being a demo user.\n// TODO(cleanup): Unlike other dates in our database, this is stored as a number\n// rather than as a Date object. We should fix that.\n// appDemoId: If present and non-null, then the user is a demo user who arrived via an /appdemo/\n// link. This field contains the app ID of the app that the user started out demoing.\n// Unlike the `expires` field, this field is not cleared when the user upgrades from\n// being a demo user.\n// suspended: If this exists, this account/identity is supsended. Both accounts and identities\n// can be suspended. After some amount of time, the user will be completely deleted\n// and removed from the DB.\n// It is an object with fields:\n// voluntary: Boolean. This is true if the user initiated it. They will have the\n// chance to still login and reverse the suspension/deletion.\n// admin: The userId of the admin who suspended the account.\n// timestamp: Date object. When the suspension occurred.\n// willDelete: Boolean. If true, this account will be deleted after some time.\n//\n// Identity users additionally contain the following fields:\n// profile: Object containing the data that will be shared with users and grains that come into\n// contact with this identity. Includes the following fields:\n// service: String containing the name of this identity's authentication method.\n// name: String containing the chosen display name of the identity.\n// handle: String containing the identity's preferred handle.\n// picture: _id into the StaticAssets table for the identity's picture. If not present,\n// an identicon will be used.\n// pronoun: One of \"male\", \"female\", \"neutral\", or \"robot\".\n// unverifiedEmail: If present, a string containing an email address specified by the user.\n// referredBy: ID of the Account that referred this Identity.\n//\n// Account users additionally contain the following fields:\n// loginIdentities: Array of identity objects, each of which may include the following fields.\n// id: The globally-stable SHA-256 ID of this identity, hex-encoded.\n// nonloginIdentities: Array of identity objects, of the same form as `loginIdentities`. We use\n// a separate array here so that we can use a Mongo index to enforce the\n// invariant that an identity only be a login identity for a single account.\n// primaryEmail: String containing this account's primary email address. Must be a verified adress\n// of one of this account's linked identities. Call SandstormDb.getUserEmails()\n// to do this checking automatically.\n// isAdmin: Boolean indicating whether this account is allowed to access the Sandstorm admin panel.\n// signupKey: If this is an invited user, then this field contains their signup key.\n// signupNote: If the user was invited through a link, then this field contains the note that the\n// inviter admin attached to the key.\n// signupEmail: If the user was invited by email, then this field contains the email address that\n// the invite was sent to.\n// hasCompletedSignup: True if this account has confirmed its profile and agreed to this server's\n// terms of service.\n// plan: _id of an entry in the Plans table which determines the user's quota.\n// planBonus: {storage, compute, grains} bonus amounts to add to the user's plan. The payments\n// module writes data here; we merely read it. Missing fields should be treated as\n// zeroes. Does not yet include referral bonus, which is calculated separately.\n// TODO(cleanup): Use for referral bonus too.\n// storageUsage: Number of bytes this user is currently storing.\n// payments: Object defined by payments module, if loaded.\n// dailySentMailCount: Number of emails sent by this user today; used to limit spam.\n// accessRequests: Object containing the following fields; used to limit spam.\n// count: Number of \"request access\" emails during sent during the current interval.\n// resetOn: Date when the count should be reset.\n// referredByComplete: ID of the Account that referred this Account. If this is set, we\n// stop writing new referredBy values onto Identities for this account.\n// referredCompleteDate: The Date at which the completed referral occurred.\n// referredIdentityIds: List of Identity IDs that this Account has referred. This is used for\n// reliably determining which Identity's names are safe to display.\n// experiments: Object where each field is an experiment that the user is in, and each value\n// is the parameters for that experiment. Typically, the value simply names which\n// experiment group which the user is in, where \"control\" is one group. If an experiment\n// is not listed, then the user should not be considered at all for the purpose of that\n// experiment. Each experiment may define a point in time where users not already in the\n// experiment may be added to it and assigned to a group (for example, at user creation\n// time). Current experiments:\n// firstTimeBillingPrompt: Value is \"control\" or \"test\". Users are assigned to groups at\n// account creation on servers where billing is enabled (i.e. Oasis). Users in the\n// test group will see a plan selection dialog and asked to make an explitic choice\n// (possibly \"free\") before they can create grains (but not when opening someone\n// else's shared grain). The goal of the experiment is to determine whether this\n// prompt scares users away -- and also whether it increases paid signups.\n// freeGrainLimit: Value is \"control\" or or a number indicating the grain limit that the\n// user should receive when on the \"free\" plan, e.g. \"Infinity\".\n// stashedOldUser: A complete copy of this user from before the accounts/identities migration.\n// TODO(cleanup): Delete this field once we're sure it's safe to do so.", "Meteor.users.ensureIndexOnServer(\"services.google.email\", { sparse: 1 });\nMeteor.users.ensureIndexOnServer(\"services.github.emails.email\", { sparse: 1 });\nMeteor.users.ensureIndexOnServer(\"services.email.email\", { unique: 1, sparse: 1 });\nMeteor.users.ensureIndexOnServer(\"loginIdentities.id\", { unique: 1, sparse: 1 });\nMeteor.users.ensureIndexOnServer(\"nonloginIdentities.id\", { sparse: 1 });\nMeteor.users.ensureIndexOnServer(\"services.google.id\", { unique: 1, sparse: 1 });\nMeteor.users.ensureIndexOnServer(\"services.github.id\", { unique: 1, sparse: 1 });\nMeteor.users.ensureIndexOnServer(\"suspended.willDelete\", { sparse: 1 });", "// TODO(cleanup): This index is obsolete; delete it.\nMeteor.users.ensureIndexOnServer(\"identities.id\", { unique: 1, sparse: 1 });", "Packages = new Mongo.Collection(\"packages\", collectionOptions);\n// Packages which are installed or downloading.\n//\n// Each contains:\n// _id: 128-bit prefix of SHA-256 hash of spk file, hex-encoded.\n// status: String. One of \"download\", \"verify\", \"unpack\", \"analyze\", \"ready\", \"failed\", \"delete\"\n// progress: Float. -1 = N/A, 0-1 = fractional progress (e.g. download percentage),\n// >1 = download byte count.\n// error: If status is \"failed\", error message string.\n// manifest: If status is \"ready\", the package manifest. See \"Manifest\" in package.capnp.\n// appId: If status is \"ready\", the application ID string. Packages representing different\n// versions of the same app have the same appId. The spk tool defines the app ID format\n// and can cryptographically verify that a package belongs to a particular app ID.\n// shouldCleanup: If true, a reference to this package was recently dropped, and the package\n// collector should at some point check whether there are any other references and, if not,\n// delete the package.\n// url: When status is \"download\", the URL from which the SPK can be obtained, if provided.\n// isAutoUpdated: This package was downloaded as part of an auto-update. We shouldn't clean it up\n// even if it has no users.\n// authorPgpKeyFingerprint: Verified PGP key fingerprint (SHA-1, hex, all-caps) of the app\n// packager.", "DevPackages = new Mongo.Collection(\"devpackages\", collectionOptions);\n// List of packages currently made available via the dev tools running on the local machine.\n// This is normally empty; the only time it is non-empty is when a developer is using the spk tool\n// on the local machine to publish an under-development app to this server. That should only ever\n// happen on developers' desktop machines.\n//\n// While a dev package is published, it automatically appears as installed by every user of the\n// server, and it overrides all packages with the same application ID. If any instances of those\n// packages are currently open, they are killed and reset on publish.\n//\n// When the dev tool disconnects, the package is automatically unpublished, and any open instances\n// are again killed and refreshed.\n//\n// Each contains:\n// _id: The package ID string (as with Packages._id).\n// appId: The app ID this package is intended to override (as with Packages.appId).\n// timestamp: Time when the package was last updated. If this changes while the package is\n// published, all running instances are reset. This is used e.g. to reset the app each time\n// changes are made to the source code.\n// manifest: The app's manifest, as with Packages.manifest.\n// mountProc: True if the supervisor should mount /proc.", "UserActions = new Mongo.Collection(\"userActions\", collectionOptions);\n// List of actions that each user has installed which create new grains. Each app may install\n// some number of actions (usually, one).\n//\n// Each contains:\n// _id: random\n// userId: Account ID of the user who has installed this action.\n// packageId: Package used to run this action.\n// appId: Same as Packages.findOne(packageId).appId; denormalized for searchability.\n// appTitle: Same as Packages.findOne(packageId).manifest.appTitle; denormalized so\n// that clients can access it without subscribing to the Packages collection.\n// appVersion: Same as Packages.findOne(packageId).manifest.appVersion; denormalized for\n// searchability.\n// appMarketingVersion: Human-readable presentation of the app version, e.g. \"2.9.17\"\n// title: JSON-encoded LocalizedText title for this action, e.g.\n// `{defaultText: \"New Spreadsheet\"}`.\n// nounPhrase: JSON-encoded LocalizedText describing what is created when this action is run.\n// command: Manifest.Command to run this action (see package.capnp).", "Grains = new Mongo.Collection(\"grains\", collectionOptions);\n// Grains belonging to users.\n//\n// Each contains:\n// _id: random\n// packageId: _id of the package of which this grain is an instance.\n// packageSalt: If present, a random string that will used in session ID generation. This field\n// is usually updated when `packageId` is updated, triggering automatic refreshes for\n// clients with active sessions.\n// appId: Same as Packages.findOne(packageId).appId; denormalized for searchability.\n// appVersion: Same as Packages.findOne(packageId).manifest.appVersion; denormalized for\n// searchability.\n// userId: The _id of the account that owns this grain.\n// identityId: The identity with which the owning account prefers to open this grain.\n// title: Human-readable string title, as chosen by the user.\n// lastUsed: Date when the grain was last used by a user.\n// private: If true, then knowledge of `_id` does not suffice to open this grain.\n// cachedViewInfo: The JSON-encoded result of `UiView.getViewInfo()`, cached from the most recent\n// time a session to this grain was opened.\n// trashed: If present, the Date when this grain was moved to the trash bin. Thirty days after\n// this date, the grain will be automatically deleted.\n// suspended: If true, the owner of this grain has been suspended. They will soon be deleted,\n// so treat this grain the same as \"trashed\". It is denormalized out of Users for ease\n// of querying.\n// ownerSeenAllActivity: True if the owner has viewed the grain since the last activity event\n// occurred. See also ApiTokenOwner.user.seenAllActivity.\n// size: On-disk size of the grain in bytes.\n//\n// The following fields *might* also exist. These are temporary hacks used to implement e-mail and\n// web publishing functionality without powerbox support; they will be replaced once the powerbox\n// is implemented.\n// publicId: An id used to publicly identify this grain. Used e.g. to route incoming e-mail and\n// web publishing. This field is initialized when first requested by the app.", "Grains.ensureIndexOnServer(\"cachedViewInfo.matchRequests.tags.id\", { sparse: 1 });", "RoleAssignments = new Mongo.Collection(\"roleAssignments\", collectionOptions);\n// *OBSOLETE* Before `user` was a variant of ApiTokenOwner, this collection was used to store edges\n// in the permissions sharing graph. This functionality has been subsumed by the ApiTokens\n// collection.", "Contacts = new Mongo.Collection(\"contacts\", collectionOptions);\n// Edges in the social graph.\n//\n// If Alice has Bob as a contact, then she is allowed to see Bob's profile information and Bob\n// will show up in her user-picker UI for actions like share-by-identity.\n//\n// Contacts are not symmetric. Bob might be one of Alice's contacts even if Alice is not one of\n// Bob's.\n//\n// Each contains:\n// _id: random\n// ownerId: The accountId of the user account who owns this contact.\n// petname: Human-readable label chosen by and only visible to the owner. Uniquely identifies\n// the contact to the owner.\n// created: Date when this contact was created.\n// identityId: The `_id` of the user whose contact info this contains.", "Sessions = new Mongo.Collection(\"sessions\", collectionOptions);\n// UI sessions open to particular grains. A new session is created each time a user opens a grain.\n//\n// Each contains:\n// _id: String generated as a SHA256 hash of the grain ID, the user ID, a salt generated by the\n// client, and the grain's `packageSalt`.\n// grainId: _id of the grain to which this session is connected.\n// hostId: ID part of the hostname from which this grain is being served. I.e. this replaces the\n// '*' in WILDCARD_HOST.\n// tabId: Random value unique to the grain tab in which this session is displayed. Typically\n// every session has a different `tabId`, but embedded sessions (including in the powerbox)\n// have the same `tabId` as the outer session.\n// timestamp: Time of last keep-alive message to this session. Sessions time out after some\n// period.\n// userId: Account ID of the user who owns this session.\n// identityId: Identity ID of the user who owns this session.\n// hashedToken: If the session is owned by an anonymous user, the _id of the entry in ApiTokens\n// that was used to open it. Note that for old-style sharing (i.e. when !grain.private),\n// anonymous users can get access without an API token and so neither userId nor hashedToken\n// are present.\n// powerboxView: Information about a server-initiated powerbox interaction taking place in this\n// session. When the client sees a `powerboxView` appear on the session, it opens the\n// powerbox popup according to the contents. This field is an object containing one of:\n// offer: A capability is being offered to the user by the app. This is an object containing:\n// token: For a non-UiView capability, the API token that can be used to restore this\n// capability.\n// uiView: A UiView capability. This object contains one of:\n// tokenId: The _id of an ApiToken belonging to the current user.\n// token: A full webkey token which can be opened by an anonymous user.\n// fulfill: A capability is being offered which fulfills the active powerbox request. This\n// is an object with members:\n// token: The SturdyRef of the fulfilling capability. This token can only be used in a call\n// to claimRequest() by the requesting\n// grain.\n// descriptor: Packed-base64 PowerboxDescriptor for the capability.\n// powerboxRequest: If present, this session is a powerbox request session. Object containing:\n// descriptors: Array of PowerboxDescriptors representing the request.\n// requestingSession: Session ID of the session initiating the request.\n// viewInfo: The UiView.ViewInfo corresponding to the underlying UiSession. This isn't populated\n// until newSession is called on the UiView.\n// permissions: The permissions for the current identity on this UiView. This isn't populated\n// until newSession is called on the UiView.\n// hasLoaded: Marked as true by the proxy when the underlying UiSession has responded to its first\n// request", "SignupKeys = new Mongo.Collection(\"signupKeys\", collectionOptions);\n// Invite keys which may be used by users to get access to Sandstorm.\n//\n// Each contains:\n// _id: random\n// used: Boolean indicating whether this key has already been consumed.\n// note: Text note assigned when creating key, to keep track of e.g. whom the key was for.\n// email: If this key was sent as an email invite, the email address to which it was sent.", "ActivityStats = new Mongo.Collection(\"activityStats\", collectionOptions);\n// Contains usage statistics taken on a regular interval. Each entry is a data point.\n//\n// Each contains:\n// timestamp: Date when measurements were taken.\n// daily: Contains stats counts pertaining to the last day before the sample time.\n// weekly: Contains stats counts pertaining to the last seven days before the sample time.\n// monthly: Contains stats counts pertaining to the last thirty days before the timestamp.\n//\n// Each of daily, weekly, and monthly contains:\n// activeUsers: The number of unique users who have used a grain on the server in the time\n// interval. Only counts logged-in users.\n// demoUsers: Demo users.\n// appDemoUsers: Users that came in through \"app demo\".\n// activeGrains: The number of unique grains that have been used in the time interval.\n// apps: An object indexed by app ID recording, for each app:\n// owners: Number of unique owners of this app (counting only grains that still exist).\n// sharedUsers: Number of users who have accessed other people's grains of this app (counting\n// only grains that still exist).\n// grains: Number of active grains of this app (that still exist).\n// deleted: Number of non-demo grains of this app that were deleted.\n// demoed: Number of demo grains created and expired.\n// appDemoUsers: Number of app demos initiated with this app.", "DeleteStats = new Mongo.Collection(\"deleteStats\", collectionOptions);\n// Contains records of objects that were deleted, for stat-keeping purposes.\n//\n// Each contains:\n// type: \"grain\" or \"user\" or \"demoGrain\" or \"demoUser\" or \"appDemoUser\"\n// lastActive: Date of the user's or grain's last activity.\n// appId: For type = \"grain\", the app ID of the grain. For type = \"appDemoUser\", the app ID they\n// arrived to demo. For others, undefined.\n// experiments: The experiments the user (or owner of the grain) was in. See user.experiments.", "FileTokens = new Mongo.Collection(\"fileTokens\", collectionOptions);\n// Tokens corresponding to backup files that are currently stored on the server. A user receives\n// a token when they create a backup file (either by uploading it, or by backing up one of their\n// grains) and may use the token to read the file (either to download it, or to restore a new\n// grain from it).\n//\n// Each contains:\n// _id: The unguessable token string.\n// name: Suggested filename.\n// timestamp: File creation time. Used to figure out when the token and file should be wiped.", "ApiTokens = new Mongo.Collection(\"apiTokens\", collectionOptions);\n// Access tokens for APIs exported by apps.\n//\n// Originally API tokens were only used by external users through the HTTP API endpoint. However,\n// now they are also used to implement SturdyRefs, not just held by external users, but also when\n// an app holds a SturdyRef to another app within the same server. See the various `save()`,\n// `restore()`, and `drop()` methods in `grain.capnp` (on `SandstormApi`, `AppPersistent`, and\n// `MainView`) -- the fields of type `Data` are API tokens.\n//\n// Each contains:\n// _id: A SHA-256 hash of the token, base64-encoded.\n// grainId: The grain servicing this API. (Not present if the API isn't serviced by a grain.)\n// identityId: For UiView capabilities, this is the identity for which the view is attenuated.\n// That is, the UiView's newSession() method will intersect the requested permissions\n// with this identity's permissions before forwarding on to the underlying app. If\n// `identityId` is not present, then no identity attenuation is applied, i.e. this is\n// a raw UiView as implemented by the app. (The `roleAssignment` field, below, may\n// still apply. For non-UiView capabilities, `identityId` is never present. Note that\n// this is NOT the identity against which the `requiredPermissions` parameter of\n// `SandstormApi.restore()` is checked; that would be `owner.grain.introducerIdentity`.\n// accountId: For tokens where `identityId` is set, the `_id` (in the Users table) of the account\n// that created the token.\n// roleAssignment: If this API token represents a UiView, this field contains a JSON-encoded\n// Grain.ViewSharingLink.RoleAssignment representing the permissions it carries. These\n// permissions will be intersected with those held by `identityId` when the view is\n// opened.\n// forSharing: If true, requests sent to the HTTP API endpoint with this token will be treated as\n// anonymous rather than as directly associated with `identityId`. This has no effect\n// on the permissions granted.\n// objectId: If present, this token represents an arbitrary Cap'n Proto capability exported by\n// the app or its supervisor (whereas without this it strictly represents UiView).\n// sturdyRef is the JSON-encoded SupervisorObjectId (defined in `supervisor.capnp`).\n// Note that if the SupervisorObjectId contains an AppObjectId, that field is\n// treated as type AnyPointer, and so encoded as a raw Cap'n Proto message.\n// frontendRef: If present, this token actually refers to an object implemented by the front-end,\n// not a particular grain. (`grainId` and `identityId` are not set.) This is an object\n// containing exactly one of the following fields:\n// notificationHandle: A `Handle` for an ongoing notification, as returned by\n// `NotificationTarget.addOngoing`. The value is an `_id` from the\n// `Notifications` collection.\n// ipNetwork: An IpNetwork capability that is implemented by the frontend. Eventually, this\n// will be moved out of the frontend and into the backend, but we'll migrate the\n// database when that happens. This field contains the boolean true to signify that\n// it has been set.\n// ipInterface: Ditto IpNetwork, except it's an IpInterface.\n// emailVerifier: An EmailVerifier capability that is implemented by the frontend. The\n// value is an object containing the fields `id` and `services`. `id` is the\n// value returned by `EmailVerifier.getId()` and is used as part of a\n// powerbox query for matching verified emails. `services` is a\n// list of names of identity providers that are trusted to verify addresses.\n// If `services` is omitted or falsy, all configured identity providers are\n// trusted. Note that a malicious user could specify invalid names in the\n// list; they should be ignored.\n// verifiedEmail: An VerifiedEmail capability that is implemented by the frontend.\n// An object containing `verifierId`, `tabId`, and `address`.\n// identity: An Identity capability. The field is the identity ID.\n// http: An ApiSession capability pointing to an external HTTP service. Object containing:\n// url: Base URL of the external service.\n// auth: Authentication mechanism. Object containing one of:\n// none: Value \"null\". Indicates no authorization.\n// bearer: A bearer token to pass in the `Authorization: Bearer` header on all\n// requests. Encrypted with nonce 0.\n// basic: A `{username, password}` object. The password is encrypted with nonce 0.\n// Before encryption, the password is padded to 32 bytes by appending NUL bytes,\n// in order to mask the length of small passwords.\n// refresh: An OAuth refresh token, which can be exchanged for an access token.\n// Encrypted with nonce 0.\n// TODO(security): How do we protect URLs that directly embed their secret? We don't\n// want to encrypt the full URL since this would make it hard to show a\n// meaningful audit UI, but maybe we could figure out a way to extract the key\n// part and encrypt it separately?\n// parentToken: If present, then this token represents exactly the capability represented by\n// the ApiToken with _id = parentToken, except possibly (if it is a UiView) attenuated\n// by `roleAssignment` (if present). To facilitate permissions computations, if the\n// capability is a UiView, then `grainId` is set to the backing grain, `identityId`\n// is set to the identity that shared the view, and `accountId` is set to the account\n// that shared the view. Neither `objectId` nor `frontendRef` is present when\n// `parentToken` is present.\n// parentTokenKey: The actual parent token -- whereas `parentToken` is only the parent token ID\n// (hash). `parentTokenFull` is encrypted with nonce 0 (see below). This is needed\n// in particular when the parent contains encrypted fields, since those would need to\n// be decrypted using this key. If the parent contains no encrypted fields then\n// `parentTokenKey` may be omitted from the child.\n// petname: Human-readable label for this access token, useful for identifying tokens for\n// revocation. This should be displayed when visualizing incoming capabilities to\n// the grain identified by `grainId`.\n// created: Date when this token was created.\n// revoked: If true, then this sturdyref has been revoked and can no longer be restored. It may\n// become un-revoked in the future.\n// trashed: If present, the Date when this token was moved to the trash bin. Thirty days after\n// this date, the token will be automatically deleted.\n// suspended: If true, the owner of this token has been suspended. They will soon be deleted,\n// so treat this token the same as \"trashed\". It is denormalized out of Users for\n// ease of querying.\n// expires: Optional expiration Date. If undefined, the token does not expire.\n// lastUsed: Optional Date when this token was last used.\n// owner: A `ApiTokenOwner` (defined in `supervisor.capnp`, stored as a JSON object)\n// as passed to the `save()` call that created this token. If not present, treat\n// as `webkey` (the default for `ApiTokenOwner`).\n// expiresIfUnused:\n// Optional Date after which the token, if it has not been used yet, expires.\n// This field should be cleared on a token's first use.\n// requirements: List of conditions which must hold for this token to be considered valid.\n// Semantically, this list specifies the powers which were *used* to originally\n// create the token. If any condition in the list becomes untrue, then the token must\n// be considered revoked, and all live refs and sturdy refs obtained transitively\n// through it must also become revoked. Each item is the JSON serialization of the\n// `MembraneRequirement` structure defined in `supervisor.capnp`.\n// hasApiHost: If true, there is an entry in ApiHosts for this token, which will need to be\n// cleaned up when the token is.\n//\n// It is important to note that a token's owner and provider are independent from each other. To\n// illustrate, here is an approximate definition of ApiToken in pseudo Cap'n Proto schema language:\n//\n// struct ApiToken {\n// owner :ApiTokenOwner;\n// provider :union {\n// grain :group {\n// grainId :Text;\n// union {\n// uiView :group {\n// identityId :Text;\n// roleAssignment :RoleAssignment;\n// forSharing :Bool;\n// }\n// objectId :SupervisorObjectId;\n// }\n// }\n// frontendRef :union {\n// notificationHandle :Text;\n// ipNetwork :Bool;\n// ipInterface :Bool;\n// emailVerifier :group {\n// id :Text;\n// services :List(String);\n// }\n// verifiedEmail :group {\n// verifierId :Text;\n// tabId :Text;\n// address :Text;\n// }\n// identity :Text;\n// http :group {\n// url :Text;\n// auth :union {\n// none :Void;\n// bearer :Text;\n// basic :group { username :Text; password :Text; }\n// refresh :Text;\n// }\n// }\n// }\n// child :group {\n// parentToken :Text;\n// union {\n// uiView :group {\n// grainId :Text;\n// identityId :Text;\n// roleAssignment :RoleAssignment = (allAccess = ());\n// }\n// other :Void;\n// }\n// }\n// }\n// requirements: List(Supervisor.MembraneRequirement);\n// ...\n// }\n//\n// ENCRYPTION\n//\n// We want to make sure that someone who obtains a copy of the database cannot use it to gain live\n// credentials.\n//\n// The actual token corresponding to an ApiToken entry is not stored in the entry itself. Instead,\n// the ApiToken's `_id` is constructed as a SHA256 hash of the actual token. To use an ApiToken\n// in the live system, you must present the original token.\n//\n// Additionally, some ApiToken entries contain tokens to third-party services, e.g. OAuth tokens\n// or even passwords. Such tokens are encrypted, using the ApiToken entry's own full token (which,\n// again, is not stored in the database) as the encryption key.\n//\n// When such encryption is applied, the cipher used is ChaCha20. All API tokens are 256-bit base64\n// strings, hence can be used directly as the key. No MAC is applied, because this scheme is not\n// intended to protect against attackers who have write access to the database -- such an attacker\n// could almost certainly do more damage by modifying the non-encrypted fields anyway. (Put another\n// way, if we wanted to MAC something, we'd need to MAC the entire ApiToken structure, not just\n// the encrypted key. But we don't have a way to do that at present.)\n//\n// ChaCha20 requires a nonce. Luckily, all of the fields we wish to encrypt are immutable, so we\n// don't have to worry about tracking nonces over time -- we can just assign a static nonce to each\n// field. Moreover, many (currently, all) of these fields are mutually exclusive, so can even share\n// nonces. Currently, nonces map to fields as follows:\n//\n// nonce 0:\n// parentTokenKey\n// frontendRef.http.auth.basic.password\n// frontendRef.http.auth.bearer\n// frontendRef.http.auth.refresh", "ApiTokens.ensureIndexOnServer(\"grainId\", { sparse: 1 });\nApiTokens.ensureIndexOnServer(\"owner.user.identityId\", { sparse: 1 });\nApiTokens.ensureIndexOnServer(\"frontendRef.emailVerifier.id\", { sparse: 1 });", "ApiHosts = new Mongo.Collection(\"apiHosts\", collectionOptions);\n// Allows defining some limited static behavior for an API host when accessed unauthenticated. This\n// mainly exists to allow backwards-compatibility with client applications that expect to be able\n// to probe an API host without authentication to determine capabilities such as DAV protocols\n// supported, before authenticating to perform real requests. An app can specify these properties\n// when creating an offerTemplate.\n//\n// Each contains:\n// _id: apiHostIdHashForToken() of the corresponding API token.\n// hash2: hash(hash(token)), aka hash(ApiToken._id). Used to allow ApiHosts to be cleaned\n// up when ApiTokens are deleted.\n// options: Specifies how to respond to unauthenticated OPTIONS requests on this host.\n// This is an object containing fields:\n// dav: List of strings specifying DAV header `compliance-class`es, e.g. \"1\" or\n// \"calendar-access\". https://tools.ietf.org/html/rfc4918#section-10.1\n// resources: Object mapping URL paths (including initial '/') to static HTTP responses to\n// give when those paths are accessed unauthenticated. Due to Mongo disliking '.'\n// and '$' in keys, these characters must be escaped as '\\uFF0E' and '\\uFF04'\n// (see SandstormDb.escapeMongoKey). Each value in this map is an object with\n// fields:\n// type: Content-Type.\n// language: Content-Language.\n// encoding: Content-Encoding.\n// body: Entity-body as a string or buffer.", "Notifications = new Mongo.Collection(\"notifications\", collectionOptions);\n// Notifications for a user.\n//\n// Each contains:\n// _id: random\n// grainId: The grain originating this notification, if any.\n// userId: Account ID of the user receiving the notification.\n// text: The JSON-ified LocalizedText to display in the notification.\n// isUnread: Boolean indicating if this notification is unread.\n// timestamp: Date when this notification was last updated\n// eventType: If this notification is due to an activity event, this is the numeric index\n// of the event type on the grain's ViewInfo.\n// count: The number of times this exact event has repeated. Identical events are\n// aggregated by incrementing the count.\n// initiatingIdentity: Identity ID of the user who initiated this notification.\n// initiatorAnonymous: True if the initiator is an anonymous user. If neither this nor\n// initiatingIdentity is present, the notification is not from a user.\n// path: Path inside the grain to which the user should be directed if they click on\n// the notification.\n// ongoing: If present, this is an ongoing notification, and this field contains an\n// ApiToken referencing the `OngoingNotification` capability.\n// admin: If present, this is a notification intended for an admin.\n// action: If present, this is a (string) link that the notification should direct the\n// admin to.\n// type: The type of notification -- currently can only be \"reportStats\".\n// appUpdates: If present, this is an app update notification. It is an object with the appIds\n// as keys.\n// $appId: The appId that has an outstanding update.\n// packageId: The packageId that it will update to.\n// name: The name of the app. (appTitle from package.manifest)\n// version: The app's version number. (appVersion from package.manifest)\n// marketingVersion: String marketing version of this app. (appMarketingVersion from package.manifest)\n// referral: If this boolean field is true, then treat this notification as a referral\n// notification. This causes text to be ignored, since we need custom logic.\n// mailingListBonus: Like `referral`, but notify the user about the mailing list bonus. This is\n// a one-time notification only to Oasis users who existed when the bonus program\n// was implemented.", "ActivitySubscriptions = new Mongo.Collection(\"activitySubscriptions\", collectionOptions);\n// Activity events to which a user is subscribed.\n//\n// Each contains:\n// _id: random\n// identityId: Who is subscribed.\n// grainId: Grain to which subscription applies.\n// threadPath: If present, the subscription is on a specific thread. Otherwise, it is on the\n// whole grain.\n// mute: If true, this is an anti-subscription -- matching events should NOT notify.\n// This allows is useful to express:\n// - A user wants to subscribe to a grain but mute a specific thread.\n// - The owner of a grain does not want notifications (normally, they are\n// implicitly subscribed).\n// - A user no longer wishes to be implicitly subscribed to threads in a grain on\n// which they comment, so they mute the grain.", "ActivitySubscriptions.ensureIndexOnServer(\"identityId\");\nActivitySubscriptions.ensureIndexOnServer({ \"grainId\": 1, \"threadPath\": 1 });", "StatsTokens = new Mongo.Collection(\"statsTokens\", collectionOptions);\n// Access tokens for the Stats collection\n//\n// These tokens are used for accessing the ActivityStats collection remotely\n// (ie. from a dashboard webapp)\n//\n// Each contains:\n// _id: The token. At least 128 bits entropy (Random.id(22)).", "Misc = new Mongo.Collection(\"misc\", collectionOptions);\n// Miscellaneous configuration and other settings\n//\n// This table is currently only used for persisting BASE_URL from one session to the next,\n// but in general any miscellaneous settings should go in here\n//\n// Each contains:\n// _id: The name of the setting. eg. \"BASE_URL\"\n// value: The value of the setting.", "Settings = new Mongo.Collection(\"settings\", collectionOptions);\n// Settings for this Sandstorm instance go here. They are configured through the adminSettings\n// route. This collection differs from misc in that any admin user can update it through the admin\n// interface.\n//\n// Each contains:\n// _id: The name of the setting. eg. \"smtpConfig\"\n// value: The value of the setting.\n// automaticallyReset: Sometimes the server needs to automatically reset a setting. When it does\n// so, it will also write an object to this field indicating why the reset was\n// needed. That object can have the following variants:\n// baseUrlChangedFrom: The reset was due to BASE_URL changing. This field contains a string\n// with the old BASE_URL.\n// preinstalledApps: A list of objects:\n// appId: The Packages.appId of the app to install\n// status: packageId\n// packageId: The Packages._id of the app to install\n//\n// potentially other fields that are unique to the setting", "Migrations = new Mongo.Collection(\"migrations\", collectionOptions);\n// This table tracks which migrations we have applied to this instance.\n// It contains a single entry:\n// _id: \"migrations_applied\"\n// value: The number of migrations this instance has successfully completed.", "StaticAssets = new Mongo.Collection(\"staticAssets\", collectionOptions);\n// Collection of static assets served up from the Sandstorm server's \"static\" host. We only\n// support relatively small assets: under 1MB each.\n//\n// Each contains:\n// _id: Random ID; will be used in the URL.\n// hash: A base64-encoded SHA-256 hash of the data, used to de-dupe.\n// mimeType: MIME type of the asset, suitable for Content-Type header.\n// encoding: Either \"gzip\" or not present, suitable for Content-Encoding header.\n// content: The asset content (byte buffer).\n// refcount: Number of places where this asset's ID appears in the database. Since Mongo doesn't\n// have transactions, this needs to bias towards over-counting; a backup GC could be used\n// to catch leaked assets, although it's probably not a big deal in practice.", "AssetUploadTokens = new Mongo.Collection(\"assetUploadTokens\", collectionOptions);\n// Collection of tokens representing a single-use permission to upload an asset, such as a new\n// profile picture.\n//\n// Each contains:\n// _id: Random ID.\n// purpose: Contains one of the following, indicating how the asset is to be used:\n// profilePicture: Indicates that the upload is a new profile picture. Contains fields:\n// userId: Account ID of user whose picture shall be replaced.\n// identityId: Which of the user's identities shall be updated.\n// expires: Time when this token will go away if unused.", "Plans = new Mongo.Collection(\"plans\", collectionOptions);\n// Subscription plans, which determine quota.\n//\n// Each contains:\n// _id: Plan ID, usually a short string like \"free\", \"standard\", \"large\", \"mega\", ...\n// storage: Number of bytes this user is allowed to store.\n// compute: Number of kilobyte-RAM-seconds this user is allowed to consume.\n// computeLabel: Label to display to the user describing this plan's compute units.\n// grains: Total number of grains this user can create (often `Infinity`).\n// price: Price per month in US cents.\n// hidden: If true, a user cannot switch to this plan, but some users may be on it and are\n// allowed to switch away.\n// title: Title from display purposes. If missing, default to capitalizing _id.", "AppIndex = new Mongo.Collection(\"appIndex\", collectionOptions);\n// A mirror of the data from the App Market index\n//\n// Each contains:\n// _id: the appId of the app\n// The rest of the fields are defined in src/sandstorm/app-index/app-index.capnp:AppIndexForMarket", "KeybaseProfiles = new Mongo.Collection(\"keybaseProfiles\", collectionOptions);\n// Cache of Keybase profile information. The profile for a user is re-fetched every time a package\n// by that user is installed, as well as if the keybase profile is requested and not already\n// present for some reason.\n//\n// Each contains:\n// _id: PGP key fingerprint (SHA-1, hex, all-caps)\n// displayName: Display name from Keybase. (NOT VERIFIED AT ALL.)\n// handle: Keybase handle.\n// proofs: The \"proofs_summary.all\" array from the Keybase lookup. See the non-existent Keybase\n// docs for details. We also add a boolean \"status\" field to each proof indicating whether\n// we have directly verified the proof ourselves. Its values may be \"unverified\" (Keybase\n// returned this but we haven't checked it directly), \"verified\" (we verified the proof and it\n// is valid), \"invalid\" (we checked the proof and it was definitely bogus), or \"checking\" (the\n// server is currently actively checking this proof). Note that if a check fails due to network\n// errors, the status goes back to \"unverified\".\n//\n// WARNING: Currently verification is NOT IMPLEMENTED, so all proofs will be \"unverified\"\n// for now and we just trust Keybase.", "FeatureKey = new Mongo.Collection(\"featureKey\", collectionOptions);\n// OBSOLETE: This was used to implement the Sandstorm for Work paywall, which has been removed.\n// Collection object still defined because it could have old data in it, for servers that used\n// to have a feature key.", "SetupSession = new Mongo.Collection(\"setupSession\", collectionOptions);\n// Responsible for storing information about setup sessions. Contains a single document with three\n// keys:\n//\n// _id: \"current-session\"\n// creationDate: Date object indicating when this session was created.\n// hashedSessionId: the sha256 of the secret session id that was returned to the client", "const DesktopNotifications = new Mongo.Collection(\"desktopNotifications\", collectionOptions);\n// Responsible for very short-lived queueing of desktop notification information.\n// Entries are removed when they are ~30 seconds old. This collection is a bit\n// odd in that it is intended primarily for edge-triggered communications, but\n// Meteor's collections aren't really designed to support that organization.\n// Fields for each :\n//\n// _id: String. Used as the tag to coordinate notification merging between browser tabs.\n// creationDate: Date object. indicating when this notification was posted.\n// userId: String. Account id to which this notification was published.\n// notificationId: String. ID of the matching event in the Notifications table to dismiss if this\n// notification is activated.\n// appActivity: Object with fields:\n// user: Optional Object. Not present if this notification wasn't generated by a user. If\n// present, it will have one of the following shapes:\n// { anonymous: true } if this notification was generated by an anonymous user. Otherwise:\n// {\n// identityId: String The user's identity ID.\n// name: String The user's display name.\n// avatarUrl: String The URL for the user's profile picture.\n// },\n// grainId: String, Which grain this action took place on\n// path: String, The path of the notification.\n// body: Util.LocalizedText, The main body of the activity event.\n// actionText: Util.LocalizedText, What action the user took, e.g.\n// { defaultText: \"added a comment\" }", "const StandaloneDomains = new Mongo.Collection(\"standaloneDomains\", collectionOptions);\n// A standalone domain that points to a single share link. These domains act a little different\n// than a normal shared Sandstorm grain. They completely drop any Sandstorm topbar/sidebar, and at\n// first glance look completely like a non-Sandstorm hosted webserver. The apps instead act in\n// concert with Sandstorm through the postMessage API, which allows it to do things like prompt for\n// login.\n// Fields for each :\n//\n// _id: String. The domain name to use.\n// token: String. _id of a sharing token (it must be a webkey).", "if (Meteor.isServer) {\n Meteor.publish(\"credentials\", function () {\n // Data needed for isSignedUp() and isAdmin() to work.", " if (this.userId) {\n const db = this.connection.sandstormDb;\n return [\n Meteor.users.find({ _id: this.userId },\n { fields: { signupKey: 1, isAdmin: 1, expires: 1, storageUsage: 1,\n plan: 1, planBonus: 1, hasCompletedSignup: 1, experiments: 1,\n referredIdentityIds: 1, cachedStorageQuota: 1, suspended: 1, }, }),\n db.collections.plans.find(),\n ];\n } else {\n return [];\n }\n });\n}", "const countReferrals = function (user) {\n const referredIdentityIds = user.referredIdentityIds;\n return (referredIdentityIds && referredIdentityIds.length || 0);\n};", "const calculateReferralBonus = function (user) {\n // This function returns an object of the form:\n //\n // - {grains: 0, storage: 0}\n //\n // which are extra resources this account gets as part of participating in the referral\n // program. (Storage is measured in bytes, as usual for plans.)", " // TODO(cleanup): Consider moving referral bonus logic into Oasis payments module (since it's\n // payments-specific) and aggregating into `planBonus`.", " // Authorization note: Only call this if accountId is the current user!\n const isPaid = (user.plan && user.plan !== \"free\");", " successfulReferralsCount = countReferrals(user);\n if (isPaid) {\n const maxPaidStorageBonus = 30 * 1e9;\n return { grains: 0,\n storage: Math.min(\n successfulReferralsCount * 2 * 1e9,\n maxPaidStorageBonus), };\n } else {\n const maxFreeStorageBonus = 2 * 1e9;\n const bonus = {\n storage: Math.min(\n successfulReferralsCount * 50 * 1e6,\n maxFreeStorageBonus),\n };\n if (successfulReferralsCount > 0) {\n bonus.grains = Infinity;\n } else {\n bonus.grains = 0;\n }", " return bonus;\n }\n};", "isAdmin = function () {\n // Returns true if the user is the administrator.", " const user = Meteor.user();\n if (user && user.isAdmin) {\n return true;\n } else {\n return false;\n }\n};", "isAdminById = function (id) {\n // Returns true if the user's id is the administrator.", " const user = Meteor.users.findOne({ _id: id }, { fields: { isAdmin: 1 } });\n if (user && user.isAdmin) {\n return true;\n } else {\n return false;\n }\n};", "findAdminUserForToken = function (token) {\n if (!token.requirements) {\n return;\n }", " const requirements = token.requirements.filter(function (requirement) {\n return \"userIsAdmin\" in requirement;\n });", " if (requirements.length > 1) {\n return;\n }", " if (requirements.length === 0) {\n return;\n }", " return requirements[0].userIsAdmin;\n};", "const wildcardHost = Meteor.settings.public.wildcardHost.toLowerCase().split(\"*\");", "if (wildcardHost.length != 2) {\n throw new Error(\"Wildcard host must contain exactly one asterisk.\");\n}", "matchWildcardHost = function (host) {\n // See if the hostname is a member of our wildcard. If so, extract the ID.", " // We remove everything after the first \":\" character so that our\n // comparison logic ignores port numbers.\n const prefix = wildcardHost[0];\n const suffix = wildcardHost[1].split(\":\")[0];\n const hostSansPort = host.split(\":\")[0];", " if (hostSansPort.lastIndexOf(prefix, 0) >= 0 &&\n hostSansPort.indexOf(suffix, -suffix.length) >= 0 &&\n hostSansPort.length >= prefix.length + suffix.length) {\n const id = hostSansPort.slice(prefix.length, -suffix.length);\n if (id.match(/^[-a-z0-9]*$/)) {\n return id;\n }\n }", " return null;\n};", "makeWildcardHost = function (id) {\n return wildcardHost[0] + id + wildcardHost[1];\n};", "const isApiHostId = function (hostId) {\n if (hostId) {\n const split = hostId.split(\"-\");\n if (split[0] === \"api\") return split[1] || \"*\";\n }", " return false;\n};", "const isTokenSpecificHostId = function (hostId) {\n return hostId.lastIndexOf(\"api-\", 0) === 0;\n};", "let apiHostIdHashForToken;\nif (Meteor.isServer) {\n const Crypto = Npm.require(\"crypto\");\n apiHostIdHashForToken = function (token) {\n // Given an API token, compute the host ID that must be used when requesting this token.", " // We add a leading 'x' to the hash so that knowing the hostname alone is not sufficient to\n // find the corresponding API token in the ApiTokens table (whose _id values are also hashes\n // of tokens). This doesn't technically add any security, but helps prove that we don't have\n // any bugs which would allow someone who knows only the hostname to access the app API.\n return Crypto.createHash(\"sha256\").update(\"x\" + token).digest(\"hex\").slice(0, 32);\n };\n} else {\n apiHostIdHashForToken = function (token) {\n // Given an API token, compute the host ID that must be used when requesting this token.", " // We add a leading 'x' to the hash so that knowing the hostname alone is not sufficient to\n // find the corresponding API token in the ApiTokens table (whose _id values are also hashes\n // of tokens). This doesn't technically add any security, but helps prove that we don't have\n // any bugs which would allow someone who knows only the hostname to access the app API.\n return SHA256(\"x\" + token).slice(0, 32);\n };\n}", "const apiHostIdForToken = function (token) {\n return \"api-\" + apiHostIdHashForToken(token);\n};", "const makeApiHost = function (token) {\n return makeWildcardHost(apiHostIdForToken(token));\n};", "if (Meteor.isServer) {\n const Url = Npm.require(\"url\");\n getWildcardOrigin = function () {\n // The wildcard URL can be something like \"foo-*-bar.example.com\", but sometimes when we're\n // trying to specify a pattern matching hostnames (say, a Content-Security-Policy directive),\n // an astrisk is only allowed as the first character and must be followed by a period. So we need\n // \"*.example.com\" instead -- which matches more than we actually want, but is the best we can\n // really do. We also add the protocol to the front (again, that's what CSP wants).", " // TODO(cleanup): `protocol` is computed in other files, like proxy.js. Put it somewhere common.\n const protocol = Url.parse(process.env.ROOT_URL).protocol;", " const dotPos = wildcardHost[1].indexOf(\".\");\n if (dotPos < 0) {\n return protocol + \"//*\";\n } else {\n return protocol + \"//*\" + wildcardHost[1].slice(dotPos);\n }\n };\n}", "SandstormDb = function (quotaManager) {\n // quotaManager is an object with the following method:\n // updateUserQuota: It is provided two arguments\n // db: This SandstormDb object\n // user: A collections.users account object\n // and returns a quota object:\n // storage: A number (can be Infinity)\n // compute: A number (can be Infinity)\n // grains: A number (can be Infinity)", " this.quotaManager = quotaManager;\n this.collections = {\n // Direct access to underlying collections. DEPRECATED, but better than accessing the top-level\n // collection globals directly.\n //\n // TODO(cleanup): Over time, we will provide methods covering each supported query and remove\n // direct access to the collections.\n users: Meteor.users,", " packages: Packages,\n devPackages: DevPackages,\n userActions: UserActions,\n grains: Grains,\n roleAssignments: RoleAssignments, // Deprecated, only used by the migration that eliminated it.\n contacts: Contacts,\n sessions: Sessions,\n signupKeys: SignupKeys,\n activityStats: ActivityStats,\n deleteStats: DeleteStats,\n fileTokens: FileTokens,\n apiTokens: ApiTokens,\n apiHosts: ApiHosts,\n notifications: Notifications,\n activitySubscriptions: ActivitySubscriptions,\n statsTokens: StatsTokens,\n misc: Misc,\n settings: Settings,\n migrations: Migrations,\n staticAssets: StaticAssets,\n assetUploadTokens: AssetUploadTokens,\n plans: Plans,\n appIndex: AppIndex,\n keybaseProfiles: KeybaseProfiles,\n setupSession: SetupSession,\n desktopNotifications: DesktopNotifications,\n standaloneDomains: StandaloneDomains,\n };\n};", "// TODO(cleanup): These methods should not be defined freestanding and should use collection\n// objects created in SandstormDb's constructor rather than globals.", "_.extend(SandstormDb.prototype, {\n isAdmin: isAdmin,\n isAdminById: isAdminById,\n findAdminUserForToken: findAdminUserForToken,\n matchWildcardHost: matchWildcardHost,\n makeWildcardHost: makeWildcardHost,\n isApiHostId: isApiHostId,\n isTokenSpecificHostId: isTokenSpecificHostId,\n apiHostIdHashForToken: apiHostIdHashForToken,\n apiHostIdForToken: apiHostIdForToken,\n makeApiHost: makeApiHost,\n allowDevAccounts() {\n const setting = this.collections.settings.findOne({ _id: \"devAccounts\" });\n if (setting) {\n return setting.value;\n } else {\n return Meteor.settings && Meteor.settings.public &&\n Meteor.settings.public.allowDevAccounts;\n }\n },", " roleAssignmentPattern: {\n none: Match.Optional(null),\n allAccess: Match.Optional(null),\n roleId: Match.Optional(Match.Integer),\n addPermissions: Match.Optional([Boolean]),\n removePermissions: Match.Optional([Boolean]),\n },", " isDemoUser() {\n // Returns true if this is a demo user.", " const user = Meteor.user();\n if (user && user.expires) {\n return true;\n } else {\n return false;\n }\n },", " isSignedUp() {\n const user = Meteor.user();\n return this.isAccountSignedUp(user);\n },", " isAccountSignedUp(user) {\n // Returns true if the user has presented an invite key.", " if (!user) return false; // not signed in", " if (!user.loginIdentities) return false; // not an account", " if (user.expires) return false; // demo user.", " if (Meteor.settings.public.allowUninvited) return true; // all accounts qualify", " if (user.signupKey) return true; // user is invited", " if (this.isUserInOrganization(user)) return true;", " return false;\n },", " isSignedUpOrDemo() {\n const user = Meteor.user();\n return this.isAccountSignedUpOrDemo(user);\n },", " isAccountSignedUpOrDemo(user) {\n if (!user) return false; // not signed in", " if (!user.loginIdentities) return false; // not an account", " if (user.expires) return true; // demo user.", " if (Meteor.settings.public.allowUninvited) return true; // all accounts qualify", " if (user.signupKey) return true; // user is invited", " if (this.isUserInOrganization(user)) return true;", " return false;\n },", " isIdentityInOrganization(identity) {\n if (!identity || !identity.services) {\n return false;\n }", " const orgMembership = this.getOrganizationMembership();\n const googleEnabled = orgMembership && orgMembership.google && orgMembership.google.enabled;\n const googleDomain = orgMembership && orgMembership.google && orgMembership.google.domain;\n const emailEnabled = orgMembership && orgMembership.emailToken && orgMembership.emailToken.enabled;\n const emailDomain = orgMembership && orgMembership.emailToken && orgMembership.emailToken.domain;\n const ldapEnabled = orgMembership && orgMembership.ldap && orgMembership.ldap.enabled;\n const samlEnabled = orgMembership && orgMembership.saml && orgMembership.saml.enabled;\n if (emailEnabled && emailDomain && identity.services.email) {\n const domainSuffixes = emailDomain.split(/\\s*,\\s*/);\n for (let i = 0; i < domainSuffixes.length; i++) {\n const suffix = domainSuffixes[i];\n const domain = identity.services.email.email.toLowerCase().split(\"@\").pop();\n if (suffix.startsWith(\"*.\")) {\n if (domain.endsWith(suffix.substr(1))) {\n return true;\n }\n } else if (domain === suffix) {\n return true;\n }\n }\n } else if (ldapEnabled && identity.services.ldap) {\n return true;\n } else if (samlEnabled && identity.services.saml) {\n return true;\n } else if (googleEnabled && googleDomain && identity.services.google && identity.services.google.hd) {\n if (identity.services.google.hd.toLowerCase() === googleDomain) {\n return true;\n }\n }", " return false;\n },", " isUserInOrganization(user) {\n for (let i = 0; i < user.loginIdentities.length; i++) {\n let identity = Meteor.users.findOne({ _id: user.loginIdentities[i].id });\n if (this.isIdentityInOrganization(identity)) {\n return true;\n }\n }", " return false;\n },\n});", "if (Meteor.isServer) {\n SandstormDb.prototype.getWildcardOrigin = getWildcardOrigin;", " const Crypto = Npm.require(\"crypto\");\n SandstormDb.prototype.removeApiTokens = function (query) {\n // Remove all API tokens matching the query, making sure to clean up ApiHosts as well.", " this.collections.apiTokens.find(query).forEach((token) => {\n // Clean up ApiHosts for webkey tokens.\n if (token.hasApiHost) {\n const hash2 = Crypto.createHash(\"sha256\").update(token._id).digest(\"base64\");\n this.collections.apiHosts.remove({ hash2: hash2 });\n }", " // TODO(soon): Drop remote OAuth tokens for frontendRef.http. Unfortunately the way to do\n // this is different for every service. :( Also we may need to clarify with the \"bearer\"\n // type whether or not the token is \"owned\" by us...\n });", " this.collections.apiTokens.remove(query);\n };\n}", "// TODO(someday): clean this up. Logic for building static asset urls on client and server\n// appears all over the codebase.\nlet httpProtocol;\nif (Meteor.isServer) {\n const Url = Npm.require(\"url\");\n httpProtocol = Url.parse(process.env.ROOT_URL).protocol;\n} else {\n httpProtocol = window.location.protocol;\n}", "// =======================================================================================\n// Below this point are newly-written or refactored functions.", "_.extend(SandstormDb.prototype, {\n getUser(userId) {\n check(userId, Match.OneOf(String, undefined, null));\n if (userId) {\n return Meteor.users.findOne(userId);\n }\n },", " getIdentity(identityId) {\n check(identityId, String);\n const identity = Meteor.users.findOne({ _id: identityId });\n if (identity) {\n SandstormDb.fillInProfileDefaults(identity);\n SandstormDb.fillInIntrinsicName(identity);\n SandstormDb.fillInPictureUrl(identity);\n return identity;\n }\n },", " userHasIdentity(userId, identityId) {\n check(userId, String);\n check(identityId, String);", " if (userId === identityId) return true;", " const user = Meteor.users.findOne(userId);\n return SandstormDb.getUserIdentityIds(user).indexOf(identityId) != -1;\n },", " userGrains(userId, options) {\n check(userId, Match.OneOf(String, undefined, null));\n check(options, Match.OneOf(undefined, null,\n { includeTrashOnly: Match.Optional(Boolean), includeTrash: Match.Optional(Boolean), }));", " const query = { userId: userId };\n if (options && options.includeTrashOnly) {\n query.trashed = { $exists: true };\n } else if (options && options.includeTrash) {\n // Keep query as-is.\n } else {\n query.trashed = { $exists: false };\n }", " return this.collections.grains.find(query);\n },", " currentUserGrains(options) {\n return this.userGrains(Meteor.userId(), options);\n },", " getGrain(grainId) {\n check(grainId, String);\n return this.collections.grains.findOne(grainId);\n },", " userApiTokens(userId, trashed) {\n check(userId, Match.OneOf(String, undefined, null));\n check(trashed, Match.OneOf(Boolean, undefined, null));\n const identityIds = SandstormDb.getUserIdentityIds(this.getUser(userId));\n return this.collections.apiTokens.find({\n \"owner.user.identityId\": { $in: identityIds },\n trashed: { $exists: !!trashed },\n });\n },", " currentUserApiTokens(trashed) {\n return this.userApiTokens(Meteor.userId(), trashed);\n },", " userActions(user) {\n return this.collections.userActions.find({ userId: user });\n },", " currentUserActions() {\n return this.userActions(Meteor.userId());\n },", " iconSrcForPackage(pkg, usage) {\n return Identicon.iconSrcForPackage(pkg, usage, httpProtocol + \"//\" + this.makeWildcardHost(\"static\"));\n },", " getDenormalizedGrainInfo(grainId) {\n const grain = this.getGrain(grainId);\n let pkg = this.collections.packages.findOne(grain.packageId);", " if (!pkg) {\n pkg = this.collections.devPackages.findOne(grain.packageId);\n }", " const appTitle = (pkg && pkg.manifest && pkg.manifest.appTitle) || { defaultText: \"\" };\n const grainInfo = { appTitle: appTitle };", " if (pkg && pkg.manifest && pkg.manifest.metadata && pkg.manifest.metadata.icons) {\n const icons = pkg.manifest.metadata.icons;\n const icon = icons.grain || icons.appGrid;\n if (icon) {\n grainInfo.icon = icon;\n }\n }", " // Only provide an app ID if we have no icon asset to provide and need to offer an identicon.\n if (!grainInfo.icon && pkg) {\n grainInfo.appId = pkg.appId;\n }", " return grainInfo;\n },", " getPlan(id, user) {\n check(id, String);", " // `user`, if provided, is the user observing the plan. This matters only for checking if the\n // user is in an experiment.", " const plan = this.collections.plans.findOne(id);\n if (!plan) {\n throw new Error(\"no such plan: \" + id);\n }", " if (plan._id === \"free\") {\n user = user || Meteor.user();\n if (user && user.experiments &&\n typeof user.experiments.freeGrainLimit === \"number\") {\n plan.grains = user.experiments.freeGrainLimit;\n }\n }", " return plan;\n },", " listPlans(user) {\n user = user || Meteor.user();\n if (user && user.experiments &&\n typeof user.experiments.freeGrainLimit === \"number\") {\n return this.collections.plans.find({}, { sort: { price: 1 } })\n .map(plan => {\n if (plan._id === \"free\") {\n plan.grains = user.experiments.freeGrainLimit;\n }", " return plan;\n });\n } else {\n return this.collections.plans.find({}, { sort: { price: 1 } }).fetch();\n }\n },", " getMyPlan() {\n const user = Meteor.user();\n return user && this.collections.plans.findOne(user.plan || \"free\");\n },", " getMyReferralBonus(user) {\n // This function is called from the server and from the client, similar to getMyPlan().\n //\n // The parameter may be omitted in which case the current user is assumed.", " return calculateReferralBonus(user || Meteor.user());\n },", " getMyUsage(user) {\n user = user || Meteor.user();\n if (user && (Meteor.isServer || user.pseudoUsage)) {\n if (Meteor.isClient) {\n // Filled by pseudo-subscription to \"getMyUsage\". WARNING: The subscription is currently\n // not reactive.\n return user.pseudoUsage;\n } else {\n return {\n grains: this.collections.grains.find({ userId: user._id }).count(),\n storage: user.storageUsage || 0,\n compute: 0, // not tracked yet\n };\n }\n } else {\n return { grains: 0, storage: 0, compute: 0 };\n }\n },", " isUninvitedFreeUser() {\n if (!Meteor.settings.public.allowUninvited) return false;", " const user = Meteor.user();\n return user && !user.expires && (!user.plan || user.plan === \"free\");\n },", " getSetting(name) {\n const setting = this.collections.settings.findOne(name);\n return setting && setting.value;\n },", " getSettingWithFallback(name, fallbackValue) {\n const value = this.getSetting(name);\n if (value === undefined) {\n return fallbackValue;\n }", " return value;\n },", " addUserActions(userId, packageId, simulation) {\n check(userId, String);\n check(packageId, String);", " const pack = this.collections.packages.findOne({ _id: packageId });\n if (pack) {\n // Remove old versions.\n const numRemoved = this.collections.userActions.remove({ userId: userId, appId: pack.appId });", " // Install new.\n const actions = pack.manifest.actions;\n for (const i in actions) {\n const action = actions[i];\n if (\"none\" in action.input) {\n const userAction = {\n userId: userId,\n packageId: pack._id,\n appId: pack.appId,\n appTitle: pack.manifest.appTitle,\n appMarketingVersion: pack.manifest.appMarketingVersion,\n appVersion: pack.manifest.appVersion,\n title: action.title,\n nounPhrase: action.nounPhrase,\n command: action.command,\n };\n this.collections.userActions.insert(userAction);\n } else {\n // TODO(someday): Implement actions with capability inputs.\n }\n }", " if (numRemoved > 0 && !simulation) {\n this.deleteUnusedPackages(pack.appId);\n }\n }\n },", " sendAdminNotification(type, action) {\n Meteor.users.find({ isAdmin: true }, { fields: { _id: 1 } }).forEach(function (user) {\n Notifications.insert({\n admin: { action, type },\n userId: user._id,\n timestamp: new Date(),\n isUnread: true,\n });\n });\n },", " getKeybaseProfile(keyFingerprint) {\n return this.collections.keybaseProfiles.findOne(keyFingerprint) || {};\n },", " getServerTitle() {\n const setting = this.collections.settings.findOne({ _id: \"serverTitle\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getSmtpConfig() {\n const setting = this.collections.settings.findOne({ _id: \"smtpConfig\" });\n return setting ? setting.value : undefined; // undefined if subscription is not ready.\n },", " getReturnAddress() {\n const config = this.getSmtpConfig();\n return config && config.returnAddress || \"\"; // empty if subscription is not ready.\n },", " getReturnAddressWithDisplayName(identityId) {\n check(identityId, String);\n const identity = this.getIdentity(identityId);\n const displayName = identity.profile.name + \" (via \" + this.getServerTitle() + \")\";", " // First remove any instances of characters that cause trouble for SimpleSmtp. Ideally,\n // we could escape such characters with a backslash, but that does not seem to help here.", " // TODO(cleanup): Unclear whether this sanitization is still necessary now that we return a\n // structured object and have moved to nodemailer. I'm not touching it for now.", " const sanitized = displayName.replace(/\"|<|>|\\\\|\\r/g, \"\");\n", " return { name: sanitized, address: this.getReturnAddress() };", " },", " getPrimaryEmail(accountId, identityId) {\n check(accountId, String);\n check(identityId, String);", " const identity = this.getIdentity(identityId);\n const senderEmails = SandstormDb.getVerifiedEmails(identity);\n const senderPrimaryEmail = _.findWhere(senderEmails, { primary: true });\n const accountPrimaryEmailAddress = this.getUser(accountId).primaryEmail;\n if (_.findWhere(senderEmails, { email: accountPrimaryEmailAddress })) {\n return accountPrimaryEmailAddress;\n } else if (senderPrimaryEmail) {\n return senderPrimaryEmail.email;\n } else {\n return null;\n }\n },", " incrementDailySentMailCount(accountId) {\n check(accountId, String);", " const DAILY_LIMIT = 50;\n const result = Meteor.users.findAndModify({\n query: { _id: accountId },\n update: {\n $inc: {\n dailySentMailCount: 1,\n },\n },\n fields: { dailySentMailCount: 1 },\n });", " if (!result.ok) {\n throw new Error(\"Couldn't update daily sent mail count.\");\n }", " const user = result.value;\n if (user.dailySentMailCount >= DAILY_LIMIT) {\n throw new Error(\n \"Sorry, you've reached your e-mail sending limit for today. Currently, Sandstorm \" +\n \"limits each user to \" + DAILY_LIMIT + \" e-mails per day for spam control reasons. \" +\n \"Please feel free to contact us if this is a problem.\");\n }\n },", " getLdapUrl() {\n const setting = this.collections.settings.findOne({ _id: \"ldapUrl\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getLdapBase() {\n const setting = this.collections.settings.findOne({ _id: \"ldapBase\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getLdapDnPattern() {\n const setting = this.collections.settings.findOne({ _id: \"ldapDnPattern\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getLdapSearchUsername() {\n const setting = this.collections.settings.findOne({ _id: \"ldapSearchUsername\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getLdapNameField() {\n const setting = this.collections.settings.findOne({ _id: \"ldapNameField\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getLdapEmailField() {\n const setting = this.collections.settings.findOne({ _id: \"ldapEmailField\" });\n return setting ? setting.value : \"mail\";\n // default to \"mail\". This setting was added later, and so could potentially be unset.\n },", " getLdapExplicitDnSelected() {\n const setting = this.collections.settings.findOne({ _id: \"ldapExplicitDnSelected\" });\n return setting && setting.value;\n },", " getLdapFilter() {\n const setting = this.collections.settings.findOne({ _id: \"ldapFilter\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getLdapSearchBindDn() {\n const setting = this.collections.settings.findOne({ _id: \"ldapSearchBindDn\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getLdapSearchBindPassword() {\n const setting = this.collections.settings.findOne({ _id: \"ldapSearchBindPassword\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getLdapCaCert() {\n const setting = this.collections.settings.findOne({ _id: \"ldapCaCert\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getOrganizationMembership() {\n const setting = this.collections.settings.findOne({ _id: \"organizationMembership\" });\n return setting && setting.value;\n },", " getOrganizationEmailEnabled() {\n const membership = this.getOrganizationMembership();\n return membership && membership.emailToken && membership.emailToken.enabled;\n },", " getOrganizationEmailDomain() {\n const membership = this.getOrganizationMembership();\n return membership && membership.emailToken && membership.emailToken.domain;\n },", " getOrganizationGoogleEnabled() {\n const membership = this.getOrganizationMembership();\n return membership && membership.google && membership.google.enabled;\n },", " getOrganizationGoogleDomain() {\n const membership = this.getOrganizationMembership();\n return membership && membership.google && membership.google.domain;\n },", " getOrganizationLdapEnabled() {\n const membership = this.getOrganizationMembership();\n return membership && membership.ldap && membership.ldap.enabled;\n },", " getOrganizationSamlEnabled() {\n const membership = this.getOrganizationMembership();\n return membership && membership.saml && membership.saml.enabled;\n },", " getOrganizationDisallowGuests() {\n return this.getOrganizationDisallowGuestsRaw();\n },", " getOrganizationDisallowGuestsRaw() {\n const setting = this.collections.settings.findOne({ _id: \"organizationSettings\" });\n return setting && setting.value && setting.value.disallowGuests;\n },", " getOrganizationShareContacts() {\n return this.getOrganizationShareContactsRaw();\n },", " getOrganizationShareContactsRaw() {\n const setting = this.collections.settings.findOne({ _id: \"organizationSettings\" });\n if (!setting || !setting.value || setting.value.shareContacts === undefined) {\n // default to true if undefined\n return true;\n } else {\n return setting.value.shareContacts;\n }\n },", " getSamlEntryPoint() {\n const setting = this.collections.settings.findOne({ _id: \"samlEntryPoint\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getSamlLogout() {\n const setting = this.collections.settings.findOne({ _id: \"samlLogout\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getSamlPublicCert() {\n const setting = this.collections.settings.findOne({ _id: \"samlPublicCert\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " getSamlEntityId() {\n const setting = this.collections.settings.findOne({ _id: \"samlEntityId\" });\n return setting ? setting.value : \"\"; // empty if subscription is not ready.\n },", " userHasSamlLoginIdentity() {\n const user = Meteor.user();\n if (!user.loginIdentities) {\n return false;\n }", " let hasSaml = false;\n user.loginIdentities.forEach((identity) => {\n if (Meteor.users.findOne({ _id: identity.id }).services.saml) {\n hasSaml = true;\n }\n });", " return hasSaml;\n },", " getActivitySubscriptions(grainId, threadPath) {\n return this.collections.activitySubscriptions.find({\n grainId: grainId,\n threadPath: threadPath || { $exists: false },\n }, {\n fields: { identityId: 1, mute: 1, _id: 0 },\n }).fetch();\n },", " subscribeToActivity(identityId, grainId, threadPath) {\n // Subscribe the given identity to activity events with the given grainId and (optional)\n // threadPath -- unless the identity has previously muted this grainId/threadPath, in which\n // case do nothing.", " const record = { identityId, grainId };\n if (threadPath) {\n record.threadPath = threadPath;\n }", " // The $set here is redundant since an upsert automatically initializes a new record to contain\n // the fields from the query, but if we try to do { $set: {} } Mongo throws an exception, and\n // if we try to just pass {}, Mongo interprets it as \"replace the record with an empty record\".\n // What a wonderful query language.\n this.collections.activitySubscriptions.upsert(record, { $set: record });\n },", " muteActivity(identityId, grainId, threadPath) {\n // Mute notifications for the given identity originating from the given grainId and\n // (optional) threadPath.", " const record = { identityId, grainId };\n if (threadPath) {\n record.threadPath = threadPath;\n }", " this.collections.activitySubscriptions.upsert(record, { $set: { mute: true } });\n },", " updateAppIndex() {\n const appUpdatesEnabledSetting = this.collections.settings.findOne({ _id: \"appUpdatesEnabled\" });\n const appUpdatesEnabled = appUpdatesEnabledSetting && appUpdatesEnabledSetting.value;\n if (!appUpdatesEnabled) {\n // It's much simpler to check appUpdatesEnabled here rather than reactively deactivate the\n // timer that triggers this call.\n return;\n }", " const appIndexUrl = this.collections.settings.findOne({ _id: \"appIndexUrl\" }).value;\n const appIndex = this.collections.appIndex;\n const data = HTTP.get(appIndexUrl + \"/apps/index.json\").data;\n const preinstalledAppIds = this.getAllPreinstalledAppIds();\n // We make sure to get all preinstalled appIds, even ones that are currently\n // downloading/failed.\n data.apps.forEach((app) => {\n app._id = app.appId;", " const oldApp = appIndex.findOne({ _id: app.appId });\n app.hasSentNotifications = false;\n appIndex.upsert({ _id: app._id }, app);\n const isAppPreinstalled = _.contains(preinstalledAppIds, app.appId);\n if ((!oldApp || app.versionNumber > oldApp.versionNumber) &&\n (this.collections.userActions.findOne({ appId: app.appId }) ||\n isAppPreinstalled)) {\n const pack = this.collections.packages.findOne({ _id: app.packageId });\n const url = appIndexUrl + \"/packages/\" + app.packageId;\n if (pack) {\n if (pack.status === \"ready\") {\n if (pack.appId && pack.appId !== app.appId) {\n console.error(\"app index returned app ID and package ID that don't match:\",\n JSON.stringify(app));\n } else {\n this.sendAppUpdateNotifications(app.appId, app.packageId, app.name, app.versionNumber,\n app.version);\n if (isAppPreinstalled) {\n this.setPreinstallAppAsReady(app.appId, app.packageId);\n }\n }\n } else {\n const result = this.collections.packages.findAndModify({\n query: { _id: app.packageId },\n update: { $set: { isAutoUpdated: true } },\n });", " if (!result.ok) {\n return;\n }", " const newPack = result.value;\n if (newPack.status === \"ready\") {\n // The package was marked as ready before we applied isAutoUpdated=true. We should send\n // notifications ourselves to be sure there's no timing issue (sending more than one is\n // fine, since it will de-dupe).\n if (pack.appId && pack.appId !== app.appId) {\n console.error(\"app index returned app ID and package ID that don't match:\",\n JSON.stringify(app));\n } else {\n this.sendAppUpdateNotifications(app.appId, app.packageId, app.name, app.versionNumber,\n app.version);\n if (isAppPreinstalled) {\n this.setPreinstallAppAsReady(app.appId, app.packageId);\n }\n }\n } else if (newPack.status === \"failed\") {\n // If the package has failed, retry it\n this.startInstall(app.packageId, url, true, true);\n }\n }\n } else {\n this.startInstall(app.packageId, url, false, true);\n }\n }\n });\n },", " isPackagePreinstalled(packageId) {\n return this.collections.settings.find({ _id: \"preinstalledApps\", \"value.packageId\": packageId }).count() === 1;\n },", " getAppIdForPreinstalledPackage(packageId) {\n const setting = this.collections.settings.findOne({ _id: \"preinstalledApps\", \"value.packageId\": packageId },\n { fields: { \"value.$\": 1 } });\n // value.$ causes mongo to transform the result and only return the first matching element in\n // the array\n return setting && setting.value && setting.value[0] && setting.value[0].appId;\n },", " getPackageIdForPreinstalledApp(appId) {\n const setting = this.collections.settings.findOne({ _id: \"preinstalledApps\", \"value.appId\": appId },\n { fields: { \"value.$\": 1 } });\n // value.$ causes mongo to transform the result and only return the first matching element in\n // the array\n return setting && setting.value && setting.value[0] && setting.value[0].packageId;\n },", " getReadyPreinstalledAppIds() {\n const setting = this.collections.settings.findOne({ _id: \"preinstalledApps\" });\n const ret = setting && setting.value || [];\n return _.chain(ret)\n .filter((app) => { return app.status === \"ready\"; })\n .map((app) => { return app.appId; })\n .value();\n },", " getAllPreinstalledAppIds() {\n const setting = this.collections.settings.findOne({ _id: \"preinstalledApps\" });\n const ret = setting && setting.value || [];\n return _.map(ret, (app) => { return app.appId; });\n },", " preinstallAppsForUser(userId) {\n const appIds = this.getReadyPreinstalledAppIds();\n appIds.forEach((appId) => {\n try {\n this.addUserActions(userId, this.getPackageIdForPreinstalledApp(appId));\n } catch (e) {\n console.error(\"failed to install app for user:\", e);\n }\n });\n },", " setPreinstallAppAsDownloading(appId, packageId) {\n this.collections.settings.update(\n { _id: \"preinstalledApps\", \"value.appId\": appId, \"value.packageId\": packageId },\n { $set: { \"value.$.status\": \"downloading\" } });\n },", " setPreinstallAppAsReady(appId, packageId) {\n // This function both sets the appId as ready and updates the packageId for the given appId\n // Setting the packageId is especially useful in installer.js, as it always ensures the\n // latest installed package will be set as ready.\n this.collections.settings.update(\n { _id: \"preinstalledApps\", \"value.appId\": appId },\n { $set: { \"value.$.status\": \"ready\", \"value.$.packageId\": packageId } });\n },", " ensureAppPreinstall(appId, packageId) {\n check(appId, String);\n const appIndexUrl = this.collections.settings.findOne({ _id: \"appIndexUrl\" }).value;\n const pack = this.collections.packages.findOne({ _id: packageId });\n const url = appIndexUrl + \"/packages/\" + packageId;\n if (pack && pack.status === \"ready\") {\n this.setPreinstallAppAsReady(appId, packageId);\n } else if (pack && pack.status === \"failed\") {\n this.setPreinstallAppAsDownloading(appId, packageId);\n this.startInstall(packageId, url, true, false);\n } else {\n this.setPreinstallAppAsDownloading(appId, packageId);\n this.startInstall(packageId, url, false, false);\n }\n },", " setPreinstalledApps(appAndPackageIds) {\n // appAndPackageIds: A List[Object] where each element has fields:\n // appId: The Packages.appId of the app to install\n // packageId: The Packages._id of the app to install\n check(appAndPackageIds, [{ appId: String, packageId: String, }]);", " // Start by clearing out the setting. We'll push appIds one by one to it\n this.collections.settings.upsert({ _id: \"preinstalledApps\" }, { $set: {\n value: appAndPackageIds.map((data) => {\n return {\n appId: data.appId,\n status: \"notReady\",\n packageId: data.packageId,\n };\n }),\n }, });\n appAndPackageIds.forEach((data) => {\n this.ensureAppPreinstall(data.appId, data.packageId);\n });\n },", " getProductivitySuiteAppIds() {\n return [\n \"8aspz4sfjnp8u89000mh2v1xrdyx97ytn8hq71mdzv4p4d8n0n3h\", // Davros\n \"h37dm17aa89yrd8zuqpdn36p6zntumtv08fjpu8a8zrte7q1cn60\", // Etherpad\n \"vfnwptfn02ty21w715snyyczw0nqxkv3jvawcah10c6z7hj1hnu0\", // Rocket.Chat\n \"m86q05rdvj14yvn78ghaxynqz7u2svw6rnttptxx49g1785cdv1h\", // Wekan\n ];\n },", " getSystemSuiteAppIds() {\n return [\n \"s3u2xgmqwznz2n3apf30sm3gw1d85y029enw5pymx734cnk5n78h\", // Collections\n ];\n },", " isPreinstalledAppsReady() {\n const setting = this.collections.settings.findOne({ _id: \"preinstalledApps\" });\n if (!setting || !setting.value) {\n return true;\n }", " const packageIds = _.pluck(setting.value, \"packageId\");\n const readyApps = this.collections.packages.find({\n _id: {\n $in: packageIds,\n },\n status: \"ready\",\n });\n return readyApps.count() === packageIds.length;\n },", " getBillingPromptUrl() {\n const setting = this.collections.settings.findOne({ _id: \"billingPromptUrl\" });\n return setting && setting.value;\n },", " isReferralEnabled() {\n // This function is a bit weird, in that we've transitioned from\n // Meteor.settings.public.quotaEnabled to DB settings. For now,\n // Meteor.settings.public.quotaEnabled implies bothisReferralEnabled and isQuotaEnabled are true.\n return Meteor.settings.public.quotaEnabled;\n },", " isHideAboutEnabled() {\n const setting = this.collections.settings.findOne({ _id: \"whiteLabelHideAbout\" });\n return setting && setting.value;\n },", " isQuotaEnabled() {\n if (Meteor.settings.public.quotaEnabled) return true;", " const setting = this.collections.settings.findOne({ _id: \"quotaEnabled\" });\n return setting && setting.value;\n },", " isQuotaLdapEnabled() {\n const setting = this.collections.settings.findOne({ _id: \"quotaLdapEnabled\" });\n return setting && setting.value;\n },", " updateUserQuota(user) {\n if (this.quotaManager) {\n return this.quotaManager.updateUserQuota(this, user);\n }\n },", " getUserQuota(user) {\n if (this.isQuotaLdapEnabled()) {\n return this.quotaManager.updateUserQuota(this, user);\n } else {\n const plan = this.getPlan(user.plan || \"free\", user);\n const referralBonus = calculateReferralBonus(user);\n const bonus = user.planBonus || {};\n const userQuota = {\n storage: plan.storage + referralBonus.storage + (bonus.storage || 0),\n grains: plan.grains + referralBonus.grains + (bonus.grains || 0),\n compute: plan.compute + (bonus.compute || 0),\n };\n return userQuota;\n }\n },", " isUserOverQuota(user) {\n // Return false if user has quota space remaining, true if it is full. When this returns true,\n // we will not allow the user to create new grains, though they may be able to open existing ones\n // which may still increase their storage usage.\n //\n // (Actually returns a string which can be fed into `billingPrompt` as the reason.)", " if (!this.isQuotaEnabled() || user.isAdmin) return false;", " const plan = this.getUserQuota(user);\n if (plan.grains < Infinity) {\n const count = this.collections.grains.find({ userId: user._id, trashed: { $exists: false } },\n { fields: {}, limit: plan.grains }).count();\n if (count >= plan.grains) return \"outOfGrains\";\n }", " return plan && user.storageUsage && user.storageUsage >= plan.storage && \"outOfStorage\";\n },", " isUserExcessivelyOverQuota(user) {\n // Return true if user is so far over quota that we should prevent their existing grains from\n // running at all.\n //\n // (Actually returns a string which can be fed into `billingPrompt` as the reason.)", " if (!this.isQuotaEnabled() || user.isAdmin) return false;", " const quota = this.getUserQuota(user);", " // quota.grains = Infinity means unlimited grains. IEEE754 defines Infinity == Infinity.\n if (quota.grains < Infinity) {\n const count = this.collections.grains.find({ userId: user._id, trashed: { $exists: false } },\n { fields: {}, limit: quota.grains * 2 }).count();\n if (count >= quota.grains * 2) return \"outOfGrains\";\n }", " return quota && user.storageUsage && user.storageUsage >= quota.storage * 1.2 && \"outOfStorage\";\n },", " suspendIdentity(userId, suspension) {\n check(userId, String);\n check(suspension, {\n timestamp: Date,\n admin: Match.Optional(String),\n voluntary: Match.Optional(Boolean),\n });", " this.collections.users.update({ _id: userId }, { $set: { suspended: suspension } });\n this.collections.apiTokens.update({ \"owner.user.identityId\": userId },\n { $set: { suspended: true } }, { multi: true });\n },", " unsuspendIdentity(userId) {\n check(userId, String);", " this.collections.users.update({ _id: userId }, { $unset: { suspended: 1 } });\n this.collections.apiTokens.update({ \"owner.user.identityId\": userId },\n { $unset: { suspended: true } }, { multi: true });\n },", " suspendAccount(userId, byAdminUserId, willDelete) {\n check(userId, String);\n check(byAdminUserId, Match.OneOf(String, null, undefined));\n check(willDelete, Boolean);", " const user = this.collections.users.findOne({ _id: userId });\n const suspension = {\n timestamp: new Date(),\n willDelete: willDelete || false,\n };\n if (byAdminUserId) {\n suspension.admin = byAdminUserId;\n } else {\n suspension.voluntary = true;\n }", " this.collections.users.update({ _id: userId }, { $set: { suspended: suspension } });\n this.collections.grains.update({ userId: userId }, { $set: { suspended: true } }, { multi: true });", " delete suspension.willDelete;\n // Only mark the parent account for deletion. This makes the query simpler later.", " user.loginIdentities.forEach((identity) => {\n this.suspendIdentity(identity.id, suspension);\n });\n user.nonloginIdentities.forEach((identity) => {\n if (this.collections.users.find({ $or: [\n { \"loginIdentities.id\": identity.id },\n { \"nonloginIdentities.id\": identity.id },\n ], }).count() === 1) {\n // Only suspend non-login identities that are unique to this account.\n this.suspendIdentity(identity.id, suspension);\n }\n });", " // Force logout this user\n this.collections.users.update({ _id: userId },\n { $unset: { \"services.resume.loginTokens\": 1 } });\n if (user && user.loginIdentities) {\n user.loginIdentities.forEach(function (identity) {\n Meteor.users.update({ _id: identity.id }, { $unset: { \"services.resume.loginTokens\": 1 } });\n });\n }\n },", " unsuspendAccount(userId) {\n check(userId, String);", " const user = this.collections.users.findOne({ _id: userId });\n this.collections.users.update({ _id: userId }, { $unset: { suspended: 1 } });\n this.collections.grains.update({ userId: userId }, { $unset: { suspended: 1 } }, { multi: true });", " user.loginIdentities.forEach((identity) => {\n this.unsuspendIdentity(identity.id);\n });", " user.nonloginIdentities.forEach((identity) => {\n this.unsuspendIdentity(identity.id);\n });\n },", " deletePendingAccounts(deletionCoolingOffTime, backend, cb) {\n check(deletionCoolingOffTime, Number);", " const queryDate = new Date(Date.now() - deletionCoolingOffTime);\n this.collections.users.find({\n \"suspended.willDelete\": true,\n \"suspended.timestamp\": { $lt: queryDate },\n }).forEach((user) => {\n if (cb) cb(this, user);\n this.deleteAccount(user._id, backend);\n });\n },", " hostIsStandalone: function (hostname) {\n check(hostname, String);", " return !!this.collections.standaloneDomains.findOne({ _id: hostname, });\n },\n});", "SandstormDb.escapeMongoKey = (key) => {\n // This incredibly poor mechanism for escaping Mongo keys is recommended by the Mongo docs here:\n // https://docs.mongodb.org/manual/faq/developers/#dollar-sign-operator-escaping\n // and seems to be a de facto standard, for example:\n // https://www.npmjs.com/package/mongo-key-escape\n return key.replace(\".\", \"\\uFF0E\").replace(\"$\", \"\\uFF04\");\n};", "const appNameFromPackage = function (packageObj) {\n // This function takes a Package object from Mongo and returns an\n // app title.\n const manifest = packageObj.manifest;\n if (!manifest) return packageObj.appId || packageObj._id || \"unknown\";\n const action = manifest.actions[0];\n appName = (manifest.appTitle && manifest.appTitle.defaultText) ||\n appNameFromActionName(action.title.defaultText);\n return appName;\n};", "const appNameFromActionName = function (name) {\n // Hack: Historically we only had action titles, like \"New Etherpad Document\", not app\n // titles. But for this UI we want app titles. As a transitionary measure, try to\n // derive the app title from the action title.\n // TODO(cleanup): Get rid of this once apps have real titles.\n if (!name) {\n return \"(unnamed)\";\n }", " if (name.lastIndexOf(\"New \", 0) === 0) {\n name = name.slice(4);\n }", " if (name.lastIndexOf(\"Hacker CMS\", 0) === 0) {\n name = \"Hacker CMS\";\n } else {\n const space = name.indexOf(\" \");\n if (space > 0) {\n name = name.slice(0, space);\n }\n }", " return name;\n};", "const appShortDescriptionFromPackage = function (pkg) {\n return pkg && pkg.manifest && pkg.manifest.metadata &&\n pkg.manifest.metadata.shortDescription &&\n pkg.manifest.metadata.shortDescription.defaultText;\n};", "const nounPhraseForActionAndAppTitle = function (action, appTitle) {\n // A hack to deal with legacy apps not including fields in their manifests.\n // I look forward to the day I can remove most of this code.\n // Attempt to figure out the appropriate noun that this action will create.\n // Use an explicit noun phrase is one is available. Apps should add these in the future.\n if (action.nounPhrase) return action.nounPhrase.defaultText;\n // Otherwise, try to guess one from the structure of the action title field\n if (action.title && action.title.defaultText) {\n const text = action.title.defaultText;\n // Strip a leading \"New \"\n if (text.lastIndexOf(\"New \", 0) === 0) {\n const candidate = text.slice(4);\n // Strip a leading appname too, if provided\n if (candidate.lastIndexOf(appTitle, 0) === 0) {\n const newCandidate = candidate.slice(appTitle.length);\n // Unless that leaves you with no noun, in which case, use \"grain\"\n if (newCandidate.length > 0) {\n return newCandidate.toLowerCase();\n } else {\n return \"grain\";\n }\n }", " return candidate.toLowerCase();\n }\n // Some other verb phrase was given. Just use it verbatim, and hope the app author updates\n // the package soon.\n return text;\n } else {\n return \"grain\";\n }\n};", "// Static methods on SandstormDb that don't need an instance.\n// Largely things that deal with backwards-compatibility.\n_.extend(SandstormDb, {\n appNameFromActionName: appNameFromActionName,\n appNameFromPackage: appNameFromPackage,\n appShortDescriptionFromPackage: appShortDescriptionFromPackage,\n nounPhraseForActionAndAppTitle: nounPhraseForActionAndAppTitle,\n});", "if (Meteor.isServer) {\n const Crypto = Npm.require(\"crypto\");\n const ContentType = Npm.require(\"content-type\");\n const Zlib = Npm.require(\"zlib\");\n const Url = Npm.require(\"url\");", " const replicaNumber = Meteor.settings.replicaNumber || 0;", " const computeStagger = function (n) {\n // Compute a fraction in the range [0, 1) such that, for any natural number k, the values\n // of computeStagger(n) for all n in [1, 2^k) are uniformly distributed between 0 and 1.\n // The sequence looks like:\n // 0, 1/2, 1/4, 3/4, 1/8, 3/8, 5/8, 7/8, 1/16, ...\n //\n // We use this to determine how we'll stagger periodic events performed by this replica.\n // Notice that this allows us to compute a stagger which is independent of the number of\n // front-end replicas present; we can add more replicas to the end without affecting how the\n // earlier ones schedule their events.\n let denom = 1;\n while (denom <= n) denom <<= 1;\n const num = n * 2 - denom + 1;\n return num / denom;\n };", " const stagger = computeStagger(replicaNumber);", " SandstormDb.periodicCleanup = function (intervalMs, callback) {\n // Register a database cleanup function than should run periodically, roughly once every\n // interval of the given length.\n //\n // In a blackrock deployment with multiple front-ends, the frequency of the cleanup will be\n // scaled appropriately on the assumption that more data is being generated demanding more\n // frequent cleanups.", " check(intervalMs, Number);\n check(callback, Function);", " if (intervalMs < 120000) {\n throw new Error(\"less than 2-minute cleanup interval seems too fast; \" +\n \"are you using the right units?\");\n }", " // Schedule first cleanup to happen at the next intervalMs interval from the epoch, so that\n // the schedule is independent of the exact startup time.\n let first = intervalMs - Date.now() % intervalMs;", " // Stagger cleanups across replicas so that we don't have all replicas trying to clean the\n // same data at the same time.\n first += Math.floor(intervalMs * computeStagger(replicaNumber));", " // If the stagger put us more than an interval away from now, back up.\n if (first > intervalMs) first -= intervalMs;", " Meteor.setTimeout(function () {\n callback();\n Meteor.setInterval(callback, intervalMs);\n }, first);\n };", " // TODO(cleanup): Node 0.12 has a `gzipSync` but 0.10 (which Meteor still uses) does not.\n const gzipSync = Meteor.wrapAsync(Zlib.gzip, Zlib);", " const BufferSmallerThan = function (limit) {\n return Match.Where(function (buf) {\n check(buf, Buffer);\n return buf.length < limit;\n });\n };", " const DatabaseId = Match.Where(function (s) {\n check(s, String);\n return !!s.match(/^[a-zA-Z0-9_]+$/);\n });", " SandstormDb.prototype.addStaticAsset = function (metadata, content) {\n // Add a new static asset to the database. If `content` is a string rather than a buffer, it\n // will be automatically gzipped before storage; do not specify metadata.encoding in this case.", " if (typeof content === \"string\" && !metadata.encoding) {\n content = gzipSync(new Buffer(content, \"utf8\"));\n metadata.encoding = \"gzip\";\n }", " check(metadata, {\n mimeType: String,\n encoding: Match.Optional(\"gzip\"),\n });\n check(content, BufferSmallerThan(1 << 20));", " // Validate content type.\n metadata.mimeType = ContentType.format(ContentType.parse(metadata.mimeType));", " const hasher = Crypto.createHash(\"sha256\");\n hasher.update(metadata.mimeType + \"\\n\" + metadata.encoding + \"\\n\", \"utf8\");\n hasher.update(content);\n const hash = hasher.digest(\"base64\");", " const result = this.collections.staticAssets.findAndModify({\n query: { hash: hash, refcount: { $gte: 1 } },\n update: { $inc: { refcount: 1 } },\n fields: { _id: 1, refcount: 1 },\n });", " if (!result.ok) {\n throw new Error(`Couldn't increment refcount of asset with hash ${hash}`);\n }", " const existing = result.value;\n if (existing) {\n return existing._id;\n }", " return this.collections.staticAssets.insert(_.extend({\n hash: hash,\n content: content,\n refcount: 1,\n }, metadata));\n };", " SandstormDb.prototype.refStaticAsset = function (id) {\n // Increment the refcount on an existing static asset. Returns the asset on success.\n // If the asset does not exist, returns a falsey value.\n //\n // You must call this BEFORE adding the new reference to the DB, in case of failure between\n // the two calls. (This way, the failure case is a storage leak, which is probably not a big\n // deal and can be fixed by GC, rather than a mysteriously missing asset.)", " check(id, String);", " const result = this.collections.staticAssets.findAndModify({\n query: { hash: hash },\n update: { $inc: { refcount: 1 } },\n fields: { _id: 1, content: 1, mimeType: 1 },\n });", " if (!result.ok) {\n throw new Error(`Couldn't increment refcount of asset with hash ${hash}`);\n }", " const existing = result.value;\n return existing;\n };", " SandstormDb.prototype.unrefStaticAsset = function (id) {\n // Decrement refcount on a static asset and delete if it has reached zero.\n //\n // You must call this AFTER removing the reference from the DB, in case of failure between\n // the two calls. (This way, the failure case is a storage leak, which is probably not a big\n // deal and can be fixed by GC, rather than a mysteriously missing asset.)", " check(id, String);", " const result = this.collections.staticAssets.findAndModify({\n query: { _id: id },\n update: { $inc: { refcount: -1 } },\n fields: { _id: 1, refcount: 1 },\n new: true,\n });", " if (!result.ok) {\n throw new Error(`Couldn't unref static asset ${id}`);\n }", " const existing = result.value;\n if (!existing) {\n console.error(new Error(\"unrefStaticAsset() called on asset that doesn't exist\").stack);\n } else if (existing.refcount <= 0) {\n this.collections.staticAssets.remove({ _id: existing._id });\n }\n };", " SandstormDb.prototype.getStaticAsset = function (id) {\n // Get a static asset's mimeType, encoding, and raw content.", " check(id, String);", " const asset = this.collections.staticAssets.findOne(id, { fields: { _id: 0, mimeType: 1, encoding: 1, content: 1 } });\n if (asset) {\n // TODO(perf): Mongo converts buffers to something else. Figure out a way to avoid a copy\n // here.\n asset.content = new Buffer(asset.content);\n }", " return asset;\n };", " SandstormDb.prototype.newAssetUpload = function (purpose) {\n check(purpose, Match.OneOf(\n { profilePicture: { userId: DatabaseId, identityId: DatabaseId } },\n { loginLogo: {} },\n ));", " return this.collections.assetUploadTokens.insert({\n purpose: purpose,\n expires: new Date(Date.now() + 300000), // in 5 minutes\n });\n };", " SandstormDb.prototype.fulfillAssetUpload = function (id) {\n // Indicates that the given asset upload has completed. It will be removed and its purpose\n // returned. If no matching upload exists, returns undefined.", " check(id, String);", " const result = this.collections.assetUploadTokens.findAndModify({\n query: { _id: id },\n remove: true,\n });", " if (!result.ok) {\n throw new Error(\"Failed to remove asset upload token\");\n }", " const upload = result.value;", " if (upload.expires.valueOf() < Date.now()) {\n return undefined; // already expired\n } else {\n return upload.purpose;\n }\n };", " SandstormDb.prototype.cleanupExpiredAssetUploads = function () {\n this.collections.assetUploadTokens.remove({ expires: { $lt: Date.now() } });\n };", " // TODO(cleanup): lift this out of the package so it can share with the ones in async-helpers.js\n const Future = Npm.require(\"fibers/future\");\n const promiseToFuture = (promise) => {\n const result = new Future();\n promise.then(result.return.bind(result), result.throw.bind(result));\n return result;\n };", " const waitPromise = (promise) => {\n return promiseToFuture(promise).wait();\n };", " SandstormDb.prototype.deleteGrains = function (query, backend, type) {\n // Returns the number of grains deleted.", " check(type, Match.OneOf(\"grain\", \"demoGrain\"));", " let numDeleted = 0;\n this.collections.grains.find(query).forEach((grain) => {\n const user = Meteor.users.findOne(grain.userId);", " waitPromise(backend.deleteGrain(grain._id, grain.userId));\n numDeleted += this.collections.grains.remove({ _id: grain._id });\n this.removeApiTokens({\n grainId: grain._id,\n $or: [\n { owner: { $exists: false } },\n { owner: { webkey: null } },\n ],\n });", " this.removeApiTokens({ \"owner.grain.grainId\": grain._id });", " this.collections.activitySubscriptions.remove({ grainId: grain._id });", " if (grain.lastUsed) {\n const record = {\n type: \"grain\", // Demo grains can never get here!\n lastActive: grain.lastUsed,\n appId: grain.appId,\n };\n if (user && user.experiments) {\n record.experiments = user.experiments;\n }", " this.collections.deleteStats.insert(record);\n }", " this.deleteUnusedPackages(grain.appId);", " if (grain.size) {\n Meteor.users.update(grain.userId, { $inc: { storageUsage: -grain.size } });\n }\n });\n return numDeleted;\n };", " SandstormDb.prototype.userGrainTitle = function (grainId, accountId, identityId) {\n check(grainId, String);\n check(accountId, Match.OneOf(String, undefined, null));\n check(identityId, String);", " const grain = this.getGrain(grainId);\n if (!grain) {\n throw new Error(\"called userGrainTitle() for a grain that doesn't exist\");\n }", " let title = grain.title;\n if (grain.userId !== accountId) {\n const sharerToken = this.collections.apiTokens.findOne({\n grainId: grainId,\n \"owner.user.identityId\": identityId,\n }, {\n sort: {\n lastUsed: -1,\n },\n });\n if (sharerToken) {\n title = sharerToken.owner.user.title;\n } else {\n title = \"shared grain\";\n }\n }", " return title;\n };", " const packageCache = {};\n // Package info is immutable. Let's cache to save on mongo queries.", " SandstormDb.prototype.getPackage = function (packageId) {\n // Get the given package record. Since package info is immutable, cache the data in the server\n // to reduce mongo query overhead, since it turns out we have to fetch specific packages a\n // lot.", " if (packageId in packageCache) {\n return packageCache[packageId];\n }", " const pkg = this.collections.packages.findOne(packageId);\n if (pkg && pkg.status === \"ready\") {\n packageCache[packageId] = pkg;\n }", " return pkg;\n };", " SandstormDb.prototype.deleteUnusedPackages = function (appId) {\n check(appId, String);\n this.collections.packages.find({ appId: appId }).forEach((pkg) => {\n // Mark package for possible deletion;\n this.collections.packages.update({ _id: pkg._id, status: \"ready\" }, { $set: { shouldCleanup: true } });\n });\n };", " SandstormDb.prototype.sendAppUpdateNotifications = function (appId, packageId, name,\n versionNumber, marketingVersion) {\n const actions = this.collections.userActions.find({ appId: appId, appVersion: { $lt: versionNumber } },\n { fields: { userId: 1 } });\n actions.forEach((action) => {\n const userId = action.userId;\n const updater = {\n timestamp: new Date(),\n isUnread: true,\n };\n const inserter = _.extend({ userId, appUpdates: {} }, updater);", " // Set only the appId that we care about. Use mongo's dot notation to specify only a single\n // field inside of an object to update\n inserter.appUpdates[appId] = updater[\"appUpdates.\" + appId] = {\n marketingVersion: marketingVersion,\n packageId: packageId,\n name: name,\n version: versionNumber,\n };", " // We unfortunately cannot upsert because upserts can only have field equality conditions in\n // the query. If we try to upsert, Mongo complaints that \"$exists\" isn't valid to store.\n if (this.collections.notifications.update(\n { userId: userId, appUpdates: { $exists: true } },\n { $set: updater }) == 0) {\n // Update failed; try an insert instead.\n this.collections.notifications.insert(inserter);\n }\n });", " this.collections.appIndex.update({ _id: appId }, { $set: { hasSentNotifications: true } });", " // In the case where we replaced a previous notification and that was the only reference to the\n // package, we need to clean it up\n this.deleteUnusedPackages(appId);\n };", " SandstormDb.prototype.sendReferralProgramNotification = function (userId) {\n this.collections.notifications.upsert({\n userId: userId,\n referral: true,\n }, {\n userId: userId,\n referral: true,\n timestamp: new Date(),\n isUnread: true,\n });\n };", " SandstormDb.prototype.upgradeGrains = function (appId, version, packageId, backend) {\n check(appId, String);\n check(version, Match.Integer);\n check(packageId, String);", " const selector = {\n userId: Meteor.userId(),\n appId: appId,\n appVersion: { $lte: version },\n packageId: { $ne: packageId },\n };", " this.collections.grains.find(selector).forEach(function (grain) {\n backend.shutdownGrain(grain._id, grain.userId);\n });", " this.collections.grains.update(selector, {\n $set: { appVersion: version, packageId: packageId, packageSalt: Random.secret() },\n }, { multi: true });\n };", " SandstormDb.prototype.startInstall = function (packageId, url, retryFailed, isAutoUpdated) {\n // Mark package for possible installation.", " const fields = {\n status: \"download\",\n progress: 0,\n url: url,\n isAutoUpdated: !!isAutoUpdated,\n };", " if (retryFailed) {\n this.collections.packages.update({ _id: packageId, status: \"failed\" }, { $set: fields });\n } else {\n try {\n fields._id = packageId;\n this.collections.packages.insert(fields);\n } catch (err) {\n console.error(\"Simultaneous startInstall()s?\", err.stack);\n }\n }\n };", " const ValidKeyFingerprint = Match.Where(function (keyFingerprint) {\n check(keyFingerprint, String);\n return !!keyFingerprint.match(/^[0-9A-F]{40}$/);\n });", " SandstormDb.prototype.updateKeybaseProfileAsync = function (keyFingerprint) {\n // Asynchronously fetch the given Keybase profile and populate the KeybaseProfiles collection.", " check(keyFingerprint, ValidKeyFingerprint);", " console.log(\"fetching keybase\", keyFingerprint);", " HTTP.get(\n \"https://keybase.io/_/api/1.0/user/lookup.json?key_fingerprint=\" + keyFingerprint +\n \"&fields=basics,profile,proofs_summary\", {\n timeout: 5000,\n }, (err, keybaseResponse) => {\n if (err) {\n console.log(\"keybase lookup error:\", err.stack);\n return;\n }", " if (!keybaseResponse.data) {\n console.log(\"keybase didn't return JSON? Headers:\", keybaseResponse.headers);\n return;\n }", " const profile = (keybaseResponse.data.them || [])[0];", " if (profile) {\n // jscs:disable requireCamelCaseOrUpperCaseIdentifiers\n const record = {\n displayName: (profile.profile || {}).full_name,\n handle: (profile.basics || {}).username,\n proofs: (profile.proofs_summary || {}).all || [],\n };\n // jscs:enable requireCamelCaseOrUpperCaseIdentifiers", " record.proofs.forEach(function (proof) {\n // Remove potentially Mongo-incompatible stuff. (Currently Keybase returns nothing that\n // this would filter.)\n for (let field in proof) {\n // Don't allow field names containing '.' or '$'. Also don't allow sub-objects mainly\n // because I'm too lazy to check the field names recursively (and Keybase doesn't\n // return any objects anyway).\n if (field.match(/[.$]/) || typeof (proof[field]) === \"object\") {\n delete proof[field];\n }\n }", " // Indicate not verified.\n // TODO(security): Asynchronously verify proofs. Presumably we can borrow code from the\n // Keybase node-based CLI.\n proof.status = \"unverified\";\n });", " this.collections.keybaseProfiles.update(keyFingerprint, { $set: record }, { upsert: true });\n } else {\n // Keybase reports no match, so remove what we know of this user. We don't want to remove\n // the item entirely from the cache as this will cause us to repeatedly re-fetch the data\n // from Keybase.\n //\n // TODO(someday): We could perhaps keep the proofs if we can still verify them directly,\n // but at present we don't have the ability to verify proofs.\n this.collections.keybaseProfiles.update(keyFingerprint,\n { $unset: { displayName: \"\", handle: \"\", proofs: \"\" } }, { upsert: true });\n }\n });\n };", " SandstormDb.prototype.deleteUnusedAccount = function (backend, identityId) {\n // If there is an *unused* account that has `identityId` as a login identity, deletes it.", " check(identityId, String);\n const account = this.collections.users.findOne({ \"loginIdentities.id\": identityId });\n if (account &&\n account.loginIdentities.length == 1 &&\n account.nonloginIdentities.length == 0 &&\n !this.collections.grains.findOne({ userId: account._id }) &&\n !this.collections.apiTokens.findOne({ accountId: account._id }) &&\n (!account.plan || account.plan === \"free\") &&\n !(account.payments && account.payments.id) &&\n !this.collections.contacts.findOne({ ownerId: account._id })) {\n this.collections.users.remove({ _id: account._id });\n backend.deleteUser(account._id);\n }\n };", " Meteor.publish(\"keybaseProfile\", function (keyFingerprint) {\n check(keyFingerprint, ValidKeyFingerprint);\n const db = this.connection.sandstormDb;", " const cursor = db.collections.keybaseProfiles.find(keyFingerprint);\n if (cursor.count() === 0) {\n // Fire off async update.\n db.updateKeybaseProfileAsync(keyFingerprint);\n }", " return cursor;\n });", " Meteor.publish(\"appIndex\", function (appId) {\n check(appId, String);\n const db = this.connection.sandstormDb;\n const cursor = db.collections.appIndex.find({ _id: appId });\n return cursor;\n });", " Meteor.publish(\"userPackages\", function () {\n // Users should be able to see packages that are either:\n // 1. referenced by one of their userActions\n // 2. referenced by one of their grains\n const db = this.connection.sandstormDb;", " // Note that package information, once it is in the database, is static. There's no need to\n // reactively subscribe to changes to a package since they don't change. It's also unecessary\n // to reactively remove a package from the client side when it is removed on the server, or\n // when the client stops using it, because the worst case is the client has a small amount\n // of extra info on a no-longer-used package held in memory until they refresh Sandstorm.\n // So, we implement this as a cache: the first time each package ID shows up among the user's\n // stuff, we push the package info to the client, and then we never update it.\n //\n // Alternatively, we could subscribe to each individual package query, but this would waste\n // lots of server-side resources watching for events that will never happen or don't matter.\n const hasPackage = {};\n const refPackage = (packageId) => {\n // Ignore dev apps.\n if (packageId.lastIndexOf(\"dev-\", 0) === 0) return;", " if (!hasPackage[packageId]) {\n hasPackage[packageId] = true;\n const pkg = db.getPackage(packageId);\n if (pkg) {\n this.added(\"packages\", packageId, pkg);\n } else {\n console.error(\n \"shouldn't happen: missing package referenced by user's stuff:\", packageId);\n }\n }\n };", " // package source 1: packages referred to by actions\n const actions = db.userActions(this.userId);\n const actionsHandle = actions.observe({\n added(newAction) {\n refPackage(newAction.packageId);\n },", " changed(newAction, oldAction) {\n refPackage(newAction.packageId);\n },\n });", " // package source 2: packages referred to by grains directly\n const grains = db.userGrains(this.userId, { includeTrash: true });\n const grainsHandle = grains.observe({\n added(newGrain) {\n // Watch out: DevApp grains can lack a packageId.\n if (newGrain.packageId) {\n refPackage(newGrain.packageId);\n }\n },", " changed(newGrain, oldGrain) {\n // Watch out: DevApp grains can lack a packageId.\n if (newGrain.packageId) {\n refPackage(newGrain.packageId);\n }\n },\n });", " this.onStop(function () {\n actionsHandle.stop();\n grainsHandle.stop();\n });", " this.ready();\n });\n}", "if (Meteor.isServer) {\n SandstormDb.prototype.deleteIdentity = function (identityId) {\n check(identityId, String);", " this.removeApiTokens({ \"owner.user.identityId\": identityId });\n this.collections.contacts.remove({ identityId: identityId });\n Meteor.users.remove({ _id: identityId });\n };", " SandstormDb.prototype.deleteAccount = function (userId, backend) {\n check(userId, String);", " const _this = this;\n const user = Meteor.users.findOne({ _id: userId });\n this.deleteGrains({ userId: userId }, backend, \"grain\");\n this.collections.userActions.remove({ userId: userId });\n this.collections.notifications.remove({ userId: userId });\n user.loginIdentities.forEach((identity) => {\n if (Meteor.users.find({ $or: [\n { \"loginIdentities.id\": identity.id },\n { \"nonloginIdentities.id\": identity.id },\n ], }).count() === 1) {\n // If this is the only account with the identity, then delete it\n _this.deleteIdentity(identity.id);\n }\n });\n user.nonloginIdentities.forEach((identity) => {\n if (Meteor.users.find({ $or: [\n { \"loginIdentities.id\": identity.id },\n { \"nonloginIdentities.id\": identity.id },\n ], }).count() === 1) {\n // If this is the only account with the identity, then delete it\n _this.deleteIdentity(identity.id);\n }\n });\n this.collections.contacts.remove({ ownerId: userId });\n backend.deleteUser(userId);\n Meteor.users.remove({ _id: userId });\n };\n}", "Meteor.methods({\n addUserActions(packageId) {\n check(packageId, String);\n if (!this.userId || !Meteor.user().loginIdentities || !isSignedUpOrDemo()) {\n throw new Meteor.Exception(403, \"Must be logged in as a non-guest to add app actions.\");\n }", " if (this.isSimulation) {\n // TODO(cleanup): Appdemo code relies on this being simulated client-side but we don't have\n // a proper DB object to use.\n new SandstormDb().addUserActions(this.userId, packageId, true);\n } else {\n this.connection.sandstormDb.addUserActions(this.userId, packageId);\n }\n },", " removeUserAction(actionId) {\n check(actionId, String);\n if (this.isSimulation) {\n UserActions.remove({ _id: actionId });\n } else {\n if (this.userId) {\n const result = this.connection.sandstormDb.collections.userActions.findAndModify({\n query: { _id: actionId, userId: this.userId },\n remove: true,\n });", " if (!result.ok) {\n throw new Error(`Couldn't remove user action ${actionId}`);\n }", " const action = result.value;\n if (action) {\n this.connection.sandstormDb.deleteUnusedPackages(action.appId);\n }\n }\n }\n },\n});" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [84, 1522, 203, 231], "buggy_code_start_loc": [77, 1518, 202, 188], "filenames": ["shell/imports/server/email.js", "shell/packages/sandstorm-db/db.js", "shell/server/accounts/email-token/token-server.js", "shell/server/admin-server.js"], "fixing_code_end_loc": [121, 1524, 203, 232], "fixing_code_start_loc": [78, 1519, 202, 188], "message": "A remote attacker could bypass the Sandstorm organization restriction before build 0.203 via a comma in an email-address field.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sandstorm:sandstorm:*:*:*:*:*:*:*:*", "matchCriteriaId": "683ED5F0-D297-4A47-ADF9-186832F3A3AD", "versionEndExcluding": "0.203", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A remote attacker could bypass the Sandstorm organization restriction before build 0.203 via a comma in an email-address field."}, {"lang": "es", "value": "Un atacante remoto podr\u00eda omitir la restricci\u00f3n de organizaci\u00f3n de Sandstorm antes de la build 0.203 mediante una coma en un campo email-address."}], "evaluatorComment": null, "id": "CVE-2017-6199", "lastModified": "2018-03-13T19:27:30.200", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-02-06T16:29:00.730", "references": [{"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://devco.re/blog/2018/01/26/Sandstorm-Security-Review-CVE-2017-6200-en/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/sandstorm-io/sandstorm/blob/v0.202/shell/packages/sandstorm-db/db.js#L1112"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/sandstorm-io/sandstorm/commit/37bd9a7f4eb776cdc2d3615f0bfea1254b66f59d"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://sandstorm.io/news/2017-03-02-security-review"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-287"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/sandstorm-io/sandstorm/commit/37bd9a7f4eb776cdc2d3615f0bfea1254b66f59d"}, "type": "CWE-287"}
324
Determine whether the {function_name} code is vulnerable or not.
[ "import crypto from \"crypto\";", "import { send as sendEmail } from \"/imports/server/email.js\";", "const Url = Npm.require(\"url\");", "const V1_ROUNDS = 4096; // Selected to take ~5msec at creation time (2016) on a developer's laptop.\nconst V1_KEYSIZE = 32; // 256 bits / 8 bits/byte = 32 bytes\nconst V1_HASHFUNC = \"sha512\";\n// ^ hash function used with pbkdf2. Chosen to be different from the function which maps the token\n// to the value stored in the database. Note that the first thing that pbkdf2 does is\n// HMAC(HASHFUNC, key, salt), and the first thing that HMAC does is either pad or hash the key to\n// make it the appropriate width. The result is that knowing sha256(key) and the salt is possibly\n// sufficient to reconstruct the output of pbkdf2().\nconst V1_CIPHER = \"AES-256-CTR\"; // cipher used", "const TOKEN_EXPIRATION_MS = 60 * 60 * 1000;", "const cleanupExpiredTokens = function () {\n Meteor.users.update({\n \"services.email.tokens.createdAt\": {\n $lt: new Date(Date.now() - TOKEN_EXPIRATION_MS),\n },\n }, {\n $pull: {\n \"services.email.tokens\": {\n createdAt: { $lt: new Date(Date.now() - TOKEN_EXPIRATION_MS) },\n },\n },\n }, {\n multi: true,\n });\n};", "Meteor.startup(cleanupExpiredTokens);\n// Tokens can actually last up to 2 * TOKEN_EXPIRATION_MS\nSandstormDb.periodicCleanup(TOKEN_EXPIRATION_MS, cleanupExpiredTokens);", "const hashToken = (token) => {\n return {\n digest: SHA256(token),\n algorithm: \"sha-256\",\n };\n};", "const checkToken = function (tokens, token) {\n // Looks for an object in `tokens` with `algorithm` and `digest` fields matching those in `token`.\n // Returns the matching object, if one is found, or undefined if none match.\n let foundToken = undefined;\n tokens.forEach(function (userToken) {\n if ((userToken.algorithm === token.algorithm) &&\n (userToken.digest === token.digest)) {\n foundToken = userToken;\n }\n });", " return foundToken;\n};", "const consumeToken = function (user, token) {\n const hashedToken = hashToken(token);\n const foundToken = checkToken(user.services.email.tokens, hashedToken);", " if (foundToken !== undefined) {\n Meteor.users.update({ _id: user._id }, { $pull: { \"services.email.tokens\": hashedToken } });\n }", " return foundToken;\n};", "const makeBox = function (token, plaintext) {\n // Encrypt plaintext symmetrically with a key derived from token. Returns an object with\n // ciphertext and associated data needed to decrypt later.", " // Produce a symmetric key. Note that the token itself does not have sufficient entropy to\n // be used as a key directly, so we need to use a KDF with a strong random salt.\n // In the fullness of time, it might be nice to move away from using a KDF (which blocks the whole\n // node process) in favor of the token itself having enough entropy to serve as the key itself.\n // This would require lengthening the token, which would make the manual-code-entry workflow\n // worse, so I'm punting on that for now.\n const salt = Random.secret(16);\n const key = crypto.pbkdf2Sync(token, salt, V1_ROUNDS, V1_KEYSIZE, V1_HASHFUNC);\n const iv = crypto.randomBytes(16);\n const cipher = crypto.createCipheriv(V1_CIPHER, key, iv);\n let ciphertext = cipher.update(new Buffer(plaintext, \"binary\"));\n return {\n version: 1,\n salt: salt,\n iv: iv.toString(\"base64\"),\n boxedValue: ciphertext.toString(\"base64\"),\n };\n};", "const tryUnbox = function (box, secret) {\n if (box) {\n if (box.version === 1) {\n const key = crypto.pbkdf2Sync(secret, box.salt, V1_ROUNDS, V1_KEYSIZE, V1_HASHFUNC);\n const iv = new Buffer(box.iv, \"base64\");\n const cipher = crypto.createDecipheriv(V1_CIPHER, key, iv);\n const cipherText = new Buffer(box.boxedValue, \"base64\");\n const plaintext = cipher.update(cipherText);\n return plaintext.toString(\"binary\");\n }\n }", " // If no box was provided, or it was of an unknown version, return no data.\n return;\n};", "// Handler to login with a token.\nAccounts.registerLoginHandler(\"email\", function (options) {\n if (!options.email) {\n return undefined; // don't handle\n }", " if (!Accounts.identityServices.email.isEnabled()) {\n throw new Meteor.Error(403, \"Email identity service is disabled.\");\n }", " options = options.email;\n check(options, {\n email: String,\n token: String,\n });", " const user = Meteor.users.findOne({\n \"services.email.email\": options.email,\n }, {\n fields: {\n \"services.email\": 1,\n },\n });", " if (!user) {\n console.error(\"User not found:\", options.email);\n return {\n error: new Meteor.Error(403, \"User not found\"),\n };\n }", " if (!user.services.email.tokens) {\n console.error(\"User has no token set:\", options.email);\n return {\n error: new Meteor.Error(403, \"User has no token set\"),\n };\n }", " const tokenString = options.token.trim();\n const maybeToken = consumeToken(user, tokenString);\n if (!maybeToken) {\n console.error(\"Token not found:\", options.email);\n return {\n error: new Meteor.Error(403, \"Invalid authentication code\"),\n };\n }", " // Attempt to decrypt the resumePath, if provided.\n const resumePath = tryUnbox(maybeToken.secureBox, tokenString);", " return {\n userId: user._id,\n options: {\n resumePath,\n },\n };\n});", "const makeTokenUrl = function (email, token, options) {\n if (options.linking) {\n return options.rootUrl + \"/_emailLinkIdentity/\" + encodeURIComponent(email) + \"/\" +\n encodeURIComponent(token) + \"/\" + Meteor.userId() +\n \"?allowLogin=\" + options.linking.allowLogin;\n } else {\n return options.rootUrl + \"/_emailLogin/\" + encodeURIComponent(email) + \"/\" + encodeURIComponent(token);\n }\n};", "///\n/// EMAIL VERIFICATION\n///\nconst sendTokenEmail = function (db, email, token, options) {\n let subject;\n let text;", " const rootHostname = Url.parse(options.rootUrl).hostname;", " if (!options.linking) {\n subject = \"Log in to \" + rootHostname;\n text = \"To confirm this email address on \";\n } else {\n subject = \"Confirm this email address on \" + rootHostname;\n text = \"To confirm this email address on \";\n }", " text = text + rootHostname + \", click on the following link:\\n\\n\" +\n makeTokenUrl(email, token, options) + \"\\n\\n\" +\n \"Alternatively, enter the following one-time authentication code into the log-in form:\\n\\n\" +\n token;", " const sendOptions = {\n to: email,", " from: db.getServerTitle() + \" <\" + db.getReturnAddress() + \">\",", " subject: subject,\n text: text,\n };", " sendEmail(sendOptions);\n};", "const parsedRootUrl = Url.parse(process.env.ROOT_URL);\n///\n/// CREATING USERS\n///\n// returns the user id\nconst createAndEmailTokenForUser = function (db, email, options) {\n check(email, String);\n check(options, {\n resumePath: String,\n linking: Match.Optional({ allowLogin: Boolean }),\n rootUrl: String,\n });", " const parsedUrl = Url.parse(options.rootUrl);\n if ((parsedUrl.hostname !== parsedRootUrl.hostname ||\n parsedUrl.protocol !== parsedRootUrl.protocol) &&\n !db.hostIsStandalone(parsedUrl.hostname)) {\n // Ignore port and only check hostname/protocol since IE will differ from other browsers and\n // sometimes include port 80/443 and sometimes won't\n throw new Meteor.Error(400, \"rootUrl is not valid\");\n }", " const atIndex = email.indexOf(\"@\");\n if (atIndex === -1) {\n throw new Meteor.Error(400, \"No @ symbol was found in your email\");\n }", " let user = Meteor.users.findOne({ \"services.email.email\": email },\n { fields: { \"services.email\": 1 } });\n let userId;", " // TODO(someday): make this shorter, and handle requests that try to brute force it.\n // Alternately, require using the link over copy/pasting the code, and crank up the entropy.\n const token = Random.id(12);\n const tokenObj = hashToken(token);\n tokenObj.createdAt = new Date();\n tokenObj.secureBox = makeBox(token, options.resumePath);", " if (user) {\n if (user.services.email.tokens && user.services.email.tokens.length > 2) {\n throw new Meteor.Error(\n \"alreadySentEmailToken\",\n \"It looks like we sent a log in email to this address not long \" +\n \"ago. Please use the one that was already sent (check your spam folder if you can't find \" +\n \"it), or wait a while and try again.\");\n }", " userId = user._id;", " Meteor.users.update({ _id: user._id }, { $push: { \"services.email.tokens\": tokenObj } });\n } else {\n const options = {};\n user = {\n services: {\n email: {\n tokens: [tokenObj],\n email: email,\n },\n },\n };", " userId = Accounts.insertUserDoc(options, user);\n }", " sendTokenEmail(db, email, token, options);", " return userId;\n};", "Meteor.methods({\n createAndEmailTokenForUser: function (email, options) {\n // method for create user. Requests come from the client.\n // This method will create a user if it doesn't exist, otherwise it will generate a token.\n // It will always send an email to the user", " check(email, String);\n check(options, {\n resumePath: String,\n linking: Match.Optional({ allowLogin: Boolean }),\n rootUrl: String,\n });", " if (!Accounts.identityServices.email.isEnabled()) {\n throw new Meteor.Error(403, \"Email identity service is disabled.\");\n }\n // Create user. result contains id and token.\n const user = createAndEmailTokenForUser(this.connection.sandstormDb, email, options);\n },", " linkEmailIdentityToAccount: function (email, token, allowLogin) {\n // Links the email identity with address `email` and login token `token` to the current account.\n check(email, String);\n check(token, String);\n check(allowLogin, Boolean);\n const account = Meteor.user();\n if (!account || !account.loginIdentities) {\n throw new Meteor.Error(403, \"Must be logged in to an account to link an email identity.\");\n }", " const identity = Meteor.users.findOne({ \"services.email.email\": email },\n { fields: { \"services.email\": 1 } });\n if (!identity) {\n throw new Meteor.Error(403, \"Invalid authentication code.\");\n }", " const maybeToken = consumeToken(identity, token.trim());\n if (!maybeToken) {\n throw new Meteor.Error(403, \"Invalid authentication code.\");\n }", " Accounts.linkIdentityToAccount(this.connection.sandstormDb, this.connection.sandstormBackend,\n identity._id, account._id, allowLogin);", " // Return the resume path, if we have one.\n const resumePath = tryUnbox(maybeToken.secureBox, token);\n return resumePath;\n },\n});" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [84, 1522, 203, 231], "buggy_code_start_loc": [77, 1518, 202, 188], "filenames": ["shell/imports/server/email.js", "shell/packages/sandstorm-db/db.js", "shell/server/accounts/email-token/token-server.js", "shell/server/admin-server.js"], "fixing_code_end_loc": [121, 1524, 203, 232], "fixing_code_start_loc": [78, 1519, 202, 188], "message": "A remote attacker could bypass the Sandstorm organization restriction before build 0.203 via a comma in an email-address field.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sandstorm:sandstorm:*:*:*:*:*:*:*:*", "matchCriteriaId": "683ED5F0-D297-4A47-ADF9-186832F3A3AD", "versionEndExcluding": "0.203", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A remote attacker could bypass the Sandstorm organization restriction before build 0.203 via a comma in an email-address field."}, {"lang": "es", "value": "Un atacante remoto podr\u00eda omitir la restricci\u00f3n de organizaci\u00f3n de Sandstorm antes de la build 0.203 mediante una coma en un campo email-address."}], "evaluatorComment": null, "id": "CVE-2017-6199", "lastModified": "2018-03-13T19:27:30.200", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-02-06T16:29:00.730", "references": [{"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://devco.re/blog/2018/01/26/Sandstorm-Security-Review-CVE-2017-6200-en/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/sandstorm-io/sandstorm/blob/v0.202/shell/packages/sandstorm-db/db.js#L1112"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/sandstorm-io/sandstorm/commit/37bd9a7f4eb776cdc2d3615f0bfea1254b66f59d"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://sandstorm.io/news/2017-03-02-security-review"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-287"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/sandstorm-io/sandstorm/commit/37bd9a7f4eb776cdc2d3615f0bfea1254b66f59d"}, "type": "CWE-287"}
324
Determine whether the {function_name} code is vulnerable or not.
[ "import crypto from \"crypto\";", "import { send as sendEmail } from \"/imports/server/email.js\";", "const Url = Npm.require(\"url\");", "const V1_ROUNDS = 4096; // Selected to take ~5msec at creation time (2016) on a developer's laptop.\nconst V1_KEYSIZE = 32; // 256 bits / 8 bits/byte = 32 bytes\nconst V1_HASHFUNC = \"sha512\";\n// ^ hash function used with pbkdf2. Chosen to be different from the function which maps the token\n// to the value stored in the database. Note that the first thing that pbkdf2 does is\n// HMAC(HASHFUNC, key, salt), and the first thing that HMAC does is either pad or hash the key to\n// make it the appropriate width. The result is that knowing sha256(key) and the salt is possibly\n// sufficient to reconstruct the output of pbkdf2().\nconst V1_CIPHER = \"AES-256-CTR\"; // cipher used", "const TOKEN_EXPIRATION_MS = 60 * 60 * 1000;", "const cleanupExpiredTokens = function () {\n Meteor.users.update({\n \"services.email.tokens.createdAt\": {\n $lt: new Date(Date.now() - TOKEN_EXPIRATION_MS),\n },\n }, {\n $pull: {\n \"services.email.tokens\": {\n createdAt: { $lt: new Date(Date.now() - TOKEN_EXPIRATION_MS) },\n },\n },\n }, {\n multi: true,\n });\n};", "Meteor.startup(cleanupExpiredTokens);\n// Tokens can actually last up to 2 * TOKEN_EXPIRATION_MS\nSandstormDb.periodicCleanup(TOKEN_EXPIRATION_MS, cleanupExpiredTokens);", "const hashToken = (token) => {\n return {\n digest: SHA256(token),\n algorithm: \"sha-256\",\n };\n};", "const checkToken = function (tokens, token) {\n // Looks for an object in `tokens` with `algorithm` and `digest` fields matching those in `token`.\n // Returns the matching object, if one is found, or undefined if none match.\n let foundToken = undefined;\n tokens.forEach(function (userToken) {\n if ((userToken.algorithm === token.algorithm) &&\n (userToken.digest === token.digest)) {\n foundToken = userToken;\n }\n });", " return foundToken;\n};", "const consumeToken = function (user, token) {\n const hashedToken = hashToken(token);\n const foundToken = checkToken(user.services.email.tokens, hashedToken);", " if (foundToken !== undefined) {\n Meteor.users.update({ _id: user._id }, { $pull: { \"services.email.tokens\": hashedToken } });\n }", " return foundToken;\n};", "const makeBox = function (token, plaintext) {\n // Encrypt plaintext symmetrically with a key derived from token. Returns an object with\n // ciphertext and associated data needed to decrypt later.", " // Produce a symmetric key. Note that the token itself does not have sufficient entropy to\n // be used as a key directly, so we need to use a KDF with a strong random salt.\n // In the fullness of time, it might be nice to move away from using a KDF (which blocks the whole\n // node process) in favor of the token itself having enough entropy to serve as the key itself.\n // This would require lengthening the token, which would make the manual-code-entry workflow\n // worse, so I'm punting on that for now.\n const salt = Random.secret(16);\n const key = crypto.pbkdf2Sync(token, salt, V1_ROUNDS, V1_KEYSIZE, V1_HASHFUNC);\n const iv = crypto.randomBytes(16);\n const cipher = crypto.createCipheriv(V1_CIPHER, key, iv);\n let ciphertext = cipher.update(new Buffer(plaintext, \"binary\"));\n return {\n version: 1,\n salt: salt,\n iv: iv.toString(\"base64\"),\n boxedValue: ciphertext.toString(\"base64\"),\n };\n};", "const tryUnbox = function (box, secret) {\n if (box) {\n if (box.version === 1) {\n const key = crypto.pbkdf2Sync(secret, box.salt, V1_ROUNDS, V1_KEYSIZE, V1_HASHFUNC);\n const iv = new Buffer(box.iv, \"base64\");\n const cipher = crypto.createDecipheriv(V1_CIPHER, key, iv);\n const cipherText = new Buffer(box.boxedValue, \"base64\");\n const plaintext = cipher.update(cipherText);\n return plaintext.toString(\"binary\");\n }\n }", " // If no box was provided, or it was of an unknown version, return no data.\n return;\n};", "// Handler to login with a token.\nAccounts.registerLoginHandler(\"email\", function (options) {\n if (!options.email) {\n return undefined; // don't handle\n }", " if (!Accounts.identityServices.email.isEnabled()) {\n throw new Meteor.Error(403, \"Email identity service is disabled.\");\n }", " options = options.email;\n check(options, {\n email: String,\n token: String,\n });", " const user = Meteor.users.findOne({\n \"services.email.email\": options.email,\n }, {\n fields: {\n \"services.email\": 1,\n },\n });", " if (!user) {\n console.error(\"User not found:\", options.email);\n return {\n error: new Meteor.Error(403, \"User not found\"),\n };\n }", " if (!user.services.email.tokens) {\n console.error(\"User has no token set:\", options.email);\n return {\n error: new Meteor.Error(403, \"User has no token set\"),\n };\n }", " const tokenString = options.token.trim();\n const maybeToken = consumeToken(user, tokenString);\n if (!maybeToken) {\n console.error(\"Token not found:\", options.email);\n return {\n error: new Meteor.Error(403, \"Invalid authentication code\"),\n };\n }", " // Attempt to decrypt the resumePath, if provided.\n const resumePath = tryUnbox(maybeToken.secureBox, tokenString);", " return {\n userId: user._id,\n options: {\n resumePath,\n },\n };\n});", "const makeTokenUrl = function (email, token, options) {\n if (options.linking) {\n return options.rootUrl + \"/_emailLinkIdentity/\" + encodeURIComponent(email) + \"/\" +\n encodeURIComponent(token) + \"/\" + Meteor.userId() +\n \"?allowLogin=\" + options.linking.allowLogin;\n } else {\n return options.rootUrl + \"/_emailLogin/\" + encodeURIComponent(email) + \"/\" + encodeURIComponent(token);\n }\n};", "///\n/// EMAIL VERIFICATION\n///\nconst sendTokenEmail = function (db, email, token, options) {\n let subject;\n let text;", " const rootHostname = Url.parse(options.rootUrl).hostname;", " if (!options.linking) {\n subject = \"Log in to \" + rootHostname;\n text = \"To confirm this email address on \";\n } else {\n subject = \"Confirm this email address on \" + rootHostname;\n text = \"To confirm this email address on \";\n }", " text = text + rootHostname + \", click on the following link:\\n\\n\" +\n makeTokenUrl(email, token, options) + \"\\n\\n\" +\n \"Alternatively, enter the following one-time authentication code into the log-in form:\\n\\n\" +\n token;", " const sendOptions = {\n to: email,", " from: { name: globalDb.getServerTitle(), address: db.getReturnAddress() },", " subject: subject,\n text: text,\n };", " sendEmail(sendOptions);\n};", "const parsedRootUrl = Url.parse(process.env.ROOT_URL);\n///\n/// CREATING USERS\n///\n// returns the user id\nconst createAndEmailTokenForUser = function (db, email, options) {\n check(email, String);\n check(options, {\n resumePath: String,\n linking: Match.Optional({ allowLogin: Boolean }),\n rootUrl: String,\n });", " const parsedUrl = Url.parse(options.rootUrl);\n if ((parsedUrl.hostname !== parsedRootUrl.hostname ||\n parsedUrl.protocol !== parsedRootUrl.protocol) &&\n !db.hostIsStandalone(parsedUrl.hostname)) {\n // Ignore port and only check hostname/protocol since IE will differ from other browsers and\n // sometimes include port 80/443 and sometimes won't\n throw new Meteor.Error(400, \"rootUrl is not valid\");\n }", " const atIndex = email.indexOf(\"@\");\n if (atIndex === -1) {\n throw new Meteor.Error(400, \"No @ symbol was found in your email\");\n }", " let user = Meteor.users.findOne({ \"services.email.email\": email },\n { fields: { \"services.email\": 1 } });\n let userId;", " // TODO(someday): make this shorter, and handle requests that try to brute force it.\n // Alternately, require using the link over copy/pasting the code, and crank up the entropy.\n const token = Random.id(12);\n const tokenObj = hashToken(token);\n tokenObj.createdAt = new Date();\n tokenObj.secureBox = makeBox(token, options.resumePath);", " if (user) {\n if (user.services.email.tokens && user.services.email.tokens.length > 2) {\n throw new Meteor.Error(\n \"alreadySentEmailToken\",\n \"It looks like we sent a log in email to this address not long \" +\n \"ago. Please use the one that was already sent (check your spam folder if you can't find \" +\n \"it), or wait a while and try again.\");\n }", " userId = user._id;", " Meteor.users.update({ _id: user._id }, { $push: { \"services.email.tokens\": tokenObj } });\n } else {\n const options = {};\n user = {\n services: {\n email: {\n tokens: [tokenObj],\n email: email,\n },\n },\n };", " userId = Accounts.insertUserDoc(options, user);\n }", " sendTokenEmail(db, email, token, options);", " return userId;\n};", "Meteor.methods({\n createAndEmailTokenForUser: function (email, options) {\n // method for create user. Requests come from the client.\n // This method will create a user if it doesn't exist, otherwise it will generate a token.\n // It will always send an email to the user", " check(email, String);\n check(options, {\n resumePath: String,\n linking: Match.Optional({ allowLogin: Boolean }),\n rootUrl: String,\n });", " if (!Accounts.identityServices.email.isEnabled()) {\n throw new Meteor.Error(403, \"Email identity service is disabled.\");\n }\n // Create user. result contains id and token.\n const user = createAndEmailTokenForUser(this.connection.sandstormDb, email, options);\n },", " linkEmailIdentityToAccount: function (email, token, allowLogin) {\n // Links the email identity with address `email` and login token `token` to the current account.\n check(email, String);\n check(token, String);\n check(allowLogin, Boolean);\n const account = Meteor.user();\n if (!account || !account.loginIdentities) {\n throw new Meteor.Error(403, \"Must be logged in to an account to link an email identity.\");\n }", " const identity = Meteor.users.findOne({ \"services.email.email\": email },\n { fields: { \"services.email\": 1 } });\n if (!identity) {\n throw new Meteor.Error(403, \"Invalid authentication code.\");\n }", " const maybeToken = consumeToken(identity, token.trim());\n if (!maybeToken) {\n throw new Meteor.Error(403, \"Invalid authentication code.\");\n }", " Accounts.linkIdentityToAccount(this.connection.sandstormDb, this.connection.sandstormBackend,\n identity._id, account._id, allowLogin);", " // Return the resume path, if we have one.\n const resumePath = tryUnbox(maybeToken.secureBox, token);\n return resumePath;\n },\n});" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [84, 1522, 203, 231], "buggy_code_start_loc": [77, 1518, 202, 188], "filenames": ["shell/imports/server/email.js", "shell/packages/sandstorm-db/db.js", "shell/server/accounts/email-token/token-server.js", "shell/server/admin-server.js"], "fixing_code_end_loc": [121, 1524, 203, 232], "fixing_code_start_loc": [78, 1519, 202, 188], "message": "A remote attacker could bypass the Sandstorm organization restriction before build 0.203 via a comma in an email-address field.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sandstorm:sandstorm:*:*:*:*:*:*:*:*", "matchCriteriaId": "683ED5F0-D297-4A47-ADF9-186832F3A3AD", "versionEndExcluding": "0.203", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A remote attacker could bypass the Sandstorm organization restriction before build 0.203 via a comma in an email-address field."}, {"lang": "es", "value": "Un atacante remoto podr\u00eda omitir la restricci\u00f3n de organizaci\u00f3n de Sandstorm antes de la build 0.203 mediante una coma en un campo email-address."}], "evaluatorComment": null, "id": "CVE-2017-6199", "lastModified": "2018-03-13T19:27:30.200", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-02-06T16:29:00.730", "references": [{"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://devco.re/blog/2018/01/26/Sandstorm-Security-Review-CVE-2017-6200-en/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/sandstorm-io/sandstorm/blob/v0.202/shell/packages/sandstorm-db/db.js#L1112"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/sandstorm-io/sandstorm/commit/37bd9a7f4eb776cdc2d3615f0bfea1254b66f59d"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://sandstorm.io/news/2017-03-02-security-review"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-287"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/sandstorm-io/sandstorm/commit/37bd9a7f4eb776cdc2d3615f0bfea1254b66f59d"}, "type": "CWE-287"}
324
Determine whether the {function_name} code is vulnerable or not.
[ "// Sandstorm - Personal Cloud Sandbox\n// Copyright (c) 2014 Sandstorm Development Group, Inc. and contributors\n// All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.", "import { Meteor } from \"meteor/meteor\";\nimport Fs from \"fs\";\nimport Crypto from \"crypto\";\nimport Heapdump from \"heapdump\";\nimport { SANDSTORM_LOGDIR } from \"/imports/server/constants.js\";\nimport { clearAdminToken, checkAuth, tokenIsValid, tokenIsSetupSession } from \"/imports/server/auth.js\";\nimport { send as sendEmail } from \"/imports/server/email.js\";\nimport { fillUndefinedForChangedDoc } from \"/imports/server/observe-helpers.js\";", "const publicAdminSettings = [\n \"google\", \"github\", \"ldap\", \"saml\", \"emailToken\", \"splashUrl\", \"signupDialog\",\n \"adminAlert\", \"adminAlertTime\", \"adminAlertUrl\", \"termsUrl\",\n \"privacyUrl\", \"appMarketUrl\", \"appIndexUrl\", \"appUpdatesEnabled\",\n \"serverTitle\", \"returnAddress\", \"ldapNameField\", \"organizationMembership\",\n \"organizationSettings\",\n \"whitelabelCustomLoginProviderName\",\n \"whitelabelCustomLogoAssetId\",\n \"whitelabelHideSendFeedback\",\n \"whitelabelHideTroubleshooting\",\n \"whiteLabelHideAbout\",\n \"whitelabelUseServerTitleForHomeText\",\n \"quotaEnabled\",\n \"quotaLdapEnabled\",\n \"billingPromptUrl\",\n];", "const smtpConfigShape = {\n hostname: String,\n port: Number,\n auth: {\n user: String,\n pass: String,\n },\n returnAddress: String,\n};", "Meteor.methods({\n setAccountSetting: function (token, serviceName, value) {\n checkAuth(token);\n check(serviceName, String);\n check(value, Boolean);", " // TODO(someday): currently this relies on the fact that an account is tied to a single\n // identity, and thus has only that entry in \"services\". This will need to be looked at when\n // multiple login methods/identities are allowed for a single account.\n if (!value && !tokenIsValid(token) && !tokenIsSetupSession(token) && (serviceName in Meteor.user().services)) {\n throw new Meteor.Error(403,\n \"You can not disable the login service that your account uses.\");\n }", " // Only check configurations for OAuth services.\n const oauthServices = [\"google\", \"github\"];\n if (value && (oauthServices.indexOf(serviceName) != -1)) {\n const config = ServiceConfiguration.configurations.findOne({ service: serviceName });\n if (!config) {\n throw new Meteor.Error(403, \"You must configure the \" + serviceName +\n \" service before you can enable it. Click the \\\"configure\\\" link.\");\n }", " if (!config.clientId || !config.secret) {\n throw new Meteor.Error(403, \"You must provide a non-empty clientId and secret for the \" +\n serviceName + \" service before you can enable it. Click the \\\"configure\\\" link.\");\n }\n }", " Settings.upsert({ _id: serviceName }, { $set: { value: value } });\n if (value) {\n Settings.update({ _id: serviceName }, { $unset: { automaticallyReset: 1 } });\n }\n },", " setSmtpConfig: function (token, config) {\n checkAuth(token);\n check(config, smtpConfigShape);", " Settings.upsert({ _id: \"smtpConfig\" }, { $set: { value: config } });\n },", " disableEmail: function (token) {\n checkAuth(token);", " const db = this.connection.sandstormDb;\n db.collections.settings.update({ _id: \"smtpConfig\" }, { $set: { \"value.hostname\": \"\" } });\n },", " setSetting: function (token, name, value) {\n checkAuth(token);\n check(name, String);\n check(value, Match.OneOf(null, String, Date, Boolean));", " Settings.upsert({ _id: name }, { $set: { value: value } });\n },", " saveOrganizationSettings(token, params) {\n checkAuth(token);\n check(params, {\n membership: {\n emailToken: {\n enabled: Boolean,\n domain: String,\n },\n google: {\n enabled: Boolean,\n domain: String,\n },\n ldap: {\n enabled: Boolean,\n },\n saml: {\n enabled: Boolean,\n },\n },\n settings: {\n disallowGuests: Boolean,\n shareContacts: Boolean,\n },\n });", " this.connection.sandstormDb.collections.settings.upsert({ _id: \"organizationMembership\" }, { value: params.membership });\n this.connection.sandstormDb.collections.settings.upsert({ _id: \"organizationSettings\" }, { value: params.settings });\n },", " adminConfigureLoginService: function (token, options) {\n checkAuth(token);\n check(options, Match.ObjectIncluding({ service: String }));", " ServiceConfiguration.configurations.upsert({ service: options.service }, options);\n },", " clearResumeTokensForService: function (token, serviceName) {\n checkAuth(token);\n check(serviceName, String);", " const query = {};\n query[\"services.\" + serviceName] = { $exists: true };\n Meteor.users.find(query).forEach(function (identity) {\n if (identity.services.resume && identity.services.resume.loginTokens &&\n identity.services.resume.loginTokens.length > 0) {\n Meteor.users.update({ _id: identity._id }, { $set: { \"services.resume.loginTokens\": [] } });\n }", " Meteor.users.update({ \"loginIdentities.id\": identity._id },\n { $set: { \"services.resume.loginTokens\": [] } });\n });\n },", " adminUpdateUser: function (token, userInfo) {\n checkAuth(token);\n check(userInfo, {\n userId: String,\n signupKey: Boolean,\n isAdmin: Boolean,\n });", " const userId = userInfo.userId;\n if (userId === Meteor.userId() && !userInfo.isAdmin) {\n throw new Meteor.Error(403, \"User cannot remove admin permissions from itself.\");\n }", " Meteor.users.update({ _id: userId }, { $set: _.omit(userInfo, [\"_id\", \"userId\"]) });\n },", " testSend: function (token, smtpConfig, to) {\n checkAuth(token);\n check(smtpConfig, smtpConfigShape);\n check(to, String);\n const { returnAddress, ...restConfig } = smtpConfig;", " try {\n sendEmail({\n to: to,", " from: globalDb.getServerTitle() + \" <\" + returnAddress + \">\",", " subject: \"Testing your Sandstorm's SMTP setting\",\n text: \"Success! Your outgoing SMTP is working.\",\n smtpConfig: restConfig,\n });\n } catch (e) {\n // Attempt to give more accurate error messages for a variety of known failure modes,\n // and the actual exception data in the event a user hits a new failure mode.\n if (e.syscall === \"getaddrinfo\") {\n if (e.code === \"EIO\" || e.code === \"ENOTFOUND\") {\n throw new Meteor.Error(\"getaddrinfo \" + e.code, \"Couldn't resolve \\\"\" + smtpConfig.hostname + \"\\\" - check for typos or broken DNS.\");\n }\n } else if (e.syscall === \"connect\") {\n if (e.code === \"ECONNREFUSED\") {\n throw new Meteor.Error(\"connect ECONNREFUSED\", \"Server at \" + smtpConfig.hostname + \":\" + smtpConfig.port + \" refused connection. Check your settings, firewall rules, and that your mail server is up.\");\n }\n } else if (e.name === \"AuthError\") {\n throw new Meteor.Error(\"auth error\", \"Authentication failed. Check your credentials. Message from \" +\n smtpConfig.hostname + \": \" + e.data);\n }", " throw new Meteor.Error(\"other-email-sending-error\", \"Error while trying to send test email: \" + JSON.stringify(e));\n }\n },", " createSignupKey: function (token, note, quota) {\n checkAuth(token);\n check(note, String);\n check(quota, Match.OneOf(undefined, null, Number));", " const key = Random.id();\n const content = { _id: key, used: false, note: note };\n if (typeof quota === \"number\") content.quota = quota;\n SignupKeys.insert(content);\n return key;\n },", " sendInvites: function (token, origin, from, list, subject, message, quota) {\n checkAuth(token);", " check([origin, from, list, subject, message], [String]);", " check(quota, Match.OneOf(undefined, null, Number));\n", " if (!from.trim()) {", " throw new Meteor.Error(403, \"Must enter 'from' address.\");\n }", " if (!list.trim()) {\n throw new Meteor.Error(403, \"Must enter 'to' addresses.\");\n }", " this.unblock();", " list = list.split(\"\\n\");\n for (const i in list) {\n const email = list[i].trim();", " if (email) {\n const key = Random.id();", " const content = {\n _id: key,\n used: false,\n note: \"E-mail invite to \" + email,\n email: email,\n definitelySent: false,\n };\n if (typeof quota === \"number\") content.quota = quota;\n SignupKeys.insert(content);\n sendEmail({\n to: email,\n from: from,\n envelopeFrom: globalDb.getReturnAddress(),\n subject: subject,\n text: message.replace(/\\$KEY/g, origin + \"/signup/\" + key),\n });\n SignupKeys.update(key, { $set: { definitelySent: true } });\n }\n }", " return { sent: true };\n },", " adminToggleDisableCap: function (token, capId, value) {\n checkAuth(token);\n check(capId, String);\n check(value, Boolean);", " if (value) {\n ApiTokens.update({ _id: capId }, { $set: { revoked: true } });\n } else {\n ApiTokens.update({ _id: capId }, { $set: { revoked: false } });\n }\n },", " updateQuotas: function (token, list, quota) {\n checkAuth(token);\n check(list, String);\n check(quota, Match.OneOf(undefined, null, Number));", " if (!list.trim()) {\n throw new Meteor.Error(400, \"Must enter addresses.\");\n }", " const items = list.split(\"\\n\");\n const invalid = [];\n for (const i in items) {\n const modifier = (typeof quota === \"number\") ? { $set: { quota: quota } }\n : { $unset: { quota: \"\" } };\n let n = SignupKeys.update({ email: items[i] }, modifier, { multi: true });\n n += Meteor.users.update({ signupEmail: items[i] }, modifier, { multi: true });", " if (n < 1) invalid.push(items[i]);\n }", " if (invalid.length > 0) {\n throw new Meteor.Error(404, \"These addresses did not map to any user nor invite: \" +\n invalid.join(\", \"));\n }\n },", " dismissAdminStatsNotifications: function (token) {\n checkAuth(token);\n globalDb.collections.notifications.remove({ \"admin.type\": \"reportStats\" });\n },", " signUpAsAdmin: function (token) {\n check(token, String);\n checkAuth(token);\n if (!this.userId) {\n throw new Meteor.Error(403, \"Must be logged in to sign up as admin.\");\n }", " if (!Meteor.user().loginIdentities) {\n throw new Meteor.Error(403, \"Must be logged into an account to sign up as admin.\");\n }", " Meteor.users.update({ _id: this.userId }, { $set: { isAdmin: true, signupKey: \"admin\" } });\n clearAdminToken(token);\n },", " redeemSetupToken(token) {\n // Redeem an admin token into a setup session.\n check(token, String);\n if (tokenIsValid(token)) {\n const sessId = Random.secret();\n const creationDate = new Date();\n const hashedSessionId = Crypto.createHash(\"sha256\").update(sessId).digest(\"base64\");\n this.connection.sandstormDb.collections.setupSession.upsert({\n _id: \"current-session\",\n }, {\n creationDate,\n hashedSessionId,\n });\n // Then, invalidate the token, so one one else can use it.\n clearAdminToken(token);\n return sessId;\n } else {\n throw new Meteor.Error(401, \"Invalid setup token\");\n }\n },", " heapdump() {\n // Requests a heap dump. Intended for use by Sandstorm developers. Requires admin.\n //\n // Call this from the JS console like:\n // Meteor.call(\"heapdump\");", " checkAuth();", " // We use /var/log because it's a location in the container to which the front-end is allowed\n // to write.\n const name = \"/var/log/\" + Date.now() + \".heapsnapshot\";\n Heapdump.writeSnapshot(name);\n console.log(\"Wrote heapdump: /opt/sandstorm\" + name);\n return name;\n },", " setPreinstalledApps: function (appAndPackageIds) {\n checkAuth();\n check(appAndPackageIds, [{ appId: String, packageId: String, }]);", " this.connection.sandstormDb.setPreinstalledApps(appAndPackageIds);\n },\n});", "const authorizedAsAdmin = function (token, userId) {\n return Match.test(token, Match.OneOf(undefined, null, String)) &&\n ((userId && isAdminById(userId)) || tokenIsValid(token) || tokenIsSetupSession(token));\n};", "Meteor.publish(\"admin\", function (token) {\n if (!authorizedAsAdmin(token, this.userId)) return [];\n return Settings.find();\n});", "Meteor.publish(\"adminServiceConfiguration\", function (token) {\n if (!authorizedAsAdmin(token, this.userId)) return [];\n return ServiceConfiguration.configurations.find();\n});", "Meteor.publish(\"publicAdminSettings\", function () {\n return Settings.find({ _id: { $in: publicAdminSettings } });\n});", "Meteor.publish(\"adminToken\", function (token) {\n check(token, String);\n this.added(\"adminToken\", \"adminToken\", { tokenIsValid: tokenIsValid(token) || tokenIsSetupSession(token) });\n this.ready();\n});", "Meteor.publish(\"allUsers\", function (token) {\n if (!authorizedAsAdmin(token, this.userId)) return [];\n return Meteor.users.find();\n});", "Meteor.publish(\"adminUserDetails\", function (userId) {\n if (!authorizedAsAdmin(undefined, this.userId)) return [];", " // Reactive publish of any identities owned by the account with id userId,\n // as well as that user object itself.\n const identitySubs = {};\n const accountId = userId;", " const unrefIdentity = (identityId) => {\n if (!identitySubs[identityId]) {\n // should never happen, but if somehow you attempt to unref an identity that we don't have a\n // subscription to, then don't crash\n console.error(\"attempted to unref untracked identity id:\", identityId);\n return;\n }", " const observeHandle = identitySubs[identityId];\n delete identitySubs[identityId];\n observeHandle.stop();\n this.removed(\"users\", identityId);\n };", " const refIdentity = (identityId) => {\n if (identitySubs[identityId]) {\n // should never happen, but if somehow an account wound up with a duplicate identity ID,\n // avoid leaking a subscription\n console.error(\"duplicate identity id:\", identityId);\n return;\n }", " const cursor = Meteor.users.find({ _id: identityId });\n const observeHandle = cursor.observe({\n added: (doc) => {\n this.added(\"users\", doc._id, doc);\n },", " changed: (newDoc, oldDoc) => {\n fillUndefinedForChangedDoc(newDoc, oldDoc);\n this.changed(\"users\", newDoc._id, newDoc);\n },", " removed: (oldDoc) => {\n this.removed(\"users\", oldDoc._id);\n },\n });", " identitySubs[identityId] = observeHandle;\n };", " const accountCursor = Meteor.users.find({ _id: accountId });\n const accountSubHandle = accountCursor.observe({\n added: (newDoc) => {\n const newIdentities = SandstormDb.getUserIdentityIds(newDoc);\n newIdentities.forEach((identityId) => {\n refIdentity(identityId);\n });", " this.added(\"users\", newDoc._id, newDoc);\n },", " changed: (newDoc, oldDoc) => {\n const newIdentities = SandstormDb.getUserIdentityIds(newDoc);\n const oldIdentities = SandstormDb.getUserIdentityIds(oldDoc);", " // Those in newDoc - oldDoc, ref.\n const identitiesAdded = _.difference(newIdentities, oldIdentities);\n identitiesAdded.forEach((identityId) => {\n refIdentity(identityId);\n });", " // Those in oldDoc - newDoc, unref.\n const identitiesRemoved = _.difference(oldIdentities, newIdentities);\n identitiesRemoved.forEach((identityId) => {\n unrefIdentity(identityId);\n });", " fillUndefinedForChangedDoc(newDoc, oldDoc);", " this.changed(\"users\", newDoc._id, newDoc);\n },", " removed: (oldDoc) => {\n this.removed(\"users\", oldDoc._id);\n const oldIdentities = SandstormDb.getUserIdentityIds(oldDoc);\n oldIdentities.forEach((identityId) => {\n unrefIdentity(identityId);\n });\n },\n });", " this.onStop(() => {\n accountSubHandle.stop();\n // Also stop all the identity subscriptions.\n const subs = _.values(identitySubs);\n subs.forEach((sub) => {\n sub.stop();\n });\n });", " // Meteor's cursor.observe() will synchronously call all of the added() callbacks from the initial\n // query, so by the time we get here we can report readiness.\n this.ready();\n});", "Meteor.publish(\"activityStats\", function (token) {\n if (!authorizedAsAdmin(token, this.userId)) return [];\n return ActivityStats.find();\n});", "Meteor.publish(\"statsTokens\", function (token) {\n if (!authorizedAsAdmin(token, this.userId)) return [];\n return StatsTokens.find();\n});", "Meteor.publish(\"allPackages\", function (token) {\n if (!authorizedAsAdmin(token, this.userId)) return [];\n return Packages.find({ manifest: { $exists: true } },\n { fields: { appId: 1, \"manifest.appVersion\": 1,\n \"manifest.actions\": 1, \"manifest.appTitle\": 1, progress: 1, status: 1, }, });\n});", "Meteor.publish(\"realTimeStats\", function (token) {\n if (!authorizedAsAdmin(token, this.userId)) return [];", " // Last five minutes.\n this.added(\"realTimeStats\", \"now\", computeStats(new Date(Date.now() - 5 * 60 * 1000)));", " // Since last sample.\n const lastSample = ActivityStats.findOne({}, { sort: { timestamp: -1 } });\n const lastSampleTime = lastSample ? lastSample.timestamp : new Date(0);\n this.added(\"realTimeStats\", \"today\", computeStats(lastSampleTime));", " // TODO(someday): Update every few minutes?", " this.ready();\n});", "Meteor.publish(\"adminLog\", function (token) {\n if (!authorizedAsAdmin(token, this.userId)) return [];", " const logfile = SANDSTORM_LOGDIR + \"/sandstorm.log\";", " const fd = Fs.openSync(logfile, \"r\");\n const startSize = Fs.fstatSync(fd).size;", " // Difference between the current file offset and the subscription offset. Can be non-zero when\n // logs have rotated.\n let extraOffset = 0;", " if (startSize < 8192) {\n // Log size is less than window size. Check for rotated log and grab its tail.\n const logfile1 = SANDSTORM_LOGDIR + \"/sandstorm.log.1\";\n if (Fs.existsSync(logfile1)) {\n const fd1 = Fs.openSync(logfile1, \"r\");\n const startSize1 = Fs.fstatSync(fd1).size;\n const amountFromLog1 = Math.min(startSize1, 8192 - startSize);\n const offset1 = startSize1 - amountFromLog1;\n const buf = new Buffer(amountFromLog1);\n const n = Fs.readSync(fd1, buf, 0, buf.length, offset);\n if (n > 0) {\n this.added(\"adminLog\", 0, { text: buf.toString(\"utf8\", 0, n) });\n extraOffset += n;\n }\n }\n }", " // Start tailing at EOF - 8k.\n let offset = Math.max(0, startSize - 8192);", " const _this = this;\n function doTail() {\n if (Fs.fstatSync(fd).size < offset) {\n extraOffset += offset;\n offset = 0;\n }", " for (;;) {\n const buf = new Buffer(Math.max(1024, startSize - offset));\n const n = Fs.readSync(fd, buf, 0, buf.length, offset);\n if (n <= 0) break;\n _this.added(\"adminLog\", offset + extraOffset, { text: buf.toString(\"utf8\", 0, n) });\n offset += n;\n }\n }", " // Watch the file for changes.\n const watcher = Fs.watch(logfile, { persistent: false }, Meteor.bindEnvironment(doTail));", " // When the subscription stops, stop watching the file.\n this.onStop(function () {\n watcher.close();\n Fs.closeSync(fd);\n });", " // Read initial 8k tail data immediately.\n doTail();", " // Notify ready.\n this.ready();\n});", "Meteor.publish(\"adminApiTokens\", function (token) {\n if (!authorizedAsAdmin(token, this.userId)) return [];\n return ApiTokens.find({\n $or: [\n { \"frontendRef.ipNetwork\": { $exists: true } },\n { \"frontendRef.ipInterface\": { $exists: true } },\n ],\n }, {\n fields: {\n frontendRef: 1,\n created: 1,\n requirements: 1,\n revoked: 1,\n owner: 1,\n },\n });\n});", "Meteor.publish(\"hasAdmin\", function (token) {\n // Like hasUsers, but for admins, and with token auth required.\n if (!authorizedAsAdmin(token, this.userId)) return [];", " // Query if there are any admin users.\n const cursor = Meteor.users.find({ isAdmin: true });\n if (cursor.count() > 0) {\n this.added(\"hasAdmin\", \"hasAdmin\", { hasAdmin: true });\n } else {\n let handle = cursor.observeChanges({\n added: (id) => {\n this.added(\"hasAdmin\", \"hasAdmin\", { hasAdmin: true });\n handle.stop();\n handle = null;\n },\n });\n this.onStop(function () {\n if (handle) handle.stop();\n });\n }", " this.ready();\n});", "Meteor.publish(\"appIndexAdmin\", function (token) {\n if (!authorizedAsAdmin(token, this.userId)) return [];\n return globalDb.collections.appIndex.find();\n});", "function observeOauthService(name) {\n Settings.find({ _id: name, value: true }).observe({\n added: function () {\n // Tell the oauth library it should accept login attempts from this service.\n Accounts.oauth.registerService(name);\n },", " removed: function () {\n // Tell the oauth library it should deny login attempts from this service.\n Accounts.oauth.unregisterService(name);\n },\n });\n}", "observeOauthService(\"github\");\nobserveOauthService(\"google\");" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [84, 1522, 203, 231], "buggy_code_start_loc": [77, 1518, 202, 188], "filenames": ["shell/imports/server/email.js", "shell/packages/sandstorm-db/db.js", "shell/server/accounts/email-token/token-server.js", "shell/server/admin-server.js"], "fixing_code_end_loc": [121, 1524, 203, 232], "fixing_code_start_loc": [78, 1519, 202, 188], "message": "A remote attacker could bypass the Sandstorm organization restriction before build 0.203 via a comma in an email-address field.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sandstorm:sandstorm:*:*:*:*:*:*:*:*", "matchCriteriaId": "683ED5F0-D297-4A47-ADF9-186832F3A3AD", "versionEndExcluding": "0.203", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A remote attacker could bypass the Sandstorm organization restriction before build 0.203 via a comma in an email-address field."}, {"lang": "es", "value": "Un atacante remoto podr\u00eda omitir la restricci\u00f3n de organizaci\u00f3n de Sandstorm antes de la build 0.203 mediante una coma en un campo email-address."}], "evaluatorComment": null, "id": "CVE-2017-6199", "lastModified": "2018-03-13T19:27:30.200", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-02-06T16:29:00.730", "references": [{"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://devco.re/blog/2018/01/26/Sandstorm-Security-Review-CVE-2017-6200-en/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/sandstorm-io/sandstorm/blob/v0.202/shell/packages/sandstorm-db/db.js#L1112"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/sandstorm-io/sandstorm/commit/37bd9a7f4eb776cdc2d3615f0bfea1254b66f59d"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://sandstorm.io/news/2017-03-02-security-review"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-287"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/sandstorm-io/sandstorm/commit/37bd9a7f4eb776cdc2d3615f0bfea1254b66f59d"}, "type": "CWE-287"}
324
Determine whether the {function_name} code is vulnerable or not.
[ "// Sandstorm - Personal Cloud Sandbox\n// Copyright (c) 2014 Sandstorm Development Group, Inc. and contributors\n// All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.", "import { Meteor } from \"meteor/meteor\";\nimport Fs from \"fs\";\nimport Crypto from \"crypto\";\nimport Heapdump from \"heapdump\";\nimport { SANDSTORM_LOGDIR } from \"/imports/server/constants.js\";\nimport { clearAdminToken, checkAuth, tokenIsValid, tokenIsSetupSession } from \"/imports/server/auth.js\";\nimport { send as sendEmail } from \"/imports/server/email.js\";\nimport { fillUndefinedForChangedDoc } from \"/imports/server/observe-helpers.js\";", "const publicAdminSettings = [\n \"google\", \"github\", \"ldap\", \"saml\", \"emailToken\", \"splashUrl\", \"signupDialog\",\n \"adminAlert\", \"adminAlertTime\", \"adminAlertUrl\", \"termsUrl\",\n \"privacyUrl\", \"appMarketUrl\", \"appIndexUrl\", \"appUpdatesEnabled\",\n \"serverTitle\", \"returnAddress\", \"ldapNameField\", \"organizationMembership\",\n \"organizationSettings\",\n \"whitelabelCustomLoginProviderName\",\n \"whitelabelCustomLogoAssetId\",\n \"whitelabelHideSendFeedback\",\n \"whitelabelHideTroubleshooting\",\n \"whiteLabelHideAbout\",\n \"whitelabelUseServerTitleForHomeText\",\n \"quotaEnabled\",\n \"quotaLdapEnabled\",\n \"billingPromptUrl\",\n];", "const smtpConfigShape = {\n hostname: String,\n port: Number,\n auth: {\n user: String,\n pass: String,\n },\n returnAddress: String,\n};", "Meteor.methods({\n setAccountSetting: function (token, serviceName, value) {\n checkAuth(token);\n check(serviceName, String);\n check(value, Boolean);", " // TODO(someday): currently this relies on the fact that an account is tied to a single\n // identity, and thus has only that entry in \"services\". This will need to be looked at when\n // multiple login methods/identities are allowed for a single account.\n if (!value && !tokenIsValid(token) && !tokenIsSetupSession(token) && (serviceName in Meteor.user().services)) {\n throw new Meteor.Error(403,\n \"You can not disable the login service that your account uses.\");\n }", " // Only check configurations for OAuth services.\n const oauthServices = [\"google\", \"github\"];\n if (value && (oauthServices.indexOf(serviceName) != -1)) {\n const config = ServiceConfiguration.configurations.findOne({ service: serviceName });\n if (!config) {\n throw new Meteor.Error(403, \"You must configure the \" + serviceName +\n \" service before you can enable it. Click the \\\"configure\\\" link.\");\n }", " if (!config.clientId || !config.secret) {\n throw new Meteor.Error(403, \"You must provide a non-empty clientId and secret for the \" +\n serviceName + \" service before you can enable it. Click the \\\"configure\\\" link.\");\n }\n }", " Settings.upsert({ _id: serviceName }, { $set: { value: value } });\n if (value) {\n Settings.update({ _id: serviceName }, { $unset: { automaticallyReset: 1 } });\n }\n },", " setSmtpConfig: function (token, config) {\n checkAuth(token);\n check(config, smtpConfigShape);", " Settings.upsert({ _id: \"smtpConfig\" }, { $set: { value: config } });\n },", " disableEmail: function (token) {\n checkAuth(token);", " const db = this.connection.sandstormDb;\n db.collections.settings.update({ _id: \"smtpConfig\" }, { $set: { \"value.hostname\": \"\" } });\n },", " setSetting: function (token, name, value) {\n checkAuth(token);\n check(name, String);\n check(value, Match.OneOf(null, String, Date, Boolean));", " Settings.upsert({ _id: name }, { $set: { value: value } });\n },", " saveOrganizationSettings(token, params) {\n checkAuth(token);\n check(params, {\n membership: {\n emailToken: {\n enabled: Boolean,\n domain: String,\n },\n google: {\n enabled: Boolean,\n domain: String,\n },\n ldap: {\n enabled: Boolean,\n },\n saml: {\n enabled: Boolean,\n },\n },\n settings: {\n disallowGuests: Boolean,\n shareContacts: Boolean,\n },\n });", " this.connection.sandstormDb.collections.settings.upsert({ _id: \"organizationMembership\" }, { value: params.membership });\n this.connection.sandstormDb.collections.settings.upsert({ _id: \"organizationSettings\" }, { value: params.settings });\n },", " adminConfigureLoginService: function (token, options) {\n checkAuth(token);\n check(options, Match.ObjectIncluding({ service: String }));", " ServiceConfiguration.configurations.upsert({ service: options.service }, options);\n },", " clearResumeTokensForService: function (token, serviceName) {\n checkAuth(token);\n check(serviceName, String);", " const query = {};\n query[\"services.\" + serviceName] = { $exists: true };\n Meteor.users.find(query).forEach(function (identity) {\n if (identity.services.resume && identity.services.resume.loginTokens &&\n identity.services.resume.loginTokens.length > 0) {\n Meteor.users.update({ _id: identity._id }, { $set: { \"services.resume.loginTokens\": [] } });\n }", " Meteor.users.update({ \"loginIdentities.id\": identity._id },\n { $set: { \"services.resume.loginTokens\": [] } });\n });\n },", " adminUpdateUser: function (token, userInfo) {\n checkAuth(token);\n check(userInfo, {\n userId: String,\n signupKey: Boolean,\n isAdmin: Boolean,\n });", " const userId = userInfo.userId;\n if (userId === Meteor.userId() && !userInfo.isAdmin) {\n throw new Meteor.Error(403, \"User cannot remove admin permissions from itself.\");\n }", " Meteor.users.update({ _id: userId }, { $set: _.omit(userInfo, [\"_id\", \"userId\"]) });\n },", " testSend: function (token, smtpConfig, to) {\n checkAuth(token);\n check(smtpConfig, smtpConfigShape);\n check(to, String);\n const { returnAddress, ...restConfig } = smtpConfig;", " try {\n sendEmail({\n to: to,", " from: { name: globalDb.getServerTitle(), address: returnAddress },", " subject: \"Testing your Sandstorm's SMTP setting\",\n text: \"Success! Your outgoing SMTP is working.\",\n smtpConfig: restConfig,\n });\n } catch (e) {\n // Attempt to give more accurate error messages for a variety of known failure modes,\n // and the actual exception data in the event a user hits a new failure mode.\n if (e.syscall === \"getaddrinfo\") {\n if (e.code === \"EIO\" || e.code === \"ENOTFOUND\") {\n throw new Meteor.Error(\"getaddrinfo \" + e.code, \"Couldn't resolve \\\"\" + smtpConfig.hostname + \"\\\" - check for typos or broken DNS.\");\n }\n } else if (e.syscall === \"connect\") {\n if (e.code === \"ECONNREFUSED\") {\n throw new Meteor.Error(\"connect ECONNREFUSED\", \"Server at \" + smtpConfig.hostname + \":\" + smtpConfig.port + \" refused connection. Check your settings, firewall rules, and that your mail server is up.\");\n }\n } else if (e.name === \"AuthError\") {\n throw new Meteor.Error(\"auth error\", \"Authentication failed. Check your credentials. Message from \" +\n smtpConfig.hostname + \": \" + e.data);\n }", " throw new Meteor.Error(\"other-email-sending-error\", \"Error while trying to send test email: \" + JSON.stringify(e));\n }\n },", " createSignupKey: function (token, note, quota) {\n checkAuth(token);\n check(note, String);\n check(quota, Match.OneOf(undefined, null, Number));", " const key = Random.id();\n const content = { _id: key, used: false, note: note };\n if (typeof quota === \"number\") content.quota = quota;\n SignupKeys.insert(content);\n return key;\n },", " sendInvites: function (token, origin, from, list, subject, message, quota) {\n checkAuth(token);", " check(from, { name: String, address: String });\n check([origin, list, subject, message], [String]);", " check(quota, Match.OneOf(undefined, null, Number));\n", " if (!from.address.trim()) {", " throw new Meteor.Error(403, \"Must enter 'from' address.\");\n }", " if (!list.trim()) {\n throw new Meteor.Error(403, \"Must enter 'to' addresses.\");\n }", " this.unblock();", " list = list.split(\"\\n\");\n for (const i in list) {\n const email = list[i].trim();", " if (email) {\n const key = Random.id();", " const content = {\n _id: key,\n used: false,\n note: \"E-mail invite to \" + email,\n email: email,\n definitelySent: false,\n };\n if (typeof quota === \"number\") content.quota = quota;\n SignupKeys.insert(content);\n sendEmail({\n to: email,\n from: from,\n envelopeFrom: globalDb.getReturnAddress(),\n subject: subject,\n text: message.replace(/\\$KEY/g, origin + \"/signup/\" + key),\n });\n SignupKeys.update(key, { $set: { definitelySent: true } });\n }\n }", " return { sent: true };\n },", " adminToggleDisableCap: function (token, capId, value) {\n checkAuth(token);\n check(capId, String);\n check(value, Boolean);", " if (value) {\n ApiTokens.update({ _id: capId }, { $set: { revoked: true } });\n } else {\n ApiTokens.update({ _id: capId }, { $set: { revoked: false } });\n }\n },", " updateQuotas: function (token, list, quota) {\n checkAuth(token);\n check(list, String);\n check(quota, Match.OneOf(undefined, null, Number));", " if (!list.trim()) {\n throw new Meteor.Error(400, \"Must enter addresses.\");\n }", " const items = list.split(\"\\n\");\n const invalid = [];\n for (const i in items) {\n const modifier = (typeof quota === \"number\") ? { $set: { quota: quota } }\n : { $unset: { quota: \"\" } };\n let n = SignupKeys.update({ email: items[i] }, modifier, { multi: true });\n n += Meteor.users.update({ signupEmail: items[i] }, modifier, { multi: true });", " if (n < 1) invalid.push(items[i]);\n }", " if (invalid.length > 0) {\n throw new Meteor.Error(404, \"These addresses did not map to any user nor invite: \" +\n invalid.join(\", \"));\n }\n },", " dismissAdminStatsNotifications: function (token) {\n checkAuth(token);\n globalDb.collections.notifications.remove({ \"admin.type\": \"reportStats\" });\n },", " signUpAsAdmin: function (token) {\n check(token, String);\n checkAuth(token);\n if (!this.userId) {\n throw new Meteor.Error(403, \"Must be logged in to sign up as admin.\");\n }", " if (!Meteor.user().loginIdentities) {\n throw new Meteor.Error(403, \"Must be logged into an account to sign up as admin.\");\n }", " Meteor.users.update({ _id: this.userId }, { $set: { isAdmin: true, signupKey: \"admin\" } });\n clearAdminToken(token);\n },", " redeemSetupToken(token) {\n // Redeem an admin token into a setup session.\n check(token, String);\n if (tokenIsValid(token)) {\n const sessId = Random.secret();\n const creationDate = new Date();\n const hashedSessionId = Crypto.createHash(\"sha256\").update(sessId).digest(\"base64\");\n this.connection.sandstormDb.collections.setupSession.upsert({\n _id: \"current-session\",\n }, {\n creationDate,\n hashedSessionId,\n });\n // Then, invalidate the token, so one one else can use it.\n clearAdminToken(token);\n return sessId;\n } else {\n throw new Meteor.Error(401, \"Invalid setup token\");\n }\n },", " heapdump() {\n // Requests a heap dump. Intended for use by Sandstorm developers. Requires admin.\n //\n // Call this from the JS console like:\n // Meteor.call(\"heapdump\");", " checkAuth();", " // We use /var/log because it's a location in the container to which the front-end is allowed\n // to write.\n const name = \"/var/log/\" + Date.now() + \".heapsnapshot\";\n Heapdump.writeSnapshot(name);\n console.log(\"Wrote heapdump: /opt/sandstorm\" + name);\n return name;\n },", " setPreinstalledApps: function (appAndPackageIds) {\n checkAuth();\n check(appAndPackageIds, [{ appId: String, packageId: String, }]);", " this.connection.sandstormDb.setPreinstalledApps(appAndPackageIds);\n },\n});", "const authorizedAsAdmin = function (token, userId) {\n return Match.test(token, Match.OneOf(undefined, null, String)) &&\n ((userId && isAdminById(userId)) || tokenIsValid(token) || tokenIsSetupSession(token));\n};", "Meteor.publish(\"admin\", function (token) {\n if (!authorizedAsAdmin(token, this.userId)) return [];\n return Settings.find();\n});", "Meteor.publish(\"adminServiceConfiguration\", function (token) {\n if (!authorizedAsAdmin(token, this.userId)) return [];\n return ServiceConfiguration.configurations.find();\n});", "Meteor.publish(\"publicAdminSettings\", function () {\n return Settings.find({ _id: { $in: publicAdminSettings } });\n});", "Meteor.publish(\"adminToken\", function (token) {\n check(token, String);\n this.added(\"adminToken\", \"adminToken\", { tokenIsValid: tokenIsValid(token) || tokenIsSetupSession(token) });\n this.ready();\n});", "Meteor.publish(\"allUsers\", function (token) {\n if (!authorizedAsAdmin(token, this.userId)) return [];\n return Meteor.users.find();\n});", "Meteor.publish(\"adminUserDetails\", function (userId) {\n if (!authorizedAsAdmin(undefined, this.userId)) return [];", " // Reactive publish of any identities owned by the account with id userId,\n // as well as that user object itself.\n const identitySubs = {};\n const accountId = userId;", " const unrefIdentity = (identityId) => {\n if (!identitySubs[identityId]) {\n // should never happen, but if somehow you attempt to unref an identity that we don't have a\n // subscription to, then don't crash\n console.error(\"attempted to unref untracked identity id:\", identityId);\n return;\n }", " const observeHandle = identitySubs[identityId];\n delete identitySubs[identityId];\n observeHandle.stop();\n this.removed(\"users\", identityId);\n };", " const refIdentity = (identityId) => {\n if (identitySubs[identityId]) {\n // should never happen, but if somehow an account wound up with a duplicate identity ID,\n // avoid leaking a subscription\n console.error(\"duplicate identity id:\", identityId);\n return;\n }", " const cursor = Meteor.users.find({ _id: identityId });\n const observeHandle = cursor.observe({\n added: (doc) => {\n this.added(\"users\", doc._id, doc);\n },", " changed: (newDoc, oldDoc) => {\n fillUndefinedForChangedDoc(newDoc, oldDoc);\n this.changed(\"users\", newDoc._id, newDoc);\n },", " removed: (oldDoc) => {\n this.removed(\"users\", oldDoc._id);\n },\n });", " identitySubs[identityId] = observeHandle;\n };", " const accountCursor = Meteor.users.find({ _id: accountId });\n const accountSubHandle = accountCursor.observe({\n added: (newDoc) => {\n const newIdentities = SandstormDb.getUserIdentityIds(newDoc);\n newIdentities.forEach((identityId) => {\n refIdentity(identityId);\n });", " this.added(\"users\", newDoc._id, newDoc);\n },", " changed: (newDoc, oldDoc) => {\n const newIdentities = SandstormDb.getUserIdentityIds(newDoc);\n const oldIdentities = SandstormDb.getUserIdentityIds(oldDoc);", " // Those in newDoc - oldDoc, ref.\n const identitiesAdded = _.difference(newIdentities, oldIdentities);\n identitiesAdded.forEach((identityId) => {\n refIdentity(identityId);\n });", " // Those in oldDoc - newDoc, unref.\n const identitiesRemoved = _.difference(oldIdentities, newIdentities);\n identitiesRemoved.forEach((identityId) => {\n unrefIdentity(identityId);\n });", " fillUndefinedForChangedDoc(newDoc, oldDoc);", " this.changed(\"users\", newDoc._id, newDoc);\n },", " removed: (oldDoc) => {\n this.removed(\"users\", oldDoc._id);\n const oldIdentities = SandstormDb.getUserIdentityIds(oldDoc);\n oldIdentities.forEach((identityId) => {\n unrefIdentity(identityId);\n });\n },\n });", " this.onStop(() => {\n accountSubHandle.stop();\n // Also stop all the identity subscriptions.\n const subs = _.values(identitySubs);\n subs.forEach((sub) => {\n sub.stop();\n });\n });", " // Meteor's cursor.observe() will synchronously call all of the added() callbacks from the initial\n // query, so by the time we get here we can report readiness.\n this.ready();\n});", "Meteor.publish(\"activityStats\", function (token) {\n if (!authorizedAsAdmin(token, this.userId)) return [];\n return ActivityStats.find();\n});", "Meteor.publish(\"statsTokens\", function (token) {\n if (!authorizedAsAdmin(token, this.userId)) return [];\n return StatsTokens.find();\n});", "Meteor.publish(\"allPackages\", function (token) {\n if (!authorizedAsAdmin(token, this.userId)) return [];\n return Packages.find({ manifest: { $exists: true } },\n { fields: { appId: 1, \"manifest.appVersion\": 1,\n \"manifest.actions\": 1, \"manifest.appTitle\": 1, progress: 1, status: 1, }, });\n});", "Meteor.publish(\"realTimeStats\", function (token) {\n if (!authorizedAsAdmin(token, this.userId)) return [];", " // Last five minutes.\n this.added(\"realTimeStats\", \"now\", computeStats(new Date(Date.now() - 5 * 60 * 1000)));", " // Since last sample.\n const lastSample = ActivityStats.findOne({}, { sort: { timestamp: -1 } });\n const lastSampleTime = lastSample ? lastSample.timestamp : new Date(0);\n this.added(\"realTimeStats\", \"today\", computeStats(lastSampleTime));", " // TODO(someday): Update every few minutes?", " this.ready();\n});", "Meteor.publish(\"adminLog\", function (token) {\n if (!authorizedAsAdmin(token, this.userId)) return [];", " const logfile = SANDSTORM_LOGDIR + \"/sandstorm.log\";", " const fd = Fs.openSync(logfile, \"r\");\n const startSize = Fs.fstatSync(fd).size;", " // Difference between the current file offset and the subscription offset. Can be non-zero when\n // logs have rotated.\n let extraOffset = 0;", " if (startSize < 8192) {\n // Log size is less than window size. Check for rotated log and grab its tail.\n const logfile1 = SANDSTORM_LOGDIR + \"/sandstorm.log.1\";\n if (Fs.existsSync(logfile1)) {\n const fd1 = Fs.openSync(logfile1, \"r\");\n const startSize1 = Fs.fstatSync(fd1).size;\n const amountFromLog1 = Math.min(startSize1, 8192 - startSize);\n const offset1 = startSize1 - amountFromLog1;\n const buf = new Buffer(amountFromLog1);\n const n = Fs.readSync(fd1, buf, 0, buf.length, offset);\n if (n > 0) {\n this.added(\"adminLog\", 0, { text: buf.toString(\"utf8\", 0, n) });\n extraOffset += n;\n }\n }\n }", " // Start tailing at EOF - 8k.\n let offset = Math.max(0, startSize - 8192);", " const _this = this;\n function doTail() {\n if (Fs.fstatSync(fd).size < offset) {\n extraOffset += offset;\n offset = 0;\n }", " for (;;) {\n const buf = new Buffer(Math.max(1024, startSize - offset));\n const n = Fs.readSync(fd, buf, 0, buf.length, offset);\n if (n <= 0) break;\n _this.added(\"adminLog\", offset + extraOffset, { text: buf.toString(\"utf8\", 0, n) });\n offset += n;\n }\n }", " // Watch the file for changes.\n const watcher = Fs.watch(logfile, { persistent: false }, Meteor.bindEnvironment(doTail));", " // When the subscription stops, stop watching the file.\n this.onStop(function () {\n watcher.close();\n Fs.closeSync(fd);\n });", " // Read initial 8k tail data immediately.\n doTail();", " // Notify ready.\n this.ready();\n});", "Meteor.publish(\"adminApiTokens\", function (token) {\n if (!authorizedAsAdmin(token, this.userId)) return [];\n return ApiTokens.find({\n $or: [\n { \"frontendRef.ipNetwork\": { $exists: true } },\n { \"frontendRef.ipInterface\": { $exists: true } },\n ],\n }, {\n fields: {\n frontendRef: 1,\n created: 1,\n requirements: 1,\n revoked: 1,\n owner: 1,\n },\n });\n});", "Meteor.publish(\"hasAdmin\", function (token) {\n // Like hasUsers, but for admins, and with token auth required.\n if (!authorizedAsAdmin(token, this.userId)) return [];", " // Query if there are any admin users.\n const cursor = Meteor.users.find({ isAdmin: true });\n if (cursor.count() > 0) {\n this.added(\"hasAdmin\", \"hasAdmin\", { hasAdmin: true });\n } else {\n let handle = cursor.observeChanges({\n added: (id) => {\n this.added(\"hasAdmin\", \"hasAdmin\", { hasAdmin: true });\n handle.stop();\n handle = null;\n },\n });\n this.onStop(function () {\n if (handle) handle.stop();\n });\n }", " this.ready();\n});", "Meteor.publish(\"appIndexAdmin\", function (token) {\n if (!authorizedAsAdmin(token, this.userId)) return [];\n return globalDb.collections.appIndex.find();\n});", "function observeOauthService(name) {\n Settings.find({ _id: name, value: true }).observe({\n added: function () {\n // Tell the oauth library it should accept login attempts from this service.\n Accounts.oauth.registerService(name);\n },", " removed: function () {\n // Tell the oauth library it should deny login attempts from this service.\n Accounts.oauth.unregisterService(name);\n },\n });\n}", "observeOauthService(\"github\");\nobserveOauthService(\"google\");" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [84, 1522, 203, 231], "buggy_code_start_loc": [77, 1518, 202, 188], "filenames": ["shell/imports/server/email.js", "shell/packages/sandstorm-db/db.js", "shell/server/accounts/email-token/token-server.js", "shell/server/admin-server.js"], "fixing_code_end_loc": [121, 1524, 203, 232], "fixing_code_start_loc": [78, 1519, 202, 188], "message": "A remote attacker could bypass the Sandstorm organization restriction before build 0.203 via a comma in an email-address field.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sandstorm:sandstorm:*:*:*:*:*:*:*:*", "matchCriteriaId": "683ED5F0-D297-4A47-ADF9-186832F3A3AD", "versionEndExcluding": "0.203", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A remote attacker could bypass the Sandstorm organization restriction before build 0.203 via a comma in an email-address field."}, {"lang": "es", "value": "Un atacante remoto podr\u00eda omitir la restricci\u00f3n de organizaci\u00f3n de Sandstorm antes de la build 0.203 mediante una coma en un campo email-address."}], "evaluatorComment": null, "id": "CVE-2017-6199", "lastModified": "2018-03-13T19:27:30.200", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-02-06T16:29:00.730", "references": [{"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://devco.re/blog/2018/01/26/Sandstorm-Security-Review-CVE-2017-6200-en/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://github.com/sandstorm-io/sandstorm/blob/v0.202/shell/packages/sandstorm-db/db.js#L1112"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/sandstorm-io/sandstorm/commit/37bd9a7f4eb776cdc2d3615f0bfea1254b66f59d"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://sandstorm.io/news/2017-03-02-security-review"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-287"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/sandstorm-io/sandstorm/commit/37bd9a7f4eb776cdc2d3615f0bfea1254b66f59d"}, "type": "CWE-287"}
324
Determine whether the {function_name} code is vulnerable or not.
[ "This file shows the changes in recent releases of MODX. The most current release is usually the\ndevelopment release, and is only shown to give an idea of what's currently in the pipeline.\n", "", "- Fix caching of manager menus", "MODX Revolution 2.2.10-pl (October 7, 2013)\n====================================\n- Increase modTransportPackage version columns range to smallint\n- [#10211] Fix parser state bug triggered by media sources\n- Fix loading modResource derivatives in class_key dropdown\n- [#9973] Prevent extended user classes being set to modUser\n- Upgrade xPDO to 2.2.9-pl\n- [#10182] Improve sanitization of processor_err_nf response", "MODX Revolution 2.2.9-pl (August 28, 2013)\n====================================\n- Avoid critical error when resource tree not initialized\n- Avoid suppressed warnings with ob_get_level()\n- Upgrade xPDO to 2.2.8-pl\n- [#10043] Fix class-loading LFI in registerLogging\n- [#6937] Fix Persistent/Reflected XSS in User Messaging\n- Set default error_handler_types to error_reporting()\n- Upgrade to ExtJS 3.4.1.1 and add ExtJS debug support\n- [#9976] Fix cross-context symlink caching\n- [#10093] Add create/update methods to S3 Media Sources\n- [#9902] Added error window when package download fails\n- [#10070] fix potential SQL injection vulnerability in modImport\n- [#9843] Added lang_topics field to create and update action window\n- [#10094] Defaults overwriting properties in ResourceCreateProcessor\n- [#10007] Fix parser logic when processing elements via API\n- [#10087] Avoid stat warnings with missing static sources\n- [#9809] Remove empty ULs in topmenu\n- [#7569] Add bottom border to collapsed panels\n- [#146] Also fire field change event on change event\n- Fix contextsAffected in resource/sort processor\n- [#9815] Improved manager redraw on browser resize\n- Fix clearcache timing issue with MODx.Console\n- Prevent accumulation of MODx.Console onMessage callbacks\n- Prevent session write errors from phpthumb cache\n- [#9964] Fix Import HTML to use context of parent\n- [#9916] Add TABLE to TRUNCATE command in flushSessions (SQLSRV)\n- [#9527] Fix password reset by user email\n- Fix login processor to use absolute url redirects for mgr\n- [#9826] Fix errant creation of Policy Templates", "MODX Revolution 2.2.8-pl (June 4, 2013)\n====================================\n- Prevent empty HTTP_MODAUTH from succeeding\n- [#9450] Prevent non-existent Context initialization\n- [#9896] Improve performance of modTemplateVar::getRenderDirectories()\n- [#9859] Prevent conditional output filter recursion\n- [#6138] Handle offline errors in RSS feeds\n- Refresh file tree after removing file\n- [#9946] Do not cache modResource::$_isForward\n- Force browser to root on Media Source change\n- Refresh file tree after root upload\n- Fix remove file from root if no folder selected\n- [#8877] Fix inline grid datefield icon\n- [#6945] Fix datefield icon in grid toolbars\n- [#9825] Revert width increase of file and image TVs\n- [#9901] Fix empty resourceMap in sqlsrv\n- [#9912] Fix length of modResource.uri index\n- [#9846] Fix incorrect parameter order passed to findResource\n- [#9814] Fix empty cross-context links using link tags", "MODX Revolution 2.2.7-pl (April 9, 2013)\n====================================\n- [#9634] Fix notices in system/settings/update processor\n- [#9768] Fix array merge in xPDOObject::getMany()\n- [#9773] Fix classKey errors viewing manager actions\n- [#9774] Prevent resource/unpublish on site_start\n- [#8312] Allow sorting users by blocked status\n- [#1] Allow Element duplication when editing\n- [#9237] Return object from ContextSetting create/update\n- [#8327] Don't close context menu on click\n- [#8980] Fix lexicon when updating user password\n- [#9258] List languages and topics alphabetically\n- [#9152] Use default_context for New Resource toolbar actions\n- [#8138] Fix Combo Settings not saving from update dialog\n- [#9571] Fix template/update always refreshing cache\n- [#9093] Make collapsed tree panel tab more visible\n- [#8859] Add button to refresh error log\n- [#9772] Fix deprecated value for CURLOPT_SSL_VERIFYHOST\n- [#9728] Fix empty create Dashboard Widget tab\n- [#9734] Fix save button state on Content Types grid\n- Fix resizing of error log textarea\n- [#9287] Enable save button when switching templates\n- [#9132] Refresh cache when enabling/disabling plugin\n- [#9690] Fix various issues with server_offset_time\n- [#9738] Prevent working context overriding user settings\n- Fix error getting MediaSource table classes on cached Resources\n- [#9368][#9437] Fix modProcessorResponse->isError()\n- [#9681] Allow country/getlist processor to work more than once\n- Fix Auto-Tag TV value sorting\n- Make caching the aliasMap optional to reduce memory usage\n- [#9672] Fix invalid ini_get call in modDbRegister\n- [#8489] Add compound index to modTemplateVarResource\n- [#9592] Iterate all inherited parent FC rules\n- Replace location redirects with MODx.loadPage proxy\n- Add MODx.beforeLoadPage event to modExt components\n- [#9143] Fix destructors in modExt components\n- Allow loading of modExt files asynchronously\n- [#9359] Report errors about unpublishing site_start to user\n- [#9197] Load RTE for SymLinks in manager\n- [#9364] Allow Unicode chars via modX::sanitizeString()\n- [#9631] Fix image preview with special chars in filename\n- [#9608] Remove connections data from MODx.config\n- Fix invalid ini boolean evaluation in config_check processor\n- Allow modX::getParser() to get an extended modParser instance\n- [#9524] Fix invalid context assignment in modX::switchContext()\n- [#9517] modPackageGetAttributeProcessor returning wrong PACKAGE_ACTION\n- [#9451] Add modx-combo-source as settings type\n- [#5515] MODx.Browser UX improvements\n- Increase width of file and image TVs\n- [#9282] Fix Minify errors when manager on different subdomain\n- Various Manager UI Fixes\n- [#6150] Fix issues with auto_publish when encountering invalid data\n- [#8936] Fix modTemplateVarRender::_loadLexiconTopics()\n- [#9257] Fix workspace/lexicon/getlist strict notice in PHP 5.4+\n- [#9339] Use Resource context_key in update processor when not specified\n- [#9212] Fix SQL syntax error in modTemplateVar->findPolicy()\n- [#9239] Make sure class_key is passed when switching templates\n- [#8101] Add support for httpOnly session cookies in PHP 5.2+\n- [#8420] Provide multi-node support to flock-independent file locking\n- [#8420] Remove LOCK_EX from flock-independent file locking method", "MODX Revolution 2.2.6-pl (December 3, 2012)\n====================================\n- [#9178] Use PHP time for valid check in modDbRegisterMessage::getValidMessages()\n- [#9165] Fix modError::hasError false positives when loaded via getService\n- [#9029] Remove modRequest->loadErrorHandler dependency in runProcessor\n- [#9156] Fix reload data for rendering multi-value TV types properly\n- [#7916] Fix Area functionality in Element Properties and Property Sets\n- [#9097] Fix leftbar tree toolbar resizing issues\n- Image optimization applied across distribution\n- [#9006] Fix ImageMagick which convert issue (PHP 5.3.2+)\n- [#9069] Remove math output filter\n- [#9080] Fix modX::stripTags() bug allowing script execution vulnerability\n- [#9007] Prevent MODx.Browser closing window when manager loaded in a new tab\n- [#8928] Error saving Resource with access-restricted TemplateVars\n- [#8978] Fix issue where change template was not fired due to onsave check overriding listener\n- [#9026] Prevent new Content Types from having binary checked", "MODX Revolution 2.2.5-pl (October 2, 2012)\n====================================\n- [#8753] Fix variable name in security/user/removemultiple processor\n- [#7654] Fix Update processor for ResourceGroup-restricted TVs\n- [#8196] Enable save button when combo selections are made\n- [#8186] Apply FC rules to Resources when changing Template\n- [#8790] Add ability to hide changed password in Update Profile\n- [#7551] Ensure static element path is not existing directory\n- [#7631] Fix duplicate beforeSave() in modObjectCreateProcessor::process()\n- [#8754] Change elementType to objectType in various processors\n- [#4430] Return 404 error if static resource target is invalid\n- [#8767] Fix MODx.panel.Resource to inherit config.url\n- [#8545] Add ability to localize ExtJS pre-loading message\n- [#8089] Fix ability to disable drag/drop in Resource tree\n- [#7661] Prevent changing template from unsetting Empty Cache\n- [#8620] Enable type-ahead on User and Country combos\n- [#8529] Prevent empty multi-value TVs from saving as '||'\n- [#8018] Fix file creation/editing on non-default Media Source\n- [#8556] Ensure regClient functions inject only once\n- CSS Style fixes for IE 9 (8, 7)\n- [#8560] Fix Context Admin ACL automation and use Context Policy\n- [#8432] Package Browser tree not reloading on Provider change\n- [#8482] RTE Output Option for TVs does not render on frontend\n- Add Quick Create/Update File feature in Files tab\n- [#6522] Retain page in Package Manager after install/upgrade\n- [#7630] Save modUserGroupMember rank upon creation\n- [#8420] Provide flock-independent file locking to avoid cache corruption\n- [#7498] Fix Media Source error reporting for file uploads\n- [#8299] Clear action_map (and menus) in system/action create/update processors\n- [#8168] Fix JS error when compress_js=Off and compress_js_groups=On\n- [#8341] Allow Resource data pages to be extended by CRCs\n- [#6695] Close sessions before min scripts terminate\n- [#6918] Fix importing access policy items always being checked\n- [#8329] Fix syncsite checkbox being unchecked by default on resource/create\n- [#8296] Fix function passed by reference in ellipsis output filter\n- Allow numeric value in modWebLink to redirect to Resource by id\n- [#7763] Fix additional Media Source path issues with static elements\n- [#8208] Fix modDbRegister->read() with include_keys option\n- Fix PropertySet switching from Element create/update controllers\n- [#7392] Get correct modMediaSource derivative in modParser->getElement()", "MODX Revolution 2.2.4-pl (June 14, 2012)\n====================================\n- [#8105], [#8051] Fix modFileHandler::sanitizePath() infinite recursion", "MODX Revolution 2.2.3-pl (June 13, 2012)\n====================================\n- Add setting to be able to set default context for new Resources\n- Pass http_host in provider requests\n- [#7933] Add friendly_urls_strict to optionally enable non-canonical redirects\n- [#6428] Fix help tooltip for new namespace window\n- [#8054] Fix transport provider verify processor consistency\n- [#8051] Added extra sanitization for modFileHandler.sanitizePath\n- [#7925] Fix error editing Resources in multi-context sites\n- [#8052] Fix empty()/isset() on hydrated fields/related objects\n- [#7798] Avoid E_NOTICE in PHP 5.4 from array_diff_assoc in xPDO::loadClass()\n- [#7796] Fix issue with phpthumb calling non-static methods statically\n- [#7764] Compress and default to open Resource Group access wizard in window\n- [#7762] Fix issue with add/decr output filter not adding 0 if 0 is passed\n- [#7793] Fix issue with saving a new media source access on user group edit screen\n- [#7712] Fix Resource quick update showing 2 checkboxes", "MODX Revolution 2.2.2-pl (May 2, 2012)\n====================================\n- Preserve GET parameters for container_suffix redirects\n- Allow custom FURLs via URL rewriting again\n- [#7427] Fix request_method_strict with FURLs off\n- Add ability to extend manager session by relogging in without leaving manager screen\n- Add better handling for AJAX exceptions, displaying AJAX errors\n- [#7649] Prevent E_NOTICE when using ago filter within <1sec difference\n- [#7568] Add JSON to default content types\n- [#7549] Open new window for phpinfo in system info page\n- [#7531] Add manager setting for first day of week in datepicker\n- Flip page title on manager pages for easier readability in browser tabs\n- [#7543] Add extra sanity checks for ellipsis output filter\n- CLI upgrades not loading MODX config data\n- [#7652] Sessionless contexts allowing anonymous access to unpublished resources\n- [#7610] User.sudo field invalid for sqlsrv\n- [#7619] Fix issue with TV FC rules and template constraints\n- [#7613] Add ability to duplicate user\n- [#7590] Fix lazy loading errors in xPDO layer\n- [#7608] Prevent ttl=0 set on modDbRegister from expiring immediately\n- Add wizard for User Group creation to speed up ACL workflow\n- Add Context policy for proper managing of access to non-mgr Contexts\n- Add wizard for Resource Group creation to speed up ACL workflow", "MODX Revolution 2.2.1-pl (April 3, 2012)\n====================================\n- Override modAccess->getOne for Principal aggregate\n- Add GroupPrincpal/UserPrincipal aggregates to modAccess\n- [#7387] Add New Category button to Element tree toolbar\n- [#7518] Fix issue that prevented absolute URLs in media-source bound TVs\n- [#7521] Allow filtering of usergroup by request on users page\n- Add assets_path field to modNamespace\n- [#7447] Change default root node name of Files tab to \"Media\" to prevent confusion when a non-default source is selected\n- Drop no-longer used, deprecated modAction.parent field\n- [#7503] Change Duplicate Values text to Duplicate Resource Values to clear up intended behavior\n- [#7499] Fix DOM ID issues with Quick Update when multiple windows are loaded\n- [#7500] Make consistent positioning of published checkbox in quick update and normal edit page\n- [#7491] Prevent Media Source dropdown from showing in MODx.Browser when loaded from a TV\n- [#6894] Move Import button on Access Policy and Access Policy Template grids to top toolbar\n- [#7391] Fix UI error causing resource group checkboxes on TV edit page to not render correctly\n- [#7481] Fix issue with reloading resource when changing templates and the context alias cache\n- Add \"sudo\" user attribute, which bypasses access permissions for said user; upgrade to 2.2.1 makes Super Users in Administrator group sudo users\n- [#7445] Fix issues with TVs not respecting Resource Groups limiting access\n- [#7446] Added extra checks to protect against parse errors with :then and :else output filters\n- [#7455] Fallback to TV name if caption not found when displaying TV inputs\n- [#7456] Fix for minify not modified status in fastcgi environments\n- [#6931] Workaround for template changing issue on servers that have misconfigured date_timzeone setting\n- [#6687] Fix duplicated OK buttons in MODx.Console in certain situations\n- [#6501] Fix SuperBoxSelect selections spanning multiple rows\n- [#6496] Fix quick edit modal windows for elements on smaller screens.\n- [#6864] Fix rare issue where primary group is not set for user, and custom dashboard for their group does not propagate\n- [#7011] Prevent infinite recursion error in modElement::isStaticSourceMutable\n- [#7333] Prevent error when id is undefined in resource edit controller\n- [#7364] Add setting to set default sort field of MODx.Browser view\n- [#7363] Check for this.stateful in MODx.tree.Tree::_saveState\n- Add missing index to modSession.access\n- [#7357] Prevent viewing of Profile if user does not have change_profile permission\n- [#7322] Fix issue where certain regions were not able to be hid via FC; clarified FC set labels\n- [#7362] Fix issue with conflicting FC Sets when User belongs to more than one User Group with a Set\n- Update to xPDO 2.2.3-pl\n- Prevent fatal error if invalid class_key is passed to Resource edit/create page\n- [#7052] Prevent username/host/dbname from being set as a system setting placeholder\n- [#3860] Fix session issue with modUser joinGroup/leaveGroup methods\n- [#7315] Standardize default sorting for User Group access grids\n- Fixed ellipsis filter to not cut off html tags in property\n- [#7326] Fix inability to unset a TV's Input Option Values field\n- [#7306] Sanity check for reload data for resource groups when changing template of new resource\n- [#7279] Handle edge case where processor classes might already be loaded with CRCs causing issues with runProcessor\n- Add dashboard name to dashboard title\n- [#3818] Add UI/processing to set response code for weblinks\n- [#7061] Prevent Static Element access to the core/config/ directory\n- [#7088] Tweak column widths for settings grids\n- [#7102] Improve memory_limit checks to properly check for values that are not formatted to PHP standards\n- [#7191] Fix invalid api doc link in link_tag_scheme description\n- [#7194] Fix issue where save button did not enable when reordering groups on user edit screen\n- [#3818] Change modWebLink default responseCode to 301\n- [#6611] Fix issue where MODx.Browser did not sort files by name by default\n- [#7070] Do not overwrite user changes in default media sources during upgrade process\n- [#7066] Allow search locally in Package Management if cURL is not installed\n- [#7063] Fix issue with retreiving Element Media Source cache data\n- [#7036] Fix issue with multiple grid store loading when searching\n- Allow for non-PHP Dashboard File Widgets that are just HTML files\n- [#6711] Fix issue with using MODx.Browser with file nodes and clicking loading edit page\n- [#6936] Add sanity check for database tables getlist processor if user did not grant SHOW TABLES permissions for sql\n- [#6942] Add missing resource duplicate ACL permission description lexicon string\n- [#6970] Reload error log page after clearing too large error log file\n- [#6956] Fix wrong groupname for OnMediaSourceDuplicate plugin event\n- [#7013] Fix issue where modUser->getUserGroupNames was buggy with non-self users\n- [#6960] Fix rendering issue when tree_root_id is set\n- [#7031] Ensure setting from addr in modMail sets return-path as well\n- [#7010] Add in rootId config option for MODx.Browser mgr widget\n- [#6874] Fix issue where duplicating a TV did not copy Media Source relationships correctly\n- [#6582] Fix clear cache checkbox persistence in Resource page when reloading via Template change\n- Add modX::getInstance() factory method\n- Allow for MODX tags within Media Source properties\n- [#5410] Add lock_ttl to System Settings for controlling ttl for resource locks\n- [#6575] Ensure that downloads of packages work behind proxies if allow_url_fopen is on\n- [#4879] Add language selector to login page\n- [#6826] Add activate/deactivate to context menu for Plugins in tree\n- [#6509] Fix minify issue in windows environments due to doc root pathing\n- Fix CSS for active tabs in mgr in IE\n- Prevent ENTER key from firing save in textareas in various modals\n- [#6712] Fix issue with Resource Group tree being limited to 10 groups\n- Bypass modSystemSetting->clearCache() when OPT_SETUP is true\n- Allow display of custom messages from form processors\n- Fix issue with extra slashes in URIs\n- Add ability to reload permissions for all authenticated users\n- [#6651] Add properties field and API methods for modResource\n- [#6613] Ensure page redirects if removing Element via tree that is currently being edited\n- [#6608] Fix search text in package management when doing empty search\n- [#6633] Ensure change password fieldset checkbox toggles dirty status for user form\n- [#6567] Fix Suhosin check to disable compress_js setting\n- [#6587] Fix issue with combobox rendering in editable grids by providing combocolumn xtype for proper data rendering\n- [#6583] Fix duplicate upload_files values\n- Prevent editing and deleting of core standard Roles", "MODX Revolution 2.2.0-pl2 (January 4, 2012)\n====================================\n- [#6564] Fix issue where save button on New Resource does not work due to JS DOM error\n- [#6470] Fix issue where Media Sources could not be protected on new installs only", "MODX Revolution 2.2.0-pl (January 4, 2012)\n====================================\n- [#6559] Fix issue with save btn on resources not enabling after template change\n- Better handling of dynamic lexicon topic adding and deprecated manager controllers\n- [#5905] Refactor new package versions to run ACTION_UPGRADE\n- [#6120] Improve static element behavior with immutable sources\n- [#6551] Fix issue where ID instead of name of Template showed on resource combo\n- [#6509] Fix minify issue when DOCUMENT_ROOT is a symlink\n- [#6546] Reposition setting grid filter dropdowns to clarify behavior\n- [#4146] Fix issue where Content Types were always binary when created\n- [#6470] Fix issue where Media Sources could not be protected due to missing reference in principal_targets setting\n- [#6520] Fix issue with Quick Create Resource and default settings\n- [#6510] Fix minify issue with virtual dirs inside the document root\n- [#5229] Fix issue where changing parent did not reload Resource edit page\n- [#6513] Better handling for large error.log files in mgr\n- [#6519] Ensure JS config gets working context config\n- [#6507] Add missing Media Source plugin events\n- [#6505] Remove htmlentities on date output filter\n- Allow PDO driver options to be defined in MODX config\n- [#6383] Add index.php to minify paths in mgr templates", "MODX Revolution 2.2.0-rc-3 (December 22, 2011)\n====================================\n- [#6247] Fix additional minify issues with CMP controllers in MODX_ASSETS_PATH\n- [#6428] Fix improperly designated tooltip and UI for create namespace window\n- Fix various regression issues with rename/delete files/directories in the Files tree\n- Ensure hideFiles property works for the files tree\n- [#6383] Add index.php to minify paths\n- Prevent TVs tab from showing in Resources if the only TVs are of type \"hidden\"\n- [#6413] Fix missing date_timezone setting description\n- [#6297] Prevent invalid characters in property set names\n- [#5997] Fix issue where components dirs were being created in assets with non-standard assets directory paths\n- Fix issue where resource ID was not being passed to FC rule checks\n- [#6417] Fix issue with modResource class_key being incorrectly set\n- Adjust modResponse contentType loading to allow overriding in custom resource classes\n- Fix critical timezone issue introduced for [#6077]", "MODX Revolution 2.2.0-rc-2 (December 16, 2011)\n====================================\n- [#3033] Add method to reload Context data in same request\n- [#6372] Add explicit resource_duplicate permission for duplicating a resource\n- [#6364] Fix incorrect lexicon reference in package versions grid\n- [#6365] Add manager_login_url_alternate setting which allows for setting a custom manager login URL\n- [#6077] Override PHP default timezone via System/Context Settings\n- [#5709] Fix issue where drag/drop in left trees did not work when package management was open\n- [#6153] Prevent enter key from sending Message when typing in messages page\n- [#6349] Properties can now belong to areas, and are grouped in grid by area\n- [#6344] Fix various pathing issues when drag/dropping files into content\n- [#5941] Add anonymous Load Only ACL when creating contexts\n- [#6247] Fix minify issues outside of $_SERVER['DOCUMENT_ROOT']\n- Improve skipFiles attribute for file media sources to allow MODX tags and hiding directories\n- [#6336] Fix error when updating property via window in media source properties grid\n- Fix various issues with permissions and ACLs on Media Sources\n- [#6306] Fix issue with close button always prompting changes made when changes may not have been made\n- [#6317] Fix issue with combo editor rendering in grids\n- [#6307] Save button now properly resets to disabled after save\n- [#6313] Fix issue with renaming content field label on derivative resource types\n- [#6084] Fix upgrade from 2.0.x releases\n- Add OnManagerPageBeforeRender and OnManagerPageAfterRender events\n- [#6207] Prevent overwriting static element file content when changing a static source\n- [#6255] Escape html tags in readme, license and changelog files for downloaded Packages\n- [#6096] Fix more issues with Resource reloading after changing a template by making the Resource Access grid local\n- [#5418] Add ability to export/import Access Policies\n- Add ability to import/export Policy Templates, as well as a base export/import processor class\n- [#6242] Actions on regular Resources break with Custom Resource Class extended fields\n- [#6096] Fix issue where reload token in Resource create would not allow save after validation\n- [#6238] Fix rendering issue when opening multiple quick create resource windows at once\n- Fix various issues with TV input and output renders by properly objectifying them into base abstract classes\n- [#5763] Allow for 3rd-level deep category nesting\n- [#6215] Fix issues with derivative resources and non-standard manager themes\n- [#6237] Add ability to sort users by active status in mgr grid\n- [#6197] Refresh old and new context caches when moving Resource\n- Update to xPDO 2.2.1-pl\n- [#6080] Fix revert to default properties on Source Properties grid\n- [#6204] Fix issue where multiple languages could not be loaded per page in the lexicon\n- [#6196] Ensure that MODx.Browser view updates when changing a media source from dropdown in tree\n- [#6198] Fix issue with saving user groups on a new user that caused duplicate role saving\n- [#6159] Implement OnBeforeUserActivate, OnUserActivate, OnBeforeUserDeactivate, and OnUserDeactivate events\n- [#6063] Add extra settings and checks to allow for better handling of manager CSS/JS minification on servers that do not allow DOCUMENT_ROOT access\n- [#6147] Fix element processors not firing proper events and passing wrong variables to plugins.\n- [#6060] Fix issue where resources were getting class_key of modResource rather than modDocument\n- [#6030] Fix issue where alt attribute was duplicated on image output renders\n- [#6122] Clarify text for removing a dashboard widget from a dashboard\n- [#6124] Fix issue where element associations of various elements were not saved in respective create processors\n- [#6145] Allow sorting of plugin events by enabled flag\n- [#6065] Fix issue with missing paths in certain environments for new installs in setup\n- Fix provider select window width in Chrome/Windows\n- [#6081] Fix issue in modFileMediaSource that prevented source properties from being read in certain processors\n- [#5141] Remove dependency for navbar.tpl in manager templates\n- [#5760] Fix memberof filter if user is not logged in\n- [#6090] Fix issue with removing Content Types in 2.2-rc1\n- [#6088] Fix issue with :date output filter and umlauts\n- [#6093] Make for easier translations of Element context menu items\n- [#6099] Fix incorrect index name for modWorkspace", "MODX Revolution 2.2.0-rc-1 (November 17, 2011)\n====================================\n- [#6019] Configure log_level, log_target, and debug via Settings\n- [#4798] Resource create/edit: Template can be switched without saving\n- Update to xPDO 2.2.0-pl\n- [#6039] Fix issue where Resources could be improperly dropped into the right tree in the Resource Groups screen\n- [#5715] Fix issue with resetting of header in Element panels\n- [#6025] Fix issue with renaming checkbox fields via Form Customization\n- [#5697] Fix issue with allow_multiple_emails in user creation\n- [#121] Add option for Elements to pre-process default property/property set values\n- [#6017],[#2774] Add more Permissions to Administrator policy for managing security functions\n- [#5064] Fix issue where access_permissions Permission was required for creating new users\n- Improve Package Management UI\n- Add modManagerController::addLexiconTopic for easier adding of lexicon topics dynamically within mgr controllers and dashboard widgets\n- [#6009] Add ability to hide left-hand trees when rendering a Dashboard\n- [#6007] Stop upgrade from overwriting session_cookie_path system setting\n- [#5998] Add \"Create File\" option for stream-based media sources\n- [#4794] Add custom Permissions for restricting creation of core derivative Resource Types\n- [#4958] Add Resource ID to node of Resource in Resource Groups tree\n- [#5434] Change manager page title to use site_name as prefix instead of MODX\n- [#4875] Add ability to download file from Files tree\n- [#5997] Fix issue where in advanced installs with moved web path, assets directory is improperly created\n- [#5990] Fix issue where content types were not listable in Resource dropdowns\n- [#232] Enable option to render target URL for WebLinks\n- [#5963] Fix issue with Static Elements and their Source being None\n- [#5936] Fix issue where Quick Update Resource was too high on smaller screens\n- Fix issue with phpThumb and zoom crop\n- [#5983] Fix adding/updating a provider window duplicating \"username\" field.[#5948] Ensure that menu item for Change Profile is added on build\n- [#5985] Fix updating a provider not showing username\n- [#5978] [ReUp] [#5978] Fix missing fields/tabs in actions XML causing issues with form customization on resource/create\n- [#5938] Optimize modResource->getTVValue() using parser source cache when available\n- [#5973] Prevent empty user groups being loaded for anonymous users\n- [#5962] Fix phptype in modContextResource.resource field definition\n- [#5050], [#5366], [#5781] Various xPDO Database Caching Fixes (xPDO 2.2.0-rc2)\n- [#4830] Prevent removal of Content Types that are in use\n- [#5293] Prevent drag/drop from Resource Group tree to Resource tree in Resource Group page\n- [#4433] Validate paths in setup for trailing slash\n- [#564], [#4506] Make Workspace path portable by allowing path setting replacements\n- [#5086] Fix issues with Package Management when open_basedir is in effect\n- [#4947] Adjust ensuring of admin access to context to only needed policies\n- [#5078] Have default resource field context settings, such as default_template, respected in Quick create\n- [#5909] Allow blank extensions in Add Content Type window\n- [#5931] Fix code that prevents easy renaming of assets directory with package management\n- [#5841] Properly color active state for tabs in mgr ui\n- [#3287] Fix issue with dob User field in editing panel in mgr\n- [#5060], [#5043] Fix issue with openTo and TVs for MODx.Browser\n- [#3396] Allow MODX_API_MODE in mgr context\n- [#4230] Add ODF and OOXML to default uploadable file types setting\n- [#5315] Use automatic_alias behavior when updating site_start regardless of setting\n- [#3535] Fix issue with tree_default_sort not being respected on the resource tree\n- [#5892] Add for default_media_source setting for specifying the default media source for a site\n- [#5896] Make console window always closable\n- [#5757] Allow text in grids to be selectable\n- [#5471] Add publishing options to Duplicate Resource window\n- [#5879] Ensure html tags are stripped on titles in the Resource edit view\n- [#5855] Ensure if no parents are specified, resourcelist input option works as expected\n- [#5852] Fix issue where input options are wiped on quick update TV\n- Add showNone option to source/getlist processor\n- [#5619] Enable modElements to store content in external files\n- [#5856] Implement ability for derivative Resource types to have their own translatable name\n- [#4726] Implement server-side state provider for modExt to fix size problems with cookies\n- [#5860] Fix FC SQL error when user is in no groups\n- [#5843] Add required asterisk to required Element fields\n- [#5723] Add Media Source tab to User Group Access screen\n- Change \"Cancel\" references to \"Close\" for clarity\n- [#4566] Fix online users manager dashboard widget grid\n- [#5809] Change \"Remove\" to \"Delete\" where appropriate to clarify language\n- Refactor processors to be class-based\n- [#90] 301 Redirect id method requests when request_method_strict is not enabled\n- [#90], [#5676] Improvements to strict routing with friendly_urls\n- [#5323] Add system events for moving Resources in and out of Resource Groups\n- [#4610] Add locale system setting for setting locale in MODX\n- Add HTML5 local caching as a toggleable option for manager ui\n- [#5788] Fix content not output to browser until after shutdown function\n- [#5777] Fix validation of TV names against Resource field names\n- Add ability to install and upgrade MODX from command line\n- [#5745] Ensure all core passwords are not transmitted through MODx.config JS array\n- [#4304] Add default_content_type Setting for setting the default Content Type for Resources\n- [#2735] Ensure menu permissions are checked for mgr action if action has menu associated\n- [#4606] Clarify connectors language in setup\n- [#5561] Add search toolbar to packages grid\n- [#5587] Fix issue with dashboard widgets and caching\n- [#5453] Add ability to disable forgot password on manager login screen\n- Add batch remove to Namespaces grid\n- [#5671] Add :toPlaceholder, :cssToHead, :htmlToHead, :htmlToBottom, :jsToHead, :jsToBottom output filters\n- Add delete user button to user editing page toolbar\n- [#5542] Add ability to drag/drop files and folders in the Files tab\n- [#5665] Remove console.log debug references in JS\n- Add Media Sources, which allow abstraction of file management in MODX\n- [#2737] Centralize logic for changing Context of modResource Children\n- [#5068] Move token check for new resources below error validation in processor to prevent bogus duplicate resource issue\n- [#4945] Remove weblink content maxlength restriction\n- [#5270] Enable container drag 'n drop in Extended Fields tree\n- [#4790] Add support for comment tag token, e.g. [[- comments here]]\n- [#5539] Add back in compress_css/js for allowing toggling of js/css compression in manager\n- [#5556] Enable connection pooling with master/slave support\n- [#5499] Ensure modFile create returns boolean\n- [#5501] Add sanity checks on FC rules renameTab and hideField\n- [#5505] Fix issue with dropdowns in Fx5\n- Enable modTag elements to accept property sets\n- Enable modElement->getPropertySet() to merge @propertyset in name with property set specified in setName parameter\n- Allow modParser->getElement() method to accept @propertySet in name parameter\n- Prevent modParser->parsePropertyString() from trimming all backticks at beginning and end of string\n- Improve parser efficiency by returning results of nested tags if elementOutput is null|false\n- [#5392] Fix bug where policy template descriptions were not translated\n- [#5377] Fix modParser->isProcessingTag() bug preventing filtering on placeholder tags\n- Pass content by reference to OnParseDocument event\n- Add message_key and json message_format option to system/registry/register/send processor\n- Allow raw messages to be returned from system/registry/register/read processor\n- Add include_keys option to modRegister implementations\n- [#5336] Prefix non-core actions in the MODx.action JS object with their namespace\n- Avoid setting description to null in element/propertyset/create processor\n- Improve modX->logManagerAction to avoid attempts to insert NULL values\n- Accept null options in modHashing->__construct()\n- [#4607], [#3463] Add rank field for contexts to allow custom sorting in tree, fix issues with context/resource dragging and dropping and ensure context name validation rules are consistent\n- Improve UI of User's groups to allow for assigning ranks to User Groups for a User\n- Add Custom Dashboards and Dashboard Widgets\n- [#4871] Fix Access Permissions not being copied when duplicating a context\n- [#4382] Forgot Manager Password now lookups using username to prevent issues when the 'allow_multiple_emails' system setting is enabled\n- Fix rendering of combo boxes in element properties\n- Add ability to select Primary User Group for User\n- [#4637] Fix RTE checkbox not saving correctly when using Quick Create Resource\n- [#5268] Add search toolbar for Resource tree\n- [#4080] Add Content Type and Content Disposition to Quick Create/Update Resource\n- [#5250] Add check for cURL in Package Management\n- [#5204] Add search by parent to mgr search page\n- Added much better handling for custom resource classes; deprecated custom_resource_classes setting\n- [#4601] Ensure children of protected Resources inherit by default their parent's Resource Groups in create UI\n- [#4016] Update description text in grid when adding/updating element properties without need for page reload\n- [#2860] Fix 'Sent On' date when viewing an expanded message\n- [#4984] Ensure tree highlighting of currently edited resource/element/file works consistently\n- [#2638] When updating an element's category, ensure old treenode is removed\n- [#5139] Fix issues with MODx.Browser and file/image TVs in other contexts\n- [#4958] Add IDs to Resource Groups in RG tree\n- Add ability to rename Resource Groups\n- [#5185] Improve core package already extracted validation for upgrades\n- Update xPDO and regenerate schema to get new maps of derivative classes\n- [#5195] Change TV value fields from TEXT to MEDIUMTEXT (mysql)\n- [#5141] Add ability to override specific controllers/templates in a custom manager theme w/ fallback to default\n- Add modResource::getControllerPath method for better abstraction of derivative resource types\n- Add show_in_tree and hide_children_in_tree fields to modResource for better support with custom Resource types\n- Abstract all manager controllers to classes to improve usability, testing and creation of controllers", "MODX Revolution 2.1.3-pl (July 21, 2011)\n====================================\n- [#5295] Fix parents input option for Resource List TV when 0 is specified\n- [#5190] Fix includeParent input option in Resource List TV\n- [#5222] Fix nested cacheable tags being skipped in non-cacheable tags\n- Fix delegateView recursion in Resource controllers on Windows\n- [#3966] Fix double slash issue in file paths when dragging into resource content from the Files tree\n- [#4565] Fix issue with Resource tree sorting\n- [#5026] Make directory tree in MODx.Browser instance launched from Files tab consistent with other instances of MODx.Browser\n- [#4960] Prevent method declaration error for modPHPMailer::reset()\n- [#3716] Ensure consistent handling of combo-boolean property values in the database\n- [#4586] Improve number detection for Radio and Checkbox TV values\n- [#5196] Unset uri_override when duplicating creates a duplicate uri", "MODX Revolution 2.1.2-pl (July 6, 2011)\n====================================\n- Fix issue with modUser::getSettings pulling a deprecated alias\n- Update to xPDO v2.1.5-pl\n- Implement DocBlox for documentation generation\n- [#5168] Fix element and tv permission queries for SQL Server\n- [#5146] Fix issue with Firefox and button widths\n- [#5164] Fix possible issue if a TV is stranded to a non-existent category\n- Update ExtJS to 3.4.0\n- Set a default session_gc_maxlifetime to avoid frequent logout issues\n- Refresh modExt trees when drag operations fail\n- [#4918] Limit save permission check to modified nodes in resource/sort processor\n- [#5065] Fix 404 error with cross-context symlinks when cacheable\n- [#5152] Fix nested non-cacheable tags from being cached in modResource->_content\n- [#5145] Update config check on dashboard to show correct core path if core is moved\n- [#5112] Add Settings for adjusting behavior of Context sorting in Resources tree\n- [#4341] Properly clarify text and function on Resource Tree context menu options for view/preview\n- [#5046] Fix issue where parent could not be changed for new resources via Form Customization\n- [#5112] Sort contexts by name ascending in the Resources tree\n- [#5102] Fix error removing older transport package versions\n- [#4940] Fix issue where CMPs that did not use ExtJS could not scroll\n- [#5097] Ensure browser toolbar button does not show when MODx.Browser is already open\n- [#4953] Improve modx.console.js to avoid message loss\n- [#4836] Make sure modFileRegister sorts messages before reading\n- [#5087] Fix issue where class_key was not respected when using Add Another in UI\n- [#260] Implement on-the-fly compression for css/js in manager\n- [#3464] Set xPDOTransport::ACTION_UPGRADE for already installed packages\n- [#4955] Package management actions refresh packages cache partition\n- [#5071] (SqlSrv) fix/refactor Plugin Events getList processor\n- [#2870] Change internalKey default value to NULL\n- [#5072] Add missing primary key index to modEvent\n- [#5005] Fix incorrect label on introtext field in weblink panel\n- Remove session_cookie_lifetime variable when logging out of context\n- Remove legacy SESSION variables and dependencies\n- [#4703] Remove user settings when logging out of a Context\n- [#2566] Improve tv output render url to take resource pagetitle when using resourcelist TV type\n- [#5020] Improve per page field on grids to handle ENTER key\n- [#5021] Improve modUser::joinGroup to check to see if user is already in group\n- [#5025] Fix issue where duplicate resource window did not show duplicate children option\n- [#5007] Only create Lexicon Entries for Settings if they are specified\n- [#5006] Fix issue with updating a policy template with no permissions\n- [#5001] Fix issue with modauth, wctx and RTE browser", "MODX Revolution 2.1.1-pl (June 1, 2011)\n====================================\n- Make modauth calculation independent of session_id\n- Ensure login/logout processors do not add Contexts with empty keys\n- [#3145] Ensure mail_smtp_pass and proxy_password System Settings use password xtype\n- [#4360] Show current context name on MODx.Browser window for reference\n- [#4881] Fix issue where modx-combo-language was missing from system setting editing screen\n- [#4896] Fix issue where New Category window is not cleared on each load\n- [#4934] Fix missing lexicon load call in package download processor\n- [#4927] Gray out disabled plugins in elements tree, italicize locked elements\n- [#4921] Ensure Category names are not ever capitalized when displayed as tabs\n- [#4865] Fix PDO error caused by missing charset for new MySQL installs on PHP 5.3.6+\n- Improve modSessionHandler and add Settings for advanced configuration\n- [#4750] Fix various issues with duplicating Resources, such as new name not prefixed and incorrect menuindex\n- [#4910] Fix bug where ResourceList TV type could not be marked as required\n- [#4915] Fix UI glitch when creating both an Access Policy and its Template on same page load\n- [#4916] Fix issue where cache clear checkbox was always being cleared on template save\n- [#4884] Remove PHP4 constructor on modRegister\n- Harden connector CSRF security by tying user session modauth to prevent hijacking of session if modauth is known\n- [#4863] Fix issue where template changing causes unintended alias\n- [#4854] Fix bug that caused update/rename file to be missing in Files tree context menu\n- [#4851] Improve safe_mode check in setup to check for non-boolean values\n- [#4856] Fix issue with MODx.Panel instances that have no textfields, causing scrollbar issues\n- Fix issue where MODX version was not being sent to provider during package update\n- [#4850] Fix issue with MODx.Window instances that have no textfields", "MODX Revolution 2.1.0-pl (May 24, 2011)\n====================================\n- [#4818] Fix SqlSrv query errors related to TVs\n- Add modX->$sourceCache data to cached Resources\n- Fix loading of cached Resource content and processed flag\n- Fix caching of empty policies for Resources\n- Fix modSessionHandler->write() cache flag if cache_db_session is not enabled\n- Update xPDO to v2.1.4-pl for cache_db bug fixes and improvements\n- [#4832] Fix issue with moving resource parent to root\n- [#4827] Make sure editing a file sends the working context along\n- Fix erroneous call to OnDocUnpublished event that should be OnDocUnPublished\n- [#4796] fix New Resource page heading during typing of page title\n- Add Usergroup filter to users grid\n- [#4785] Fix preview of files in left tree in non-standard contexts with absolute filemanager_ settings\n- [#4473] Add other common file types to upload_files system setting\n- [#4539] Fix issue with stretching of quick update chunk and small screen resolutions\n- Automatically focus cursor to first textfield on windows in mgr\n- [#4738] Fix issue with inconsistent results in resourcelist TV\n- [#4441] Fix FC issue when parent is constraint and trying to change default template\n- [#4764] Fix issue with timestamp display on manager log page\n- [#4680] Fix javascript error when typing Template name\n- [#4681] Fix path issue which was causing 404 errors in the manager, IE 7-9\n- [#4439] Add parentheses to list of disallowed password characters in installer\n- [#4669] Fix button target size to make it more responsive to most clicks\n- [#4625] Fix sizes of buttons and submit inputs in installer - IE 8 and 9\n- [#4617] Fix custom values not being shown on Context Installation page during Advanced Upgrade\n- [#4605] modX->switchContext() now checks load permission via Context ACLs\n- [#4595] Fix display of modified/accessed times on Edit File page\n- [#4594] Fix last login time displayed in Info block of Manager welcome page\n- [#4470] Fix frozen URI not displayed when editing resource\n- [#4572] Fix installer error log filenames (characters not allowed in Windows filenames)\n- [#4585] Fix database connection processors in advanced upgrade\n- Update xPDO to v2.1.3-pl\n- [#4567] Remove calls to xPDO->log() in xPDOCacheManager->writeFile()\n- [#4557] Minor fixes on Installer Options screen for Traditional package\n- [#4556] Fix js error on Welcome screen of Traditional package's installer\n- [#4076] Fix Edit/Quick Update context menu items in protected categories\n- Fix Context Access query broken in RC4 changes for #4502", "MODX Revolution 2.1.0-rc-4 (April 29, 2011)\n====================================\n- [#4543] Fix preview URLs when FURLs are turned Off\n- [#4537] Trigger refreshURIs when related settings are modified\n- Have modAccess*::loadAttributes() check access_*_enabled settings\n- [#4502] Enable custom targets in modUser->loadAttributes()\n- [#3692] Add policy checks for new_document_in_root and add_children to resource/sort processor\n- [#4526] Additional fixes for output filters on placeholders\n- [#4504] Ensure UserGroup ACLs are deleted along with UserGroups\n- [#4507] Fix usergroup description not being set when created\n- Change modResource->isDuplicateAlias() to return id of duplicate Resource\n- [#4495] Add duplicate URI check to resource/publish action\n- [#3857] Fix placeholder processing when output filters applied\n- [#4362] Fix path issues with Static Resources and base_urls of /\n- [#4074] Require list permission on Context for Resource searches\n- [#4439] Do not allow invalid characters in username / password\n- [#4485] Fix issue with scrolling on drag/drop Element Properties window in small resolutions\n- [#4352] Fix failedlogincount / user blocking logic in login processor\n- [#4373] Fix issue with htmltag TV output render and empty values\n- [#4374] Fix issue with updating files in the edit file page\n- [#4024] Fix issue with LocalProperty grids not rendering list type properties display values correctly\n- [#4400] Trim whitespace from Namespace paths when adding/updating them\n- [#4434] Fix issue with edit panel on contexts\n- [#4372] Fix View button not getting URI change after Save Resource (all Resource types)\n- [#4369] Ensure Save button is active after Template change on Weblink, Symlink, Static Resource\n- [#4471] Set Resource alias properly on update\n- [#4469] Guard against inadvertent creation of duplicate New Resources\n- Add options to configure cache file writing attempts when exclusive locks fail\n- [#4464] Prevent unnecessary TV queries on uncached Resources\n- [#4422] Fix problems updating Boolean settings (System, Context, User)\n- [#4453] Fix File Browser when paths contain \"n_\"\n- [#4447] Fix ACL grid in Edit Context view\n- [#4438] Fix error logging to custom log targets defined by array\n- [#4399] Fix IE8 javascript error on Resource and Element update pages", "MODX Revolution 2.1.0-rc-3 (April 11, 2011)\n====================================\n- Fix invalid merge retained in master branch from 2.1.0-rc-1\n- Fix modResource::save() to refresh uri if isfolder field is dirty.", "MODX Revolution 2.1.0-rc-2 (April 11, 2011)\n====================================\n- Refresh resource tree if resource's parent has changed\n- [#4327] Fix bug with auto-publishing\n- Fix positioning of right panel in mgr UI to make tree/nav static and isolated from scrolling of right panel\n- Make alias required field in resource/create processor when friendly_urls is on but automatic_alias is off\n- [#4280] Fix issue where transport package could not be removed if transport files were removed\n- [#4281] Utilize modX::sourceCache in modParser::processElement()\n- Fix issues with Namespace grid related to context menus and search\n- [#4257] Fix issue where context menus did not show in Contexts grid\n- [#4288] Fix issue with resource preview context menu\n- [#4279] Fix undefined collResources notice with empty Contexts\n- [#3119] Fix modResource->getAliasPath() to use id if set\n- Upgrade MagpieRSS to 0.72 to fix issues with atom feeds\n- [#3623] Fix TemplateVarTemplate foreign key definition in modTemplate\n- Replace specific references to MySQL with more general language\n- [#4185] Change modx logo in mgr to new logo\n- [#4217] Add rank field to modUserGroupMember table\n- [#4271] Highlight currently editing Resource on tree\n- Fix issue with image/file TV and uploading in MODx.Browser when using a custom basePath TV\n- [#4270] Fix issue where images could not be removed when using a custom basePath TV\n- Add User Group related events\n- [#4260] Change title tag in mgr UI to reflect current page\n- [#4256] Add caption field to Quick Create/Update TV\n- [#4261] Change keyboard save shortcut to CTRL+S\n- [#4262] Ensure that FC rules htmlencode their tab/field labels\n- [#4243] Ensure that files that are read-only do not show save button; fix file tree opening\n- [#4244] Add backwards compatibility for Element properties of list type with older indexes\n- [#4236] Fix bug in Template combo that hid category name\n- Improve compression of images in mgr to reduce load times and core transport zip size\n- [#4232] Fix Output Options being ignored in TVs in 2.1.0-rc1\n- Add options to allow ACL queries to be disabled for Contexts, Categories, and Resource Groups\n- [#3941] Fix issue where Resource TV values were not copied when duplicating a Context\n- [#4202] Fix issues with file/image TVs urls/paths when using modx path placeholders\n- Fix sorting/display bugs on UserGroup ACL grids, add grouping for better visibility\n- [#4175] Add modRequest->getClientIp() for better IP handling\n- [#4217] Add rank field to modUserGroup\n- Update version to 2.1.0-rc-2\n- [#4173] Fix issues with math-related output filters and floats\n- [#4205] Ensure old modxcms.com provider is removed after change to modx.com provider\n- [#4220] Fix modX::makeUrl() when friendly_urls not enabled\n- [#4207] Fix issues with checkboxes and Form Customization rules\n- [#4013] Fix modX::_log() to pass target to parent::_log() properly", "MODX Revolution 2.1.0-rc-1 (March 28, 2011)\n====================================", "- Fix issue with properties and i18n in Element properties and in drag/drop box\n- [#4146] Fix issue where new Content Types were always created as Binary\n- [#291] Add principal_targets setting to allow custom ACLs to be loaded by MODX Principals/Users\n- [#99] Allow SymLinks/modX->sendForward() to forward to Resources in external Contexts\n- [#4147] Changing ContentType extension in grid not refreshing URIs\n- [#3967] Fix issue with running user create/update processors more than once in a session\n- [#3542] Hide Template Variables tab on Resource create/update pages if no TVs are present\n- [#788] FC Rules for TVs now display distinctly for create or update\n- [#1118] Add more help for User fields in manager editing page\n- [#2578] Fix issues with manager log view page where sorting was off and grid was not sortable\n- Fix issue where user-created FC tabs were not removable from a Set\n- [#4096] Fix Package Management archive issue when using mapped Windows drives\n- [#3785] Add category filter and search box to TV grid on Template panel\n- [#65] Make locked Resources be read-only rather than unviewable\n- Improve Package Management to show changelog, more supports information in package browser\n- [#4120] Fix issue where TV sort order is reset on Quick Update\n- [#4115] Fix issue with modPhpThumb and filenames with + signs\n- [#2719] Fix reset behavior on autotag/tag TV inputs\n- [#3586] Adjust improper text on Content Types page\n- [#2652] Fix issue where Element could be drag/dropped onto another Element in tree\n- Add ability to select a blank value for ResourceList TV input type\n- [#54] Fix issues with phpThumb and DOCUMENT_ROOT by adding a custom phpthumb_document_root System Setting\n- [#4122] Fix order of execution of validation and plugin events for Element processors\n- [#4105] Add Spanish translation\n- Refactor duplicate alias checks into duplicate URI checks\n- Cleanup deprecated code in Resource templates\n- [#3765] Ensure entries editedon values are set when editing a Lexicon Entry\n- Update ExtJS to 3.3.1\n- [#4073] Add session_name, session_cookie_path, session_cookie_domain as System Settings with blank default values\n- [#4077] Add resource_quick_create and resource_quick_update Permissions to restrict access to Quick actions on Resource tree\n- [#4050] Add tree_show_resource_ids and tree_show_element_ids Permissions to show/hide IDs of Resources/Elements in tree panels\n- Add username field to modTransportProvider, and send it and UUID to providers during transmissions\n- [#3641] Add base URL for Help links in manager for easier management and customization of URLs\n- [#3552] Fix issue causing list-xtype properties to be swapped when using drag/drop into field functionality\n- [#4069] Ensure that you cannot delete the last User in the Administrator user group\n- Add fix for ie9 to get tree nodes to work properly\n- Prevent Category ACL queries on Elements if no entries for current context\n- [#2601] Improve text and drag/drop for weblink/symlink content fields\n- [#3636] Fix issue with empty values on options in list/dropdown/checkbox/radio TVs\n- [#4024] Fix issue with display value not always showing for list properties in element property grid\n- [#4056], [#4041] Add xtype password, template, user, usergroup, etc to available xtypes for System Settings\n- [#3350] Improvements to bugfix for PHP bug 53632\n- [#4054] Improve select binding to be able to use Resource fields via placeholders\n- [#142] Add modResource.setTVValue API method\n- [#4021] Add system setting to allow setting of a custom favicon for the manager\n- [#3589] Fix issue with Static Resource paths when using custom filemanager_path\n- [#4040] Fix issue where Users were always created as active in mgr UI\n- [#4043] Enable drag/drop of users and groups in User Group tree\n- [#4052] Fix issues with element property import and invalid characters causing freezing in UI\n- [#4042] Fix issue in phpThumb base class preventing far property from working\n- [#4049] Add resource_tree_node_tooltip for controlling field in Resource Tree tooltip\n- [#3511], [#2964], [#3601] Fix issues regarding form customization and Templates by removing ajax loading of TVs in Resource panels\n- Consolidate JS for derivative Resource panels to allow to inherit from main Resource panel\n- Add context param to modx.getParentIds\n- [#3754] Ensure Resources can not have their parent set as one of their descendants\n- Add context param to modX.getChildIds\n- [#3612] Improve CDATA filter to not add spaces at beginning or end\n- [#3764] Add delete to actionbar on Resource edit panel\n- [#3585] Add description field to modUserGroup\n- [#3020] Improve trees to expand node on click if no href target is set for tree node\n- [#4006] Show children count rather than IDs on categories in element tree to lessen id ambiguity\n- Fix issue where Quick Create was not respecting unchecked setting checkboxes\n- [#3673] Add \"Save and Close\" button to quick update windows\n- [#3970] Ensure extension is lowercased before checking for allowed status when uploading files\n- [#3920] Ensure modPHPMailer resets replyTo and custom header fields\n- Add UI for managing Resource uri and uri_override fields\n- Remove all deprecated methods and variables scheduled for removal in next minor release\n- Change modxcms.com references to modx.com\n- [#3898] Prevent any non-integer being set in ?a= in mgr interface\n- [#3926] Ensure security/user/create processor can take in a class_key parameter to set class_key for SSO\n- Improve user processors event handling to allow for better SSO integration that can stop save/remove/update\n- Refactor password reset not to send password hash as activation key\n- [#325] Allow configurable user password hashing with PBKDF2 default implementation\n- [#3111] Fix bug causing unnecessary writes to Resource cache files\n- Update xPDO to v2.1.1-pl2\n- Add modResource.uri_override to allow a uri to be manually set and locked per Resource\n- [#3111] Add modResource.uri field to allow context maps to be regenerated in a single query\n- [#3859] Remove redundant check for php bug\n- [#3858] Fix javascript errors from FC hideField rule\n- [#2812] Add link_tag_scheme to define default scheme for makeUrl() call in modLinkTag\n- [#3111] Remove resourceListing, documentListing, and documentMap from context cache\n- [#3111] Cache refactoring with proper file locking, partitioning, and multiple format support\n- [#3111] Update xPDO to release 2.1.0-pl for cache improvements\n- [#3740] Add proxy support to modTransportPackage.class.php\n- [#3693] Fix reversed content-disposition logic on static resources\n- [#3427] Fix issue where User Settings were not respected with filemanager_path/url\n- [#3702] Ensure file/image TVs can have files drag/dropped onto them\n- [#3465] Add sanity check for non-object to log call in modAccessibleObject::_loadInstance\n- [#3615] Fix issue with modx->user->getResourceGroups, set resource groups in \"modx.user.{$id}.resourceGroups\" session key\n- [#3568] Fix double error->failure reference in resource/create processor\n- [#3425] MODx.Browser now loads directory of TV's current value on load\n- [#3481], [#3571], [#3304], [#3569] Fix issue with filemanager_path in non-web contexts\n- [#3009] Add ability to assign TVs to specific directories and base paths, limit file extensions shown\n- [#2679] Add Input Options to TVs, allowing TV inputs to be customized and tweaked", "MODX Revolution 2.0.7-pl (January 14, 2011)\n====================================\n- [#3472] Fix issue due to tree impr that prevented element saving success response\n- Improve loading of mgr pages by preventing trees from rendering until activated\n- [#3205] FC fixes: Ensure Resource Content field can have values set/renamed, that rules on create respect template, and that default values on create are set\n- [#3165] Fix issue where resource/updatefromgrid processor was missing published value if user does not have publish permission\n- [#2] Fix issue in user extended fields where subkeys in 2 separate containers DOM IDs conflict and prevent editing\n- [#3422], [#3374], [#3197] Fix issue with filemanager_url and Image/File TVs and their relative end result URLs\n- [#3201], [#177] Add modResource.leaveGroup, modTemplate.hasTemplateVar, modTemplateVar.hasTemplate\n- [#3350] Fix for PHP bug: http://www.exploringbinary.com/php-hangs-on-numeric-value-2-2250738585072011e-308/\n- [#3326] Fix issue where TV radio/cb options with value of 0 couldnt be selected\n- [#3329] Fix edit and cancel buttons on view resource page\n- [#3329] Clarify Preview link on Resource action toolbar to be more correct \"View\"\n- [#3347] Fix issue where renaming a file broke the browsing of directory tree\n- Fix issue where FC tvDefault rules, regardless of active state, are always run\n- Introduce pdo_sqlsrv support\n- Add database_dsn to config\n- Update xPDO to release 2.1.0-pl", "MODX Revolution 2.0.6-pl2 (January 6, 2011)\n====================================\n- [#3350] Fix for PHP bug: http://bugs.php.net/bug.php?id=53632\n- [#3347] Fix issue where renaming a file broke the browsing of directory tree\n- Fix issue where FC tvDefault rules, regardless of active state, are always run", "MODX Revolution 2.0.6-pl (December 20, 2010)\n====================================\n- [#3143] Fix lexicon grid search to respond to enter key\n- [#3144] Fix issue with reset password and @ being stripped\n- [#3142] Ensure whitespace is stripped from tags in tag/autotag TV types\n- [#3118] Ensure defaults are set in resource/create processor if values are not sent\n- [#3105] Improve memory_limit check in setup to accept integer values from PHP instances\n- [#3106] Add sanity check to resource create/update processors to disallow invalid Resource Group ID references\n- [#3038] Fix problems with filemanager_path settings and absolute URLs in image TV values\n- [#3039] Add symlink_merge_fields setting to disable modSymLink merge behavior\n- [#3103] Alter modSession data field to store more than 64Kb\n- [#3091] Add missing specific dom ID to profile change password panel\n- [#3096] Fix issue with exporting default properties not in a set from an element\n- [#3099] Fix FC rules to respect class_key constraints\n- [#3097] Fix extension_packages to support modx path placeholders, as well as new serviceClass and serviceName parameters\n- [#3085] Ensure Files tree only refreshes active node when creating/updating a file/dir\n- Improve the Permission dropdown and add window in AP Template page\n- [#3083] Fix Form Customization issue when Resource has a blank Template\n- [#3082] Fix Form Customization issue where cacheable and ID fields not able to be hidden/altered\n- [#3034] Fix error creating Resources in Contexts other than web\n- Fix issue with incorrect active permission total in Access Policy grid\n- [#3023] Fix issue where topmenu did not respect manager_language\n- [#3080] Fix missing placeholder in error message when attempting to create a duplicate Element\n- Add new header image to match new site\n- [#3078] Fix issue with htmltag TV widget properties when using = in its value\n- [#3079] Ensure GPC vars are not sent into $scriptProperties array in $modx->runProcessor\n- [#2983] Add sanity check to prevent plugins from firing if disabled (redundancy)\n- [#3057] Fix issue where parent change causes fail to save in UI\n- [#3076] Fix bug where manager returnUrl was not working due to [#2918] fix\n- [#3059] Ensure createdby is set on resource creation\n- [#3041] Fix missing lexicon entry in resource processors\n- [#3043] Fix invalid 200 response header on sendError()", "MODX Revolution 2.0.5-pl (December 8th, 2010)\n====================================\n- Change remove() to removePackage() in modTransportPackage\n- Fix issue with package setup-options attribute not loading forms\n- [#2932] Fix redirect issue after setup and on manager login page caused by [#2918]\n- [#2931] Fix issue where FC rules weren't applying if no UserGroup was set in a Profile\n- Ensure non-Resource FC rules are removed on upgrade\n- [#2918] Address XSS vuln in manager login that allows JS injection\n- Fix issue where // is stripped from filemanager_url http address\n- [#2902] Fix issue where Administrator policy ACLs in non-Administrator groups couldnt be edited\n- [#2915] Ensure UserGroups restriction is enforced in FC Profiles\n- Fix bug when editing FC profiles from a grid, issue where UserGroup wasn't respected\n- Ensure radio TV values still can select if default value is 0\n- [#2869] Fix issue with parent display text in Resource panel\n- [#2892] Fix problem creating folders on filesystem from file manager and browser\n- [#22] Allow SymLinks metadata to override target Resource metadata\n- Cache Resource ACL Policies with the Resource\n- [#2888] Fix problem with elementCache in modX::sendForward()\n- [#2610] Allow Elements to be created under a Category when a Category Policy is in effect\n- [#2869] Standardize initial parent combo value text on Resource edit page\n- [#2736] Colon character \":\" added to default FURL Alias Character Restriction Pattern\n- [#2889] Ensure that a new Resource gets an alias generated if auto_alias is On\n- [#2837] Ensure element properties import escapes <> and provide better error checking\n- [#2886] Ensure SimpleXML and XMLWriter extensions are installed when using FC Set import/export\n- [#2882] Add hidemenu_default setting for setting default hide from menus on Resources\n- Fix issue with derivative Resource types and FC rules\n- [#2858] Extra sanity checks to ensure md5 pw is never sent across get/getlist processors for Users, even if user has access level\n- [#6] Fix issue with RTL text in nodes in Resource tree\n- [#2873] Fix relativity of image urls in drag/drop and TVs when using various filemanager_path/url settings\n- [#2878] Ensure resource panel is marked dirty when drag/dropping into TV\n- [#2828] Fix issue with incorrect content field name for FC rules\n- [#2863] Fix order of execution issues with FC rules and default values\n- [#2874] Enhance User blockedafter/blockeduntil fields to accept time as well as date values\n- [#2529] Fix automatic publish/unpublish\n- Adjust FC rule ranks to properly account for prior FC rules that may affect FC constraints\n- Update xPDO to 2.0.0-pl release\n- [#2661] Fix Template getList processor to respect authority\n- [#313] Fix header error with binary modStaticResource downloads\n- [#206] Fix session bug with opcode caching systems like APC, WinCache, eAccelerator\n- [#2846] Add tag syntax to description hover text for resource fields\n- [#2849] Add ability to drag/drop onto TV fields\n- [#2848] Fix issue with file edit and base paths\n- [#2802] Ensure Category tab is hidden when all TVs are hidden in that Category\n- [#2779] Added Content Editor policy to default list of policies\n- [#2819] Fix bug in FC rules where parent constraint was not traversing up tree to inherit parents\n- [#2744] Fix bug with empty template and TV values\n- [#2841] Fix bug with File Edit page and modFileHandler reference\n- [#2839] Fix bug with failed login count not being updated\n- Add ability to view permissions inherited when viewing an ACL row in a grid\n- [#2834] Fix issue where constraint class was not set on new FC rules\n- [#2819] Fix issue with FC rules and execution order due to setting default templates, constraints\n- [#2830] Permit ability to change FC Set Template when editing a FC Set\n- [#2827] Fix issues related to FC upgrade with Rules with comma-separated names, differing constraints, and template setting\n- Fix issue related to #2625 with deferred tabpanel rendering that caused unpublishing when using Quick Update/Create\n- [#2825] Append idx to each item DOM id when using HTML tag tv output widget\n- [#2823] Add missing lexicon entry for TV output type\n- [#2817] Reorder System top menu for easier navigation\n- [#2820] Add DOM id to Profile page tabs\n- [#2814] Add longtitle, description, template to Quick Update/Create\n- [#2789] Add check to make sure safe_mode is off in setup\n- [#2565] Improve Quick Create/Update Resource to move settings into tab rather than fieldset\n- [#2807] Add tree_default_sort System Setting for configuring the default sort setting for the Resource tree\n- [#2803] Fix css issue with portal blocks on manager dashboard in Fx\n- Add new Form Customization UI, including Form Customization Profiles and Sets; much easier editing of FC rules\n- Fix issue with modInstallSmarty constructor due to Smarty upgrade\n- [#2799] Remove ext3 debug files to save space\n- [#2801] Fix bug with checkbox tvs without specified value options\n- Upgrade Smarty to 3.0.4\n- [#2782] Add changelog to Package View page\n- [#2782] Add ability to view changelog when installing a package via the \"changelog\" package attribute (similar to readme)\n- [#2770] Ensure email TV input type validates email\n- [#2776] Fix issue where context settings grid was not filterable\n- [#2790] Ensure \"number\" TV types restrict input to numbers only\n- [#2730] Fix rendering issue with policy template/group grids\n- [#2794] Allow TV URL output render to handle values that are straight Resource IDs\n- [#2741] Fix bug where Resource Group associations were not copied when duplicating a Resource\n- [#2746] Fix bug where email was sent in registration email rather than username\n- [#2733] Fix bug where Template Var associations were not copied when duplicating a Template\n- [#2742] Fix deprecated evtid reference in plugin duplicate processor\n- Fix various bugs with context settings and wctx param\n- Fix bug where modX::getDocumentChildrenTVars ignores docsort parameter\n- [#2743] Connectors using wrong permissions with processors\n- [#2758] Add modProcessorResponse class to better handle processor responses and error messages\n- [#2758] Add $modx->runProcessor($action,$scriptProperties,$options) to better handle processor execution; deprecated $modx->executeProcessor\n- [#84] Make distribution name available in manager\n- [#2666] Prevent sendRedirect() from preserving request parameters unless specified\n- [#2721] Fixed issue with per page items in MODx.grid.Grid that was incorrectly handling int value\n- [#2691] Fixed issue with duplicate aliases when duplicating a Resource\n- [#2506] Flag properties as dirty when importing from a file on properties grid\n- [#2592] Prevent cache files from being allowed in upload_files setting\n- Improved areas dropdown filter to include number of settings that have that area\n- [#2694] Fixed positioning and scrollbar issue in Fx with success status message on save\n- Added setting clear_cache_refresh_trees that allows you to toggle whether the trees refresh on site cache clear; defaults to false\n- [#2709] Fixed bug where Object-Template policies were unavailable to certain grids\n- [#2597] Fixed bug where Context Setting xtype and area are reset on grid save\n- Upgraded extension_packages setting to JSON for more options with packages and easier editing in Extras scripts\n- Fixed bugs relating to using filemanager_path in a separate context, as well as other bugs with context-specific settings in mgr\n- [#2496] Fixed bug that prevented icon from resetting when dragging Resources into a new parent\n- [#713] Prevent children resources from being prefixed with \"Duplicate of\" when duplicating a resource unless explicitly told to do so\n- [#2581] Fixed bug with resourcelist TV input type to handle resources from multiple contexts\n- [#2518] Added delay to allow FC rules to load before RTEs load to allow RTE TVs to be moved\n- [#2611] Added workaround for ExtJS bug with checkboxes/radios and an inputValue of string 0 that would prevent toggling\n- [#2512] Have remove setup/ dir checked by default if not using Git version of MODx\n- [#2699] Fixed loading issues with help panel on slow connections\n- [#2701] Fixed issue where description did not show until refresh when adding a new Permission to an Access Policy Template\n- [#2695] Postfixed Template to names of Access Policy Templates for clarity\n- [#2700] Fixed bug with Access Policy Template editor that reset values on save\n- [#2690] Renamed Administrator Access Policy Template Group to Admin\n- [#2563] Fixed chmod action on directories from File Tree\n- [#2693] Properly sort country indicies to properly display in dropdowns\n- [#2562] Added confirm dialog and success response for emptying recycle bin\n- [#2634] Ensured context key is changed when changing parent of a Resource via Edit Resource page if context is different for new parent\n- [#2631] Fixed issue when drag/dropping categories onto other categories in Element tree\n- [#2659] Fixed issue where action buttons were overlapping tabs on edit pages\n- [#2668] Fixed issue with FC rules and labels on checkbox/radio fields\n- [#2582] Fixed bug with orm tree preventing attributes on the root node\n- Fix bug in phpthumb allowing remote src parameters regardless of settings\n- [#2555] Expose additional phpthumb options in System Settings\n- [#2503] \"Preview\" inaccurately described viewing current page/site. Changed to \"View\".\n- Fixed help message strings to correct URLs\n- Fixed missing options array call in modRestClient, isArray call in modRestCurlClient\n- [#2545] Added setting resource_tree_node_name to allow users to specify the field used for the node text on the Resource Tree\n- [#2639] Prevent user from specifying a FC rule with Action of none\n- [#2641] Fixed issue where template was reset incorrectly when canceled on template change\n- Fixed issue where Permissions were being duplicated on setup due to relational db issue\n- [#2646] Prevent removal/editing of default Administrator policy ACLs to prevent users from accidentally removing access to web context\n- Added modAccessPolicyTemplate and modAccessPolicyTemplateGroup for easier managing and editing of Access Policies, including a UI for managing Access Policy Templates\n- [#2483] Auto-generate alias when duplicating a Resource\n- [#2645] Set Resources unpublished when duplicating\n- Update to xPDO v2.0.0-rc3\n- [#2501] Fixed menu not being loaded on immediately-added policies without page refresh, added bulk actions to policy grid\n- [#2505] Save Property Set now shows feedback and success message\n- [#2507] Export properties now prefixes filename with property set name\n- [#2624] Improved Users grid to allow batch editing from right-click context menu\n- [#2609] Remove filter commands and modifiers from scriptProperties passed to modElement/modTag instances\n- [#2500] Improved CSS on welcome page for Fx users\n- [#2532] Improved Resource tree icons to better shown when a Resource has children as opposed to when it is marked as a container\n- [#2602] Improved language on Users access permissions grid to clarify action\n- [#2614] Expand comment field on modUserProfile to handle more than 255 characters\n- [#2613] Ensured User Groups in mgr are sorted alphanumerically\n- [#2599] Fixed issue where Add Element to Property Set window form values were not cleared on second loading\n- [#2596] Fixed issue where User Groups could not be removed\n- [#2542] Fixed hardcoded language lexicon load reference in policy/get processor\n- [#2573] Fixed issue with backslash in TV output render property values\n- [#2594] Fixed issue where special characters were being stripped from phone numbers in user profile\n- Fixed issue with file tree that prevented image thumbnails from showing\n- [#2525] Fixed filemanager_path issues by added filemanager_path_relative setting, and then calculating from that\n- [#2589] Fixed issue with port 80 feeds in magpie RSS feed parser\n- [#2544] Fixed issue with updatefromgrid processor with User Settings\n- [#2560] Fixed issue with resourcelist TV not persisting set value\n- [#2586] Add rank field to FC rules allowing organizing of order of execution\n- Update core schemas and regenerate maps for new xPDO index elements\n- [#69] Allow Transport Vehicles to abort installation when validation fails\n- Update xPDO version to 2.0.0-rc2 (official release)\n- [#2552] Fix scope issues when passing nested arrays in Chunk properties", "MODX Revolution 2.0.4-pl2 (October 15, 2010)\n====================================\n- [#2502] Fix fatal error with Resources protected by Resource Groups\n- Fixed issue with resourcelist TV", "MODX Revolution 2.0.4-pl (October 14, 2010)\n====================================\n- Fixed issue where redirect was not working after creating new derivative resource\n- [#2485] Fixed issue where placeholder was in duplicated Access Policy\n- [#2492] Fixed reference in menu to bugs.modx.com\n- [#2486] Removed hardcoded language reference in lexicon load in access permissions getList processor\n- [#126] Ensured clearing of cache when deleting a Template Variable\n- Fixed issue where cancel button did not work on Resources after save\n- Fixed issue with URL TV Output Render and empty input values\n- Fixed issues with checkboxes/radios in TVs and widths when hidden\n- Fixed various issues with thumbnails in MODx.Browser and return paths in separate contexts\n- Added toggle setting for drag/drop in Resource and Element trees\n- [#MODX-2346] Allow login/logout processors to handle multiple contexts\n- [#MODX-2405] Fixed issue with border on portal panels in mgr home screen\n- Fixed issue with TV output render that stripped whitespace in delimiter\n- Fixed hanging save issue that occurred when HTML was in pagetitle/longtitle in a Resource\n- Fixed issue where TV values were being erased when a TV was hidden via Form Customization\n- Updated reference to help in Form Customization page\n- Fixed trivial issues with widths in richtext tvs\n- [#MODX-2415] Added fix to prevent adding of orm tree attributes with the same key on the same level\n- Added resourcelist TV input type for easier listing of resources in a tv input\n- Updated ExtJS to 3.3.0\n- [#MODX-2378] Fixed issue where action toolbar was on left in IE7\n- [#MODX-2408] Fixed issue where sorting was not available for description field on search page\n- Fixed issue where modx->resource was not available to TV input option values or default values in mgr\n- [#MODX-2410] Fixed issue with urlencoded context key on context edit page\n- [#MODX-2407] Fixed issue where user settings were not respected in connectors in mgr\n- [#MODX-2279] Fix bad AJAX response if database does not exist or can't be created during setup\n- [#MODX-2404] Fixed issue with auto_menuindex and multiple contexts\n- [#MODX-2354] Fixed issue with image TV loading incorrect URL in thumbnail preview on initial load\n- [#MODX-2357] Properly addressed issue where FC hideTab rule was causing hidden tabs to show if they were active at load\n- Refactor modAccessibleObject to centralize load policy check in _loadInstance()\n- Update xPDO for several critical bug fixes\n- [#MODX-2402] In Package Browser, Most Popular/Recently Added package names are now links to auto-search in grid\n- [#MODX-2397] Added filtering and search to FC rule grid\n- [#MODX-2401] Adjusted JS version postfix code to not adjust .php (or non-js) files used as script src targets\n- Improved context menus on FC rule grid to allow for batch actions on selected items\n- Added `for_parent` field to FC rules, to allow for more fine-grained control of rule applications\n- [#MODX-2385] Fixed issue when Context ACL is using no policy that prevented grid loading\n- [#MODX-2380] Fixed issue with upgrades and rb_base_dir, rb_base_url and filemanager_path\n- [#MODX-2246] Added topmenu_show_descriptions system setting to be able to toggle the top menus description text\n- [#MODX-2375] Improved class key field in Resource panel to a dropdown, added modClassMap for easier querying of resource/element types\n- [#MODX-2391] Fixed issues with FC rules not being respected on resource/create with default values for new Resource\n- [#MODX-2382] Fixed dynamic width of fields in windows across ui\n- [#MODX-2383] Fix inability to update rank of TV's in template editor\n- [#MODX-2379] Fixed issue where permission checks were swapped in Resource context menu with regards to delete/undelete\n- [#MODX-2384] Fixed issue where treepanel still showed if all trees were hidden via permissions\n- [#MODX-2389] Fixed issue where setup options, license and readme displays were not cleared after installation of package\n- Fixed issue where loading mask shows up and never disappears on extended Resource types\n- [#MODX-2388] Fixed issue with save button and user settings\n- [#MODX-2387] Fixed issue with user settings not able to be added via mgr ui\n- Fixed bug that would reset provider for updated packages\n- Fixed issue with paging toolbar pageSize being interpreted as string rather than int\n- Fixed issue where parent id constraint was ignored for default template on new Resources\n- Added sanitization to REQUEST_URI for login controller\n- Updated version to 2.0.4-pl", "MODX Revolution 2.0.3-pl (September 30, 2010)\n====================================\n- Fixed error in modResource::cleanAlias when context var is not available\n- [#MODX-2376] Fixed issues with updating settings on the context page\n- Fixed security issue with login screen and resource TV controller that allowed html injection\n- Fixed issue where clear cache checkbox isn't checked on Element pages\n- [#MODX-2370] Fixed various bugs with plugin event association on plugin page\n- [#MODX-1823] Improved the System Info panel by extracting data from phpinfo()\n- [#MODX-2362] Added missing OnResourceTVFormPrerender event\n- [#MODX-2374] Fixed issue where children nodes were not being moved with parent into new context\n- [#MODX-2373] Fixed imageTV issue where thumbnail was not cleared on data clearing\n- [#MODX-364] Fixed regClient* methods in cacheable Snippets on cacheable Resources\n- [#MODX-2370] Fixed issue with saving property sets on plugin events\n- [#MODX-2369] Fixed issue with modLinkTag and output filters where the filter commands were included in the URL\n- [#MODX-2350] Ensure that new Contexts always have Admin and Resource policy for Admin user group assigned to them\n- [#MODX-2352] Ensure that Context Settings appropriately override System Settings in core-level parsing where a Context is existent (example: site_unavailable_page)\n- [#MODX-2356] Ensure that OnResourceDelete and OnResourceUndelete events in update processors fire at correct times, after save()\n- [#MODX-2361] Ensure that a user in the Administrator group *always* has access to a Context when it is restricted in another user group\n- [#MODX-2357] Fixed bug that occurs when hiding a tab with FC rule that is the default active tab\n- [#MODX-2358] Fixed rare bug occurring with treestate in Chrome due to undefined variables in path\n- Fixed various issues with package management and the add new package button\n- Fixed bug where ?v=203pl is being added to content with .js in it, due to earlier commit to prevent js caching\n- Fixed issues with ellipsis/limit filters and special chars\n- [#MODX-2353] Fixed bugs with checkbox/radio TVs and complex values with HTML/quotes in them\n- Fixed some bugs with deleting a file in MODx.Browser in the actual view pane\n- [#MODX-2354] Fixed issue with imageTV and incorrect preview url reference\n- Fixed ellipsis output filter to use &#8230; instead of ...\n- [#MODX-2327] Fixed bugs with Form Customization not being respected\n- [#MODX-2349] Fixed bug with Form Customization and fieldDefault rule with template field\n- Added code to prevent caching of JS after upgrades by postfixing version to JS URLs\n- [#MODX-2342] Fixed issue where xhtml_urls setting wasnt included in build\n- [#MODX-2345] Fixed issue with templates and categories in mgr not persisting\n- [#MODX-2341] Fixed issue with redirect statement on login page in certain environments\n- [#MODX-2343] File upload now respects upload_* extension restrictions\n- [#MODX-2344] Respect context-specific filemanager_path in upload/remove actions on directory tree in mgr", "MODX Revolution 2.0.2-pl (September 17, 2010)\n====================================\n- Fixed issue where Add New Package would not work when selecting a provider manually\n- [#MODX-2339] Fixed issue with caching menus in mgr and multiple languages\n- [#MODX-2340] Fixed issue with initial resource values reverting after a save\n- [#XPDO-72] Fix invalid call to $this->manager->getPhpType()", "MODX Revolution 2.0.1-pl (September 16, 2010)\n====================================\n- [#MODX-2317] Add responseCode parameter to modX::sendRedirect() method\n- Fixed issue with @DIRECTORY binding not postfixing base path with / before value\n- Many styling enhancements, fixes for [#MODX-2264], [#MODX-2193], [#MODX-1885], [#MODX-1847]\n- Fixed issue with lexicon translations for permissions dropdown in mgr\n- Enhanced system settings grid to autosave without refresh, which allows for tabbing between settings via keyboard to set values\n- [#MODX-2325] Updated placeholders in setup lexicons for french/german languages\n- Added an editable dropdown for Permissions tab when editing an Access Policy for easier addition of Permissions\n- Fixed issue where default template was overriding empty template resources\n- [#MODX-2325] Updated Czech translation\n- [#MODX-2329] Login page now auto-focuses on username textfield\n- Add missing modCategoryClosure to create_tables script in setup\n- [#MODX-2280] Fixed bugs with IE and package management\n- Prevent issue where a User Group can select itself as a parent\n- Allow typeahead on user field when adding a User to a User Group\n- Optimized Resource Group tree in mgr UI\n- Fixed issue where > 20 records were not showing in ACL lists in User Group edit panel\n- [#MODX-2206] Prevent issue where renaming a menu's lexicon key orphans child menus\n- Fixed rendering bugs in file edit panel, as well as optimized its loading and streamlined RTE integration on the panel\n- [#MODX-2202] Removed deprecated modAction objects to prevent confusion\n- [#MODX-2325] Updated Swedish translation\n- Prevent bug that causes modal to overlap welcome screen\n- Allow non-empty responses to OnBeforeTVFormSave to prevent save\n- [#MODX-2201] Ensure MODX_PROCESSORS_PATH is upgraded correctly on upgrades where the core is moved\n- [#MODX-2323] Allow non-empty responses to OnBeforeDocFormSave to prevent save\n- [#MODX-2309] Ensure upload files button always uses the active node as the path, or if it is a file, its parent directory\n- [#MODX-2295] Ensure menuindex can be overridden in resource creation if auto_menuindex is set to true\n- Fixes to resource panels to adjust widths, loading of values properly\n- [#MODX-2318] Fixes to TVs in Resource pages to make order sorting work correctly\n- Abstracted setup database methods to driver-specific structures to accomodate for various future db drivers\n- [#MODX-2241] Added archive_with setting so users with improper ZipArchive compiles can switch back to PCLZip\n- Updated xPDO to include sqlite drivers\n- [#MODX-2308] Added UUID to all modx installs for usage in extras, custom providers, stats tracking, etc\n- [#MODX-2303] Fixed issue where resource editing pages were not respecting context settings\n- [#MODX-2302] Fixed issue with loading of input option values in TV related to optimizations in 2.0.1\n- [#MODX-2297] Fixed output filters limit/ellipsis when dealing with special character cases\n- [#MODX-2290] Added image preview when hovering over images in file tree\n- Added extra sanity checks in Package Management in case transport zips are not extracted\n- Make package grid update available Yes clickable to update\n- Cleaned up and better abstracted modRestClient and modRestCurlClient code\n- Fixed bug in setup during upgrade-advanced where DB information was not being checked correctly\n- Lots of improvements to handling and caching of thumbnails in manager\n- Fixed bug where reset filter on settings grid was not resetting to core namespace\n- [#MODX-2178] Added missing settings and lexicon values for those settings to build/lexicons\n- [#MODX-2179] Lexicons in Setup now use placeholders rather than sprintf for better i18n support\n- Added phpthumb_imagemagick_path for users that need to change the imagemagick path for different environments\n- [#MODX-2288] Dont duplicate TV Resource values when duplicating a TV unless explicitly told to\n- [#MODX-2217] Persist sort order of Resource tree\n- [#MODX-2291] Prevent editing of binary files to prevent zeroing out of file when saving\n- [#MODX-2185] Resource tree expand all toolbar button now expands all levels deep\n- [#MODX-2260] Added ability to rename ORM container nodes on extended fields\n- [#MODX-2285] Added ability to dynamically set number of results for any grid in manager, as well as a default number via default_per_page system setting\n- [#MODX-2284] Fixed bug in modX::getChildIds\n- Adjusted the way resources/elements load data in mgr edit/create pages to vastly speed up load times\n- [#MODX-2282] Fixed deprecated help menu URLs\n- Trees now properly handle state, allowing multiple state paths to be set\n- [#MODX-2163] Give area combobox in System Settings a bit more breathing room\n- [#MODX-2259] Fixed issue with empty value fields in extended/remote fields via ORM widget\n- [#MODX-2249] Fixed issue with misleading comment in modTemplateVar::getValue\n- [#MODX-2270] Added option to sort by pulishedon in the resource tree\n- [#MODX-2278] Removed non-used files and added space to empty files\n- [#MODX-2250] Fixed bug where Checkbox TVs with default value dont allow all checkboxes unchecked\n- [#MODX-2274] Introduced filemanager_url setting to handle URLs when filemanager_path is outside the webroot\n- [#MODX-2251] Fixed issue where @bindings in TVs were running during input, preventing setting values\n- Fixed bug with modContext::getOption and default values\n- [#MODX-2184] Fixed issues with MODx.rte.Browser and context-specifics\n- Fixed issue with filemanager_path in Windows\n- Fixed a possible issue in base file perms in modFileHandler\n- Fixed some random typos in system settings data and lexicon translations\n- Fixed bug where userinfo filter was outputting wrong content when user was empty\n- [#MODX-2263] Fixed IE issue with dropdowns as TVs\n- [#MODX-2183] Autotag values are now alphabetically sorted\n- [#MODX-2240] Site - Preview now dynamically previews current editing context\n- Fixed invalid login issue that prevented OnUserNotFound from firing on mgr login screen\n- [#MODX-2238] Fixed bugs regarding parent constraint and default template\n- [#MODX-2234] Fixed issue when drag/dropping a Resource into the parent field\n- [#MODX-2226] Fixed bugs with date output filter not behaving as expected\n- [#MODX-2184] Fixed issue where context was not respected in MODx.Browser instances, fixed bugs when specifying paths outside MODX_BASE_PATH\n- [#MODX-2236] Added sanity check to modTemplateVar::getRenderDirectories with custom dirs\n- Added modResource::joinGroup\n- Added helper JS function MODx.hideTV to modext\n- [#MODX-2233] Fixed issue where qtip was not showing on Elements in a Category\n- [#MODX-2203] Fixed issue where root of file tree was not accessible after navigating away\n- [#MODX-2192], [#MODX-2232] Fixed issues with settings and their translations, names in the Settings grids\n- Adjustments and optimizations to menus/actions processors and js\n- [#MODX-2231] Fixed issue where saving translated properties would overwrite key with translation\n- [#MODX-2220] Fixed bug where save_user was needed to change profile\n- [#MODX-2213] Always include english lexicon when loading a lexicon to act as a backup translation\n- [#MODX-2210] Added strip for xss in manager a variable\n- [#MODX-2205] Fixed issue with saving resources with resource fields having html and unescaped content\n- [#MODX-2198] Fixed directory checks on context web path for advanced distribution\n- [#MODX-2194] Fixed issue with modLexicon::fetch not working if a prefix is set\n- Removed SVN commit log from top header now that we're in Git\n- Adjusted version to 2.0.1-rc1", "MODX Revolution 2.0.0-pl (LastChangedRevision: 7216, LastChangedDate: 2010-07-21 09:10:12 -0500 (Thu, 21 Jul 2010))\n====================================\n- [#MODX-2159] Fixed bug where richtext_default was being ignored in Quick Create\n- [#MODX-2174] Fixed bug where manager_language was being ignored in Connectors, check for ctx init\n- [#MODX-1715] Added reference to setting keymap_save to allow for overriding of save shortcut key\n- [#MODX-2008] Updated Russian and Japanese translations\n- [#MODX-2008] Added in Thai translation\n- Fixed typo in filters english lexicon\n- [#MODX-2008] Added in French translation, updated German translation\n- [#MODX-2173] Fixed issue with IE and package installation wizard\n- Fixed setup directory checks for advanced builds\n- Fixed incorrect welcome URL in build\n- [#MODX-2008] Added in Czech translation\n- Configured phpdoc.ini file for SDK build\n- Fixed bug in file tree where URL was absolute rather than relative when being drag/dropped\n- Added OnFileEditFormPrerender event to allow plugins to fire on file editing form\n- [#MODX-2172] Fixed bug where tooltips for stay buttons were behind window\n- Sanity checks to tv render directories\n- Removed deprecated CSS icon reference\n- [#MODX-2169] Fixed bug with TV default values, inheriting and non-linear TV inputs\n- [#MODX-2170] Fixed error where element names cannot have less than 3 characters\n- [#MODX-2169] Properly handled @INHERIT binding in TV inputs\n- [#MODX-2165] Changed 'Remove Package Version' context menu item behavior to allow to show on non-installed versions to allow rollbacks from downloaded but not installed updates\n- [#MODX-2164] Fixed issue that might cause random, non-affecting error during package updates\n- [#MODX-2008] Added in Japanese translation\n- [#MODX-2163] Default settings grid to show only core namespace settings to reduce confusion\n- Added autotag TV input widget that grabs tags from a list of the tags so far for all content values for that TV\n- [#MODX-2161] Added sanity check for incorrect or invalid filemanager_path values in file tree\n- Added missing deleted checkbox on resource panels\n- [#MODX-2167] Fixed issue where duplicate button was creating incorrect duplicate name\n- [#MODX-2162] Fixed issues with set to default in TV values, reliance on processedValue\n- [#MODX-2168] Fixed new user panel issue with missing JS reference\n- [#MODX-2160] Fixed bug where config check was running checkPolicy on resources that caused inadvertent missing unavail/error page message\n- Some query optimizations in processors\n- [#MODX-2159] Ensure richtext_default setting is respected\n- Fixed bug where context settings create modal wasnt resetting values\n- Added missing tabpanel IDs for various tabpanels across mgr ui\n- Fixed bug that was strtolower'ing any strings in tabNew FC rule\n- Added grid renderer to FC grid\n- Tweaks to general UX, other slight cosmetic fixes\n- [#MODX-2156] Fixed unitialized variable in modTemplateVar::renderOutput/renderInput\n- [#MODX-2152] Fixed issue where local package dialog wasnt showing after clicking modxcms.com package browser\n- [#MODX-2154] Fixed issue where publish_document access permission was being ignored in resource processors\n- [#MODX-2149] Fixed issue where Package Management's modal would only once if hidden\n- Fixed issues with stay button on resources\n- [#MODX-2008] Added Swedish translation\n- [#MODX-2148] Fixed image TV thumbnail sizing\n- [#MODX-2145] Fixed 'New' context menu text to be easier to translate\n- Slight tweaks to CSS for MODx.Browser file thumbs\n- [#MODX-2147] Added phpThumb settings for controlling thumbnail output in manager, defaulted zoomcrop to off and force aspect ratio to on, center\n- Fixed erroneous change template message\n- [#MODX-2143] Fixed filemanager_path implementation so that thumbnails and relative URLs in browsing work with absolute and relative paths as setting\n- Removed powered-by text in request headers in AJAX calls\n- [#MODX-2143] Fixed issue where if filemanager_path was set differently that URL insertion on TVs or drag/drop was incorrect\n- Added urlencode/urldecode to filters\n- [#MODX-2132] Remove friendly_url_prefix reference that was causing PHP warnings without breaking makeUrl()\n- [#MODX-2142] Fixed issue where translations in settings, properties and permissions were not being translated or falling back to english\n- [#MODX-2132] Reverting commit in r7125 due to side issue caused by fix in it\n- Hardened security on some file download actions in mgr such as console output, phpinfo, properties export\n- Adjusted setup expiry to 15 minutes\n- [#MODX-2139] Added message to display if setup has to restart due to timeout\n- [#MODX-2140] Fixed welcome page to point to static page rather than atlassian stack\n- Update Help URLs to new base url for docs\n- Some UI tweaks to lexicon grid, added reset() JS method to MODx.Window for shorter code\n- Added in create entry to lexicon management\n- Ensure $modx is available in custom TV renders\n- [#MODX-2137] Fixed bug in image TV output render\n- [#MODX-2138] Fixed textarea bug in system settings\n- Allow MODx tags in TV descriptions in input renders, but prevent HTML tags\n- Fixed bug where output render type was being ignored\n- Ensure tv data isnt sent back in resource update processor, to prevent escaping problems with richtext tvs\n- [#MODX-2109] Fixed setup to have upgrade mode not go to editing database/contexts, only advanced upgrade goes there\n- Fix object caching bug in modAccessibleObject::_loadCollectionInstance()\n- Update xPDO 2.0 to revision 429\n- Ensure extended fields can be added to users with none pre-existing\n- [#MODX-2131] Fixed other issues with TV values and rendering\n- Added ctrl+alt+p key shortcut when updating a Resource to preview it\n- Prevent illegal drops of actions to menus, menus to actions, in trees on Actions page\n- Slight fixes, tweaks to plugin events grid\n- [#MODX-2130] Fixed typos and missing references in mb-based output filters\n- [#MODX-2131] Fixed various issues with TV rendering, values, and in multiple contexts\n- [#MODX-1404] Make MySQL client version check a warning only for older versions\n- [#MODX-1404] Remove MySQL client version check for 5.0.51\n- [#MODX-2024] Fix use of %s strftime modifier in modSessionHandler::write()\n- [#MODX-2132] Remove friendly_url_prefix reference that was causing PHP warnings\n- [#MODX-2107] Fix errors with friendly alias slug generation with certain multi-byte characters\n- [#MODX-2114] Fix Error Caching Resource log message when site unavailable or other transient Resources are constructed\n- [#MODX-2129] Added missing Resource events\n- Fixes to Messages page/grid\n- Added optimize database button on database tables grid\n- Fixed reference bug in resource/update processor\n- Improvements to Users grid to dim inactive users\n- Fixed a few bugs with MODx.Browser and file tree\n- [#MODX-2127] Added message to Package Management if cURL or Sockets is not installed that prompts user to do so\n- Added ability to send warning/error messages to all MODx.* grids/trees\n- [#MODX-2128] Fixed MODx.Browser in RTE mode\n- Added modManagerRequest::addLangTopic,setLangTopics,getLangTopics assistance methods\n- [#MODX-2125] Various fixes for manager log page\n- [#MODX-2023] Added sanity checks for settings caches in setup, ensure settings caches are removed post-setup\n- [#MODX-2064] Ensure Action combos in System Actions page are reloaded when an action is updated/created/removed\n- Fixed invalid validation rule on element classes\n- [#MODX-2091] Ensure duplicate maintains published status\n- [#MODX-2123] Added workaround for IE with Quick Update Resource window\n- Modified validation on modChunk, modPlugin, modSnippet, and modTemplateVar to allow spaces within a name\n- [#MODX-2052] Fixed bug with loading multiple MODx.Browser instances in non-file management circumstances\n- Updated duplicate processors to check validation, return more informative messages, sanity checks\n- Removed duplicate days keys in lexicon\n- Fixed issues when TV render directories are overridden\n- [#MODX-2115] Fixed issue with phpthumb reference and capitalization, and when base_url is /\n- [#MODX-2113] Fixed CTRL+SHIFT+H shortcut for hiding left nav\n- Fixed bug in ORM tree relating to adding root nodes when subnode was selected\n- Added ability to add/remove attributes and containers to UI ORM trees, specifically in User extended and remote data\n- Added UI for editing extended User Profile data\n- [#MODX-2116] Fixed bug in depth search in modX::sanitize\n- [#MODX-1150] Changing class_key for a Resource now reloads the page to change editing area\n- [#MODX-2077] Config check screen in welcome panel now is same width as other panels\n- [#MODX-1648] Lexicon Management now loads by default the current manager_language\n- [#MODX-1743] Package update now shows status alert when package is already up to date, rather than an error\n- [#MODX-2119] Fixed bug in IE where onunload was firing regardless, preventing moving off page seamlessly\n- [#MODX-2112] Fixed bug where admin password reset was not working\n- [#MODX-2111] Fixed bug where language settings were not set after running setup in another language\n- [#MODX-2110] Fixed bug where resource fields were not being updated on update, causing publishedon errors\n- Adjusted version for pl development", "MODX Revolution 2.0.0-rc-3 (LastChangedRevision: 7083, LastChangedDate: 2010-07-07 12:20:55 -0500 (Wed, 07 Jul 2010))\n====================================\n- Updated German translation\n- Fixed bug with new installs and base template name\n- Fixed UI issue with Namespace path being unwantingly translated\n- Upped timeout on setup settings cache to 10 minutes; was far too short\n- [#MODX-2040] Fixed bug with setProperties and merge argument\n- Slight tweaks to phpthumb default config\n- Added sanity check when using multiple TV render directories\n- [#MODX-2100] Fixed content type creation for binary type bug, bug in build with regards to content types\n- Added flag to setup to fix proceeding error after install\n- Fixed setup to return setup process to very beginning when settings timeout, avoiding various errors about classes not being found\n- Added modx-tv-checkbox class to resource TV checkboxes for easier DOM manip\n- Added showCheckbox setting for resource TVs display to allow for extensibility and TV targeting\n- Added phpThumb specific settings\n- Added OnResourceTVFormRender event for affecting TV displays on resources\n- [#MODX-2104] Auto-detect correct value and set use_multibyte on new installs\n- [#MODX-2104] Added 'use_multibyte' setting that allows for use of mb_* functions for multibyte characters; fixes bug with MB chars in output filters\n- [#MODX-2019] Added default Element policy\n- Fixed issue with Ext.form.BasicForm and prior commit, adjust else/if condition\n- Added headers check to all Ajax requests to connectors to require unique site ID header to harden security\n- Added modx-content-above and modx-content-below divs for RTE usage\n- [#MODX-2008] Updated Russian translation\n- Enabled RTEs to be used on TV default value field\n- Added which_element_editor setting, which allows for usage of multiple RTEs for Elements vs Resources\n- Fixed bug with custom_resource_classes setting implementation on blank values\n- [#MODX-2094] Enabled Packages to be able to have their Provider changed\n- [#MODX-1809] Added manager_time_format to allow changing of time formats in mgr widgets\n- Added extra var to pass revo version in transport provider requests; helps with download metrics and version checking\n- Optimized package grid by moving menus to JS\n- Fixed issue where manager_language setting was being ignored in mgr connectors\n- Enhance security on language string loader\n- [#MODX-1834] Adjusted color on Yes/No on packages grid to more reflect intent\n- Readjust JS firing timing for Elements to prevent RTE timing errors in faster browsers\n- [#MODX-2090] Added auto_check_pkg_updates_cache_expire setting, which caches package update checks in Package Management to speed up grid load times\n- Ensure Resource pages using RTEs always have save btn enabled\n- Fixes to RTE loading in Element panes, other issues regarding timing of plugin firing\n- Fixed bug with area listings in combo in system settings\n- [#MODX-1961] Fixed bug with octal perms when creating directories in the admin\n- [#MODX-1527] Fixed bugs in admin confirm password field on install\n- Fixed Package Management in IE8\n- Styling improvements\n- Fixed IE issue on navbar, few other tweaks to package management for IE\n- [#MODX-2032] Fixed topic varchar length issue with UTF-8 installs\n- [#MODX-1612] Added Create Menu context menu on root node for menus tree\n- [#MODX-2020] Ensure error when creating duplicate context ACLs shows\n- Tweaks to Package Management browser JS to allow for more consistent rendering\n- [#MODX-2051] Stripped tags from TV description field on input rendering\n- Added 'custom_resource_classes' setting, which allows you to specify custom resource types for the resource tree\n- Tweaked FC tvMove rule to be more consistent with values of other TV FC rules\n- Allow blank names (not keys) in Settings create/update windows; tweaks to query in package management grid\n- [#MODX-1737] Container resources can now have names specified on duplicate\n- [#MODX-2074] Fixed bug where property descriptions were not i18n-able\n- [#MODX-2062] Date TV type now can store time; updated datetime ExtJS xtype to latest version\n- [#MODX-2046] Added 'collapse' toggle to left trees, shortened username on top right to allow for small resolutions\n- [#MODX-2067] Fixed bug with cleanAlias and a non-existent lexicon string\n- [#MODX-2086] Fixed a few bugs in package management styling\n- Tweaks to context menu styling\n- [#MODX-2078] Context menus now show under cursor\n- [#MODX-2083] Fixed bug where setting editedon was returning invalid date\n- [#MODX-2061] Fixed erroneous lexicon entry for cache_handler setting description\n- [#MODX-2085] Fixed issue with namespace path not being translated on get\n- Added ability to activate/deactivate FC rules from context menu\n- fieldVisible, fieldLabel, tvVisible, tvMove Form Customization rules now support multiple fields via comma-sep list\n- Added functionality to Form Customization to add new Tabs and move TVs to other tabs\n- Applied CSS gradient styling to grids, tabs\n- [#MODX-2056] Fixed CSS for topmenu, restyled to add contrast and enhanced\n- Cleaned up TV display panel, removed TV reload button, extended fields all the way across\n- [#MODX-1832] moved \"Set to Default\" to a fade-in icon\n- Prepared code for oncoming feature to move TVs into other tabs\n- Removed credits from about pane, consolidated tabs\n- Fixed permissions checks on resource tree context menu when policies are limited\n- Added prefix filtering to modLexicon::fetch\n- Added modTemplateVar::getDisplayParams for easier fetching of display_params for a TV\n- Fixed bug with custom TV render paths\n- Added phpThumb to core, added connector for secure access, integrated into MODx.Browser\n- Ensure categories in TV panel are sorted alphanumerically\n- Added stripString, cdata, replace, fuzzydate and ago output filters\n- [#MODX-2045] Added ExtJS, Smarty, PHPMailer, MagpieRSS version into System info\n- [#MODX-2057] Fixed bugs with action/menu trees\n- Fixed bug with is_writable check in setup; was checking core/config rather than just core/config/config.inc.php\n- [#MODX-2042] Fixed extra beginning slash for image/file TVs\n- Add validation to processors for Chunks, Plugins, Snippets, and Template Variables\n- [#MODX-1998] Disallow reserved Template Variable names (i.e. Resource field names)\n- [#MODX-2033] Fix bug with unchecking Template Variable access when editing a Template\n- Have modX::switchContext() update placeholders from config on successful switch\n- [#MODX-1774] Remove redundant setting of placeholders from modX::$config in modRequest::handleRequest()\n- [#MODX-2031] Fix modX::stripTags() and modX::sanitize() to properly strip nested element tags\n- [#MODX-2027] Added icon to file tree to show MODx Browser, for a different view on file management\n- [#MODX-1924] Made more precise the cursor pointer change on buttons in mgr\n- [#MODX-1904] Fixed bug with phx placeholders in modTranslate095 class\n- [#MODX-1535] Fixed bug with transparent background for grid-based comboboxes\n- [#MODX-1904] Fixed bug with phx placeholders in modParser095 class\n- [#MODX-1936] Lexicons now fallback to English if no translation is found for specified language\n- [#MODX-1781] Fixed z-index issue with top nav and window masks\n- [#MODX-217] Added create element type icons for Element tree\n- [#MODX-217] Added directory create icon to file tree toolbar, changed upload files button to icon\n- [#MODX-2022] Fixed bug regarding php file permissions and writable checks\n- Fixed bugs related to loading of RTEs for TVs in derivative resource classes\n- Enhanced image TV to show preview of image, adjusted to display below\n- [#MODX-2015] Added sanity check to prevent users from dragging Resources to a non-existent context\n- [#MODX-2013] Fixed bug where hiding fields with Form Customization would disable them from being sent\n- Fixed bugs with System Settings grid due to erroneous merge in UI styling\n- [#MODX-2012] Made Form Customization grid sortable\n- [#MODX-2011] Fixed MODx.grid.Grid::getSelectedAsList to work in Fx,IE\n- Added more sophisticated check for writable directories in setup to ensure compatibility across environments\n- Fixed bug where manager_language setting was ignored\n- [#MODX-2007] Redirect to requested mgr page when logging in\n- Adjusted version for RC-3 development", "MODX Revolution 2.0.0-rc-2 (LastChangedRevision: 6924, LastChangedDate: 2010-05-27 15:56:51 -0500 (Thu, 27 May 2010))\n====================================\n- Fixed copy-prepared-css command in build.xml to prepare for rc-2 release\n- Adjusted welcome screen URL to go to a non-release specific confluence page\n- [#MODX-2000] Fixed FC rule to apply to template fields by overriding in controller\n- [#MODX-2000] Add ability to specify a template in REQUEST or alter via plugin in resource/create controller\n- [#MODX-2004] Allow settings to be duplicated when duplicating a context\n- Added missing OnUserBeforeRemove event\n- [#MODX-1797] Fix bug with publishedby field getting updated unintentionally\n- [#MODX-1919], [#XPDO-52] Update xPDO to revision 425 for fix to xPDOManager::createObjectContainer()\n- [#MODX-1918], [#MODX-1919] Improve error reporting in database setup steps\n- Made default click behavior for Files in file tree be to edit\n- [#MODX-1995] Fixed issues regarding sending password via email with new users\n- [#MODX-1549] Preserve file tree state\n- [#MODX-1810] Gender now saves correctly in user panel\n- [#MODX-1635] Redirect to Users grid after creating a new user\n- Fixed bug with import properties\n- [#MODX-1971] Allow ./- in Context key names, but not as first character\n- [#MODX-1997] Added ability to duplicate and set inactive/active Form Customization Rules, batch actions to Rule grid\n- Cleaned up profile editing page\n- Cleaned up style for headers on welcome page\n- Reworked System Info page, cleaned up styling, display, info\n- Added batch actions to Users grid\n- Fixed bugs with removing directories in file tree\n- [#MODX-1996] Fixed missing create/update settings windows\n- Allow for separate paths on derivative resource types based on a [classkey]_delegate_path setting that points to their controllers, added checks to prevent path mapping\n- Prevent deferred render on left nav trees, to prevent loading errors for js hooks\n- Fixed bugs with MODx.grid.encodeModified/encode, plugin event saving\n- Added loadCreateMenus JS event to modx-resource-tree modext widget\n- Refactored js lang loading to allow for dynamic modification of strings\n- [#MODX-1993] Moved config.inc.tpl to core/docs to prevent confusion\n- Added description below TV rows in Resource edit\n- [#MODX-1853] Fixed issue where reload button was above MODx.Browser in TV pane\n- Switched Quick Create/Update Resource description field to more-used introtext field\n- [#MODX-1992] Fixed error in modSnippet preventing multiple executions per request\n- [#MODX-1983] Clarified package uninstall option message\n- [#MODX-1982] Fixed broken cancel button on Package View page\n- [#MODX-1989] Fixed incorrect var reference in getfiles processor\n- Added extra pagination to dropdowns in mgr that might have large #s of records to add usability for large sites\n- Fixed all Elements including Template Variables to properly respect modAccessCategory ACLs.\n- Allow base-level Element Category ACL assignments\n- Fixed some issues with Settings grid and lexicons, key not being displayed, etc\n- [#MODX-1940] Resized lexicon grid toolbar to fit better in smaller resolutions;\n- [#MODX-1950] Adjusted permissions to allow proper listing of Elements; checks 'list' policy on Element now rather than view_[element]\n- [#MODX-1975] Added warning messages for PHP 5.2.0 and 5.1.6 versions in setup asking that users upgrade to 5.3.0+; will still allow installs, however, if the user has those versions\n- [#MODX-1967] Added warning to setup for people who are using PHP 5.3.0+ and dont have date.timezone set\n- Added proper permission checks to Elements/Categories across processors/controllers\n- Added UX for managing Element Category access for User Groups\n- Add modAccessCategory to allow context-specific security policies on modCategory as well as any modElement via the related modCategory; includes policy inheritance to sub-categories\n- Add modCategoryClosure table class to allow for easy recursive queries on modCategory\n- Fixed bug caused by JS/CSS optimizations that would break left nav when too many resources were loaded\n- Fixed bug where access contexts for admin user were being duplicated on upgrades\n- Added extra options to attaching with modPhpMailer; fixed bug in phpmailer that caused E_DEPRECATED errors\n- [#MODX-1912] Added manager logging to file/directory actions\n- [#MODX-1912] Added file/directory specific permissions to allow more fine-grained security on using the file manager\n- [#MODX-1972] Added OnTVInputRenderList, OnTVOutputRenderList, and OnTVOutputRenderPropertiesList System Events to allow you to return a path to specify where to look for custom TV files\n- Allow separate caching directories for smarty when using different manager themes\n- [#MODX-1951] Ensure smarty cache is cleared on site cache clearing and settings\n- Ensure admin ACLs are set on new installs\n- Added check to modResource::stripAlias to make sure modX object is a modX instance\n- Added basic template and default home resource to new installs\n- Added load-only and load,list and view policies to build, adjusted setup to handle admin/resource policies with different IDs\n- Moved setup's global new/upgrade install scripts to separate files\n- MODExt adjustments; main layout now in central viewport so can handle browser resizing, refactored settings grid editing code, IE/FF/Chrome fixes\n- [#MODX-1970] Add scheme property to Link Tags to allow canonical, https, or any URL generation scheme from modX::makeUrl()\n- Fixed bug where core namespace was not in build\n- Update xPDO to revision 424 for fixes related to PDOException reporting\n- Ensure packages are unpacked after downloading\n- Fixed bug with removing a plugin\n- Added System Setting, 'cache_noncore_lexicon_topics', which can be used to disable caching on noncore lexicon topics, which is useful for 3PC development.\n- Deprecated modPackageBuilder::buildLexicon\n- Completely refactored the Lexicon system to now do file-based Lexicon Entries only. DB entries are only for overrides. This allows for proper overriding of\ncore lexicon entries, caches faster, and allows for much easier 3PC development.\n- [#MODX-1783] Fixed unnecessary scrollbar bug by removing unnecessary margin on body/html tags\n- Slight spacing tweaks to main layout to make layout feel more open\n- [#MODX-1806] Improvements to messages section\n- [#MODX-1913] Fixed incorrect wording on setup complete page\n- Tweaked launching of layout panel to add consistency across browsers\n- [#MODX-1835] Fixed error on Windows platforms when an extension_packages path contains a colon (:)\n- Added ORM editing formpanel object for editing v/p editing pairs, used now on modUser remote data form\n- Added panel for viewing remote data on a user\n- Added 'lexicon' field to modAccessPolicy to enable translations of descriptions of Permissions\n- Added extended field to modUserProfile to handle a majority of basic extended user profile storage/retrieval needs\n- Added 'lexicon' field to Element properties to enable automatic translating of property descriptions and option names\n- Fixed parent/context_key reference issue when creating resource from context tree node\n- Tweaks to index.css for default mgr theme to correct styling issues in webkit browsers due to ExtJS upgrade\n- Fixed deprecated references to removed images in default mgr template css that was causing 404s\n- [#MODX-1911] Allow for drag/drop reorganizing of categories in the Element tree\n- [#MODX-1892] Various fixes to TV-Template relationship grids\n- [#MODX-1895] Added sanity check for windows systems with file names in file browser\n- [#MODX-1908] Corrected logic flaw in modManagerResponse that prevented smarty templatePath from being set for CMPs\n- Optimized loading for System Settings grid\n- Updated ExtJS to 3.2.1\n- Add remote_key and remote_data to modUser\n- [#MODX-1898] Fix static calls to modX::fromJSON() and modX::toJSON() instance methods (xPDO updated to revision 421)\n- Pushed File tree nodes' context menus to JS layer, added Upload Files button to tree toolbar\n- Pushed Element tree nodes' context menus to JS layer, similar to Resource Tree optimizations\n- [#MODX-1897] Fix Date TemplateVar web output render error in PHP 5.3 due to use of ereg()\n- Fixed bug with Quick Update caused by new resource tree js changes\n- [#MODX-1848] Allowed parent selector to select contexts as the parent in Resource page\n- Pushed Resource tree nodes' context menus to the JS layer, massively decreasing the size of the JSON tree sent in the getNodes processor, vast speeding up tree functionality\n- Made publish/unpublish/delete/undelete actions on the tree only change the class of the node, rather than refreshing the node, speeding up workflow\n- Pushed modX::getService to xPDO layer\n- [#MODX-1873] Ensure setup redirects use full URL in header\n- [#MODX-1887] Adjust default widths for main layout to render panels more consistently\n- Optimized modX::getChunk() and modX::runSnippet() by caching instances within a request to modX::$sourceCache\n- Modified modX::setDebug(true) to set error_reporting(-1)\n- Optimized modLexicon::loadCache\n- [#MODX-1824] Fixed bug where duplicate wasnt fully duping resources\n- Moved Resource's duplicate method into the model, via modResource::duplicate\n- [#MODX-1868] tree_root_id now accepts a comma-delimited list of Resource IDs to restrict by. Works across contexts as well.\n- [#MODX-1871] Fixed bug with delimiter TV output render\n- Dropped unnecessary ID field on modEvent table and made `name` column PK\n- Refactored modX::invokeEvent and modX::getEventMap to take advantage of new plugin event changes\n- Adjusted the modPluginEvent model to reference the event name rather than id\n- Added new model-based System Events to work more effectively in any context\n- Removed deprecated system events\n- Added tree_root_id setting that allows you to specify the start parent ID of the left Resource tree\n- Fixed bug where User Settings could not be removed\n- Enabled ability to set absolute path and placeholders for filemanager_path and rb_base_dir\n- [#MODX-1791] modPackageBuilder::createPackage now forces lowercase package name to be more compatible across environments\n- Sanity checks to prevent user from accidentally removing admin/resource access policies\n- [#MODX-1860] Fixed bug where new password was being hidden too fast when changing user password\n- Added proxy support to modRestCurlClient for Package Management\n- Added a couple refactorings to modRestSockClient to prevent possible errors\n- Consolidated user group create system events into one event, OnUserGroupCreate\n- Fixed some various plugin event calls\n- Fixed Plugin Event code to restrict groupname to a UI filter only, not in event caching; adjusted UI grid to support groupname in display\n- Refactored file handling processors to use modFileHandler class with modFile and modDirectory derivative classes to abstract file system processing to abstract for multiple environments\n- [#MODX-1789] Added extra checks in Package Management to make sure that the correct directories are created before using it. Will now prevent usage of PM if those directories do not exist or are not writable.\n- [#MODX-1789] Added code to attempt to create core/components and assets/components after install. If fails, displays a notice to user to manually create them themselves to allow Package Management to work properly.\n- [#MODX-1839] Fixed grammatical error in forgot login link on login page\n- [#MODX-1846] Fixed invalid markup for username in top right\n- [#MODX-1854] Fixed invalid references to cultureKey that broke cultureKey setting effectiveness\n- [#MODX-1785] Fixed invalid password variable reference in invoke notfound event in login processor\n- [#MODX-1784] Fixed invalid event call on user update, as well as added event invoking into updatefromgrid processor\n- [#MODX-1836] Set default context_key in modResource objects to 'web'\n- Fixed bug with system info page and active users that would cause error in error log\n- [#MODX-1788] File tree now respects filemanager_path setting. Also cleaned up file browsing processors.\n- Upgraded ExtJS to version 3.2\n- Updated version to 2.0.0-rc-2 for svn development and issue tracking\n- [#MODX-1778] Fixed error that shows up if E_NOTICE set to true in setup/ index due to servers not posting a HTTPS server global", "MODX Revolution 2.0.0-rc-1 (LastChangedRevision: 6614, LastChangedDate: 2010-03-22 16:41:04 -0500 (Mon, 22 Mar 2010))\n====================================\n- Prepared for rc1 release\n- Fixed CSS compression copying in build.xml\n- Fixed regClient*() functions to work again on cacheable scripts\n- Move element source and include cache files outside of context cache directories since they should be cleared only when elements are updated\n- Remove eval() from modScript and re-enable remote debugging of modScript instances by caching function as include in addition to source cache\n- [#MODX-1759] Ensure manager log fires on top menu deletion\n- [#MODX-1772] Ensure array of IDs is passed to OnBeforeEmptyTrash and OnEmptyTrash plugin events\n- Added a welcome screen to show on first login to manager\n- [#MODX-1738] Fixed issue with default value on radio TVs\n- [#MODX-1741] Fixing inconsistent widths for radio options by making them list vertically rather than horizontally\n- [#MODX-1769] Lexicon grid search now searches name and value\n- [#MODX-877] Updated confusing text on TV access permissions tab\n- [#MODX-1766] Fixed PHP_SAPI issue to properly work by setting a default value on setup to provide a default http_host value to properly populate the site_url\n- Fixed bug in setup that didn't catch processors_path in prior configs\n- [#MODX-1759] Fixed bugs with manager log not storing correct PK values, or displaying missing keys in grid\n- [#MODX-1766] Fixed config.inc.tpl to work with non-httpd SAPI's\n- Added title/info for the Reports->System Info->Database page. This is return fixed the CSS styling issue as well.\n- Fixed CSS Styling on Recent Documents. 5px padding was removed.\n- Fixed bugs with modMail class and default attributes that prevented attributes from persisting after a reset()\n- Removing deprecated RTE handler code\n- [#MODX-1762] Increased file uploader window size for translations\n- Dont render unnecessary tabs in Resource TV panel if no TVs assigned to Template for that Resource\n- Sort Template Variables on the Template editing page by name\n- Ensure Element Properties that have HTML in them show markup instead of rendering the html in editing mode in mgr ui\n- [#MODX-1669] Redid File Uploader in Directory tree to be more cross-browser compatible\n- Cleaned up and enhanced login CSS\n- Standardizing and adding class constants to modRest* classes\n- Updated copyright data in lexicon entries\n- Fixes to build.xml, css compression command\n- Updated copyright dates\n- [#MODX-1750] Lots of procedural and reference fixes to Lexicon grid UI\n- Cleaned up presentation of modAction records in mgr\n- Added a fix to tree refreshParentNode; enhanced modUserGroup::getUsersIn()\n- Added saving mask to Element Property grid to fire when saving the property set\n- Removed deprecated file reference in login template\n- Added System Settings to toggle news/security feeds in welcome panel\n- Added System Setting to toggle on automatic checking of package updates in Package Management\n- [#MODX-1751] Fixed erroneous reference in friendly alias setting description\n- [#MODX-1752] Fixed bug where topmenu items without children didnt show even if they had an action\n- Some css tweaks to login page\n- Updated to xPDO 2.0.0 r419 to fix xPDOVehicle bug\n- Fixed bug with Download Output button in MODx.Console\n- Ensure forgot login activation email is HTML\n- Added Forgot Login link and form to manager, sends an activation email to specified email if user forgot login/password\n- Fixed SQL sorting algorithm for package versions, added helper methods for comparing package versions\n- Added $resource to properties passed to OnDocFormDelete in resource/delete processor\n- Updated to xPDO 2.0.0 r417 ([#XPDO-40] Fixed getCount to work when passing a criteria with a class alias set)\n- Enhanced striptags output filter to take a parameter of allowed tags\n- Make sure $paths and $options are passed to OnCacheUpdate\n- Added compression/concat references to login and browser tpls\n- Fixed build.local.xml and build.xml scripts\n- Added compress_css system setting for compressed CSS for releases, moved over modx-theme.css to templates css/ dir. Don't use compress_css without first running _build/build.local.xml Ant task.\n- Cleaned up leftover PHP4 function definitions, unescaped SQL code, added proper accessor methods for private vars, other old code\n- Fixed bug with modLexiconLanguage::clearCache\n- [#MODX-1738] Fixed issue with FC TV rules not working as expected on Resource Update\n- Fixed bug where plugin event properties were getting merged if more than one plugin was associated with the event\n- Added loading mask to editing panels to prevent accidental editing before data is loaded\n- Added sanity check for OnRichTextBrowserInit event processing\n- Added fix for RTE loading in Resource panel, should fix most RTE saving bugs\n- Added collapsibility to Document panel\n- Added 'concat_js' system setting that will concat all the common JS files into one single file\n- Adjusted lang.js.php to properly use ETag header to cache lang js\n- Added css rule to prevent hidden iframes from being shown\n- Fixed bug where Resource Groups were not editable on Create Resource\n- Added sanity check for packages with missing provider\n- Added \"Updates Available\" column to packages grid, auto-checks provider for updates\n- [#MODX-1732] Added duplicate language ability to language grid\n- [#MODX-1741] Fixed possible bug with radio/cb tv labels\n- [#MODX-1593] Fixed bug where User could not be added with no role in User Groups tree\n- [#MODX-1735] Properly URL encode link tags while still preserving = and &amp; in query string\n- [#MODX-1736] Fixed bug with assigning TVs to Resource Groups\n- [#MODX-1740] Added workaround for SQL code to properly hide TVs with FC rules\n- [#MODX-1738] Fixed bug with radiogroups and set TV default FC rule\n- Fixed some header issues, _FILES content type handling\n- [#MODX-1733] Fixed bug that was stripping tags from connector processing\n- Ensured that Static Resource filename change fires dirty status\n- Made sure Set to Default fires dirty status for Resource panel\n- Fixed possible width stretching bug in TV panel in Resource edit view\n- [#MODX-1543] Added \"Rename Category\" to category nodes in element subnodes in Element Tree\n- [#MODX-933] Can now drag/drop Elements into Categories in the Element Tree to assign them to Categories\n- [#MODX-1729] Fixed incorrect filter name to be more appropriate to function\n- [#MODX-1727] Added missing Empty Cache checkbox to derivative resource panels\n- [#MODX-1724] Fixed bug with output renders in TV panel not triggering panel dirty status\n- [#MODX-1730] Fixed bug with $scriptProperties and login processor\n- Some cleanups to MODExt flow and ID referencing\n- Changed all GPC references in processors to $scriptProperties, which is loaded at entrance points to processors with GPC vars, pushing input handling to the connector\n- [#MODX-1711] Fixed bug with strip output filter\n- Added ellipsis output filter\n- Fixed various event callings across JS implementation to properly modularize modext components\n- Added events to user's groups grid to ensure dirty firing\n- Added MODx.FormPanel::markDirty\n- Added in CSS tweaks to accommodate Opera 10.5\n- Fixed bug with users grid if access permissions tab is removed\n- Fixed deprecated method definitions in modConnector classes\n- Fixed text in language settings to more accurately reflect function\n- Added area filter to Settings grid\n- [#MODX-1721] Disabled unnecessary paging on System Events table\n- [#MODX-1726] Added sanity check to ensure TV input type is properly set\n- Fixed bug with action buttons and continue stay method\n- Added UI for managing website field in modUserProfile\n- Added website field to modUserProfile\n- Removed unnecessary and problematic editor dropdown in chunk editing screen\n- Sped up drag/drop of reordering in tree by now only framing moved nodes instead of refreshing\n- Added modRequest::getParameters() method for retrieving various GPC variables or arrays of variables; automatically strips MODx GET parameters as necessary\n- modRequest::__construct() now creates references to all GPC variables in modRequest::$parameters\n- Modified modX::makeUrl()/modContext::makeUrl() to accept query string parameters as an array or string\n- Added modX::toQueryString() static method to turn associative array into a valid query string\n- [#MODX-1709] Fixed issue with encoding of action button parameter\n- [#MODX-1554] Prevented uploading of files to files themselves in directory tree\n- [#MODX-1700] Fixed issue with text referencing setting in lexicon entry\n- Ensure tags in a Static Resource content are parsed before trying to load the source path\n- Fixed static/weblink update js\n- Removed unnecessary and redundant table prefix check later on in setup\n- Fixed css/js properties in TV tab to let RTEs auto-determine the height of their TD fields\n- Fixed missing permissions reference on resource controllers\n- Added OnHandleRequest to modManagerRequest::handleRequest\n- Properly hides UI elements for Resource buttons/pages if user doesnt have permissions\n- Refactored modResource::cleanAlias() to allow various options, including built-in and custom transliteration capabilities\n- [#MODX-717] Foreign characters (UTF8 data) needlessly removed from alias\n- Hide top menu items if there are no submenus and if the topmenu is not clickable\n- [#MODX-1690] Fixed text for confirmation dialog when removing an Element to include name and type of Element\n- [#MODX-1707] Added mail_charset and mail_encoding system settings to control charset and encoding in emails\n- [#MODX-1706] Ensure that text and qtip fields in Resource/Element trees have any tags stripped\n- [#MODX-1699] Fixed bug in Quick Edit TV where it would erase the caption and replace it with the name\n- [#MODX-1704] Fixed erroneous if statement in clear button hiding in error log panel\n- [#MODX-1675] Added fix for windows paths on Edit File panel\n- [#MODX-1681] Added checks for issue with importing lexicon in Webkit-based browsers\n- Cleanups to TV input widths\n- Removing core RTE; too much work, may take back up in a later version\n- [#MODX-1697] Added ability to edit images and links in RTE\n- Added more robust MODx.rte.Selection API\n- Added missing changes to modActions needed to load lexicon entries for RTE\n- [#MODX-1662] Fixed mismatch in menus widget field label\n- [#MODX-1687] Fixed bugs in template package browser due to changes in modx.view.js\n- Made resource panel be a fileUpload-able panel for plugins\n- [#MODX-1357] Added richtext_default system setting\n- [#MODX-1685] Added MODxEditor, a core Ext-based RTE to be the default RTE for Revolution\n- [#MODX-1674] Stabilized MODx.Browser to work with core RTE\n- - Added missing registry.db.modDbRegister* classes to setup\n- [#MODX-1642] Logging out doesn't unlock resources: added modUser::removeLocks() and modified modUser::endSession() to call this method\n- Added OnInitCulture event to core transport data.\n- [#MODX-1672] Refactor collation/connection processors in setup to be more stable\n- Updated xPDO to r414 for improvements in xPDOManager\n- modInstall::writeConfig() uses new_file_permissions if specified or umask() settings by default\n- Removed superfluous calls to xPDO/modX::setDebug() and xPDO/modX::setLogLevel() in modInstall\n- modInstall::getConnection() now uses utf8_general_ci for charset/collation by default\n- [#MODX-1691] Set Quick Create/Update windows to use anchor property rather than width to adjust for resizing\n- Added 'cultureKey' setting to enable easier language translation in contexts/fe/components\n- Fixes to styling for MODx.Browser window\n- Added 'relativeUrl' parameter to MODx.Browser file data\n- [#MODX-1674] Fixes and stabilization to MODx.Browser, specifically when used by RTEs\n- Changing default editor from TinyMCE to blank value\n- Fixed bug in setup where inplace setting was being forced to 1\n- Cleaned up most processors, fixed wrong permission references, standardized code\n- Fixed welcome panel to only show panels with permission to see\n- Fixed error log view page to restrict viewing and clearing by permission\n- Added descriptive information to Roles grid\n- Lots of permissions fixes, other bugfixes and sanity checks to Element processors/controllers\n- Added propertyset permissions\n- Cleanups to Resource controllers, processors, optimizing of security permission checks\n- Fixed various bugs with search page\n- Fixed bug with adding policies that prevented partial regexp matches in name\n- Fixed bugs when adding new policies or permissions that showed prior added perm/policy in form\n- Properly secured and refactored recently edited resources grid\n- [#MODX-1670] Adjusted permissions to allow restricted user to edit profile\n- [#MODX-1667] Removed unnecessary opacity CSS rule in menus\n- Fixed bug where page wasnt reloading on login in certain situations\n- Make rightlogin div longer to support longer translations\n- [#MODX-1653] Fixed issues with related objects, removal of aggregates, and other packaging bugs. Introduced xPDOTransport::UNINSTALL_OBJECT, which defaults to true. When off, it will prevent an object from being uninstalled.\n- Updated xPDO to r413\n- [#MODX-761] Fixed language issue in setup, now sets it correctly and loads proper lexicon for login screen\n- Ensure console window appears above other windows\n- [#MODX-1663] Added MODx.msg.status, which shows a fading status message on a successful save. This also solves the issue of user feedback.\n- Removed unnecessary field from recently-edited-resource grid on welcome screen\n- [#MODX-1660], [#MODX-1037] Revamped login screen to HTML/CSS, basic form processing to allow browsers to save password in their password management systems\n- Revamped UI in new setup options, cleared up text, simplified presented options\n- [#MODX-18] Allow editing of MODX_CONFIG_KEY in setup welcome view\n- [#MODX-18] Prompt user for MODX_CORE_PATH if not found at beginning of setup\n- [#MODX-760], [#MODX-1080], [#MODX-1528] Added setup option to set new_file_permissions and new_folder_permissions in welcome view\n- [#MODX-760], [#MODX-1528] Removed new_file_permissions and new_folder_permissions system settings from setup\n- [#MODX-760], [#MODX-1528] Updated xPDO 2.0 to revision 407: new file and folder permissions determined from umask()\n- [#MODX-878] Stay buttons now action-specific, done through Ext state rather than PHP\n- Redo logic order of modPackageBuilder::buildLexicon to ensure languages are packaged in before topics\n- [#MODX-1647] Added width specification to force width of screen to prevent scrolling off of RTE TVs\n- Cleaned up tvTitle Form Customization rule by moving code from JS to PHP\n- Fixed z-index issue for windows due to IE fix\n- [#MODX-732] Added z-index force to topmenu for IE, fixed rightlogin div on topbar for IE\n- [#MODX-1641] Optimized and cleaned code dealing with Form Customization TV visibility and default values\n- [#MODX-1658] Fixed bug where placing a menu item in a submenu would place it in top level\n- [#MODX-1624] Enabled changing of text field in menu items\n- [#MODX-1656], [#MODX-1654] Fixed CSS gap in install summary in setup\n- [#MODX-1655] Fixed hardcoded lexicon strings in setup\n- [#MODX-1621] Remove unnecessary context menu items from items in Resource Group Resources tree\n- [#MODX-1627] Fixed incorrect menu in resource group tree resources when newly dragged\n- [#MODX-1599] Added manager_date_format system setting for customizing date formats for the manager\n- [#MODX-1651] Increasing width of setup navbar buttons to accommodate translations\n- [#MODX-1649] Fixed bug where Quick Create didn't respect default_template setting\n- [#MODX-1650] Fixed bug with language specification in setup to properly set cookie for Windows machines, and set initial language properly\n- [#MODX-1626] Fixed bug where top menus could not have actions\n- [#MODX-1494] Fixed issue where some settings dont have descriptions, and cleaned up deprecated settings\n- [#MODX-1645] Fixed incorrect lexicon key for setting_site_start_err\n- [#MODX-1646] Fixed issue where download buttons were staying grayed out if there was an error message\n- [#MODX-1644] Added SMTP mail settings to default system settings to allow global SMTP usage for all modMail functions\n- [#MODX-1606] Fixed bug in modRestCurlClient class due to encoded ampersand\n- [#MODX-197] Refactored Action Buttons JS, added 'actionNew', 'actionContinue', and 'actionClose' events to MODx.FormPanel objects, ensured parent/context_key is persisted through add another resources\n- Added a couple sanity checks to modRestCurlClient\n- Added JS to disable install button when clicked in setup to prevent double-clicks\n- controllers/resources/create: Refactored template inheritance to occur before any delegate controller is called.\n- processors/resources/create: Moved OnBeforeDocFormSave event invocation until after POST vars are applied to $resource object.\n- processors/resources/create: Refactored common code to be executed before any delegate processor is called.\n- processors/resources/create: Refactored to respect add_children and new_document_in_root permissions.\n- Added various access_denied lexicons to the resource topic.\n- Added new_document_in_root permission to control access to creating Resources at the root level.\n- Updated to xPDO 2.0 revision 406.\n- [#MODX-1606] Added sanity checks and ID standardization to DOM nodes for Package Browser\n- Fixed possible bug with ta-toggle div in resource panel\n- [#MODX-1628] Fixed FC tvDefault rule by doing setting php-side\n- [#MODX-1636] Added ability to assign Role to User when adding them to a User Group from the User Groups tree\n- [#MODX-1634] Fixed bug with resource/resourcegroup/getlist processor that prevented showing of resource groups in new resource panels\n- [#MODX-1639] Fixed bug where resource panel JS didnt check for existence of possibly hidden access permissions grid\n- Fixed modUser::removeSessionContext() to call modUser::endSession() if no contexts are left\n- Fixed modUser::endSession() to destroy all SESSION data and the session cookie\n- Fixed bug in Plugin -> System Events tab caused by invalid function call in getlist processor\n- Fixed problems with various deprecated functions to increase compatibility with Evo and avoid performance issues:\n * modX::getDocuments() and modX::getDocument()\n * modX::getAllChildren()\n * modX::getActiveChildren()\n * modX::getDocumentChildren()\n * modX::getDocumentChildrenTVars()\n * modX::getParent()\n * modX::getPageInfo()\n * modX::getUserInfo()\n- Fixed modX::__construct() declaration to indicate it properly as a public method; added phpdoc comments.\n- Fixed modX::sanitize() declaration to indicate it properly as a static method.\n- Updated to xPDO 2.0 revision 405\n- [#MODX-1614] Fixed issue with cached pages going to unauthorized_page instead of error_page when user does not have load permission\n- [#MODX-411] Set system setting: emailsender to the admin email address during install\n- [#MODX-1556] Show class and id for deleted resources or elements in Manager Action Log\n- [#MODX-1552] Create New element Here shows for root elements but not those in categories\n- [#MODX-1625] Fixed bugs with menu tree preventing creating child nodes of new items, restyled menu and action icons\n- Added preventative to make sure packages are only downloaded once when in Package Browser\n- [#MODX-1623] Fixed package installation error: attempting to preserve files fails with error message\n- Updated to xPDO 2.0 revision 404\n- Setup upgrades no longer preserve existing data/files on install\n- Fixed issue with setup trying to write connector files regardless if files are already in place\n- Updated to xPDO 2.0 revision 403\n- Fixed bug where plugin properties were not being injected into the plugin event call\n- [#MODX-1617] Fixed bug with tvDefaultValue Form Customization Rule\n- [#MODX-1619] Added sanity check for modActionDom constraint check\n- [#MODX-1620] Fixed missing or incorrect lexicon entries across ui\n- [#MODX-1612] Fixed bug where Create Menu button was not working\n- [#MODX-1616] Renamed \"field\" to \"name\" in Form Customization rule windows\n- Removed any non-essential JS from the top menu items\n- Added additional check and error logging for processor_path option in modX::executeProcessor().\n- Added missing view_sysinfo permission to default Administrator policy\n- [#MODX-1595] Fixed bug regarding hiding top menu items with permissions\n- [#MODX-1596] Fixed bug related to creating a new top menu item\n- Fixed issues related to usergroup panels and anonymous usergroup editing\n- Fixed bug in template viewer for package browser that wasnt paginating right\n- Added modRestServer for generic REST request handling\n- Enable remote sorting and sorting by ID on Users grid\n- Fixed and enhanced search field on Users grid\n- Fixed bug with duplicating a context where only the first level would duplicate\n- Updated to xPDO 2.0 revision 396\n- Fixed bug where package version info wasnt being computed on download/scanlocal\n- Added check for locked status on resources, now shows locked status in tree, as well as who is editing\n- [#MODX-1592] Fixed bug with usergroup create by moving it to a window\n- [#MODX-1590] Fixed missing processors for ACL grids\n- [#MODX-1526] Added permissions resource_tree, element_tree, file_tree that restrict rendering/viewing of the left-side trees. Must be applied to access policies.\n- [#MODX-625] Adjusted text in config.inc.php writable warning message\n- [#MODX-1586] Fixed toolbar rendering bug in user settings due to hidden div, now using hideMode: offsets\n- Added search for user box in usergroup users grid\n- Changed User Group users grid to a non-local grid, now supports pagination and proper validation\n- Enhanced UI for editing User Group Context/ResourceGroup ACLs\n- [#MODX-1525] Added permissions field to modMenu to define policy permissions required to see Top Menu items\n- Fixed bug in Packages grid to properly show provider name\n- Added modRestResponse class, improved error handling for REST-based package management\n- Added verification for Providers, now check to make sure they can connect before being added or updated\n- Added Package View page to Package Management, allowing you to view more info about a package, view prior installed versions, and remove older package versions\n- Fixed typo in setup script for PM changes\n- Added version_major, version_minor, version_patch, release, and release_index fields to modTransportPackage tables to assist sorting and organization\n- Fixed bug in transport schema\n- [#MODX-1571] Fixed xtype in automatic_alias setting\n- [#MODX-1572] Fixed deprecated error in PHPMailer service\n- [#MODX-1512] Fixed bug with MODx.tree.Tree::refreshNode that caused a strange duplicate node error\n- Updated xPDO to revision 392 to get new nested condition features\n- [#MODX-1515] Fixed date picker CSS\n- [#MODX-923] Added file path to config.inc.php configcheck message on welcome page\n- [#MODX-1579] Added code to prevent invalid characters from being used in admin username/password in setup\n- [#MODX-1575] Fixed bug with Resource Group getList processor\n- Updated to xPDO 2.0 revision 389\n- Added validation to modContext.key field; must be a valid PHP identifier without underscore characters\n- Modified modError::checkValidation() to call modError::addField() for each validation message\n- [#MODX-1562] Cleaned up Site Schedule grid to properly load baseParams during refresh and adjust pagination\n- Cleaned up processor code, plugin invoking, access permission checks in processors\n- [#MODX-1562] Fixed bug in Site Schedule data\n- Fixed OnDocUnpublished and OnDocPublished calls in processors to pass modResource reference\n- [#MODX-1564] Fixed bug causing combo values to get overridden if they were set before the combo store loaded\n- Move element and resource prerender plugin events to after js registering to allow for proper event execution order\n- [#MODX-986] Added \"Duplicate Context\" to Resource tree, as well as \"Remove Context\"\n- Fixed bug with default provider on package management UI\n- [#MODX-1540] Fixed last login display in Welcome page\n- [#MODX-1567] Enabled sorting in Reports -> System Info -> Recently Edited Documents\n- [#MODX-1522] Restricted user editing to just the save_user permission\n- Added a \"reload\" button to the error log\n- Fixed Active Resources on Reports - System Info\n- Fixed database version query in Reports - System Info\n- [#MODX-1560] Added a button to truncate manager log\n- Added new browsing view for Templates in Package Management; thumbnail-based browsing.\n- [#MODX-1534] Revamped file edit page to match other page structures\n- [#MODX-1542] Added missing undelete permission to basic Resource policy\n- [#MODX-1539] Added view_user permission to solve dropdown combo users bug that needed \"edit_user\"; view is more applicable there\n- [#MODX-1553] Show current permissions in chmod window\n- [#MODX-1539] Fixed a few bugs with the manager log page\n- [#MODX-1530] Fixed permission reference in resource create/data\n- [#MODX-1532] Fixed bug in permissions reference when trying to remove element from property set\n- Fixed bug with login page and new controllers location\n- Enhanced provider home page to allow links for newest/most downloaded packages\n- Added sorting to Access Policy grid, cleaned up getList processors across site\n- Fixed Manager Log page to properly display content, log the right class key, and now display the name of the object edited\n- Enhanced Property Sets page to now allow you to edit specific implementations of Property Sets per element, as well as the default set\n- Added \"disabled\" checkbox to Quick Update Plugin\n- Fixed bug in modManagerResponse dealing with CMPs and templating paths\n- Moved controllers/* files to controllers/default/ to allow for custom manager templating\n- Fixed bugs with Property Sets not showing correctly in dropdowns\n- Updated xPDO to revision 385 to fix cache_db functionality broken by PHP 5 only changes\n- [#MODX-1514] Added css for pointer cursor to top menus\n- [#MODX-1513] Added check for SimpleXML to installer\n- Add sanity check to make sure languages arent erased on package uninstall\n- Removed confirm dialog for remove action on Access Permissions grid\n- Fixed panel layout for Access Policies, User Group editing\n- Fixed E_STRICT warning on modX::getCacheManager() [method signature did not match xPDO::getCacheManager()]", "MODX Revolution 2.0.0-beta-5 (LastChangedRevision: 6224, LastChangedDate: 2009-12-15 10:03:36 -0700 (Tue, 15 Dec 2009))\n====================================\n- Fixed bug where Set to Default on Resource TV panel was hidden unless you clicked Reload\n- Fixed some bugs with Property Sets editing\n- Fixed bug where download wasnt working for package management due to missing provider\n- Fixed bug where quick create Static Resource wasnt loading MODx.Browser\n- [#MODX-1496] Fixed issue with scrolling context menus not working on local grids\n- Fixed styling in welcome panel\n- Shrinking top menu a bit to fit in smaller window resolutions\n- Fixed invalid method reference in modInstallTest derivative classes\n- Fixed styling and JS in TV pane\n- Fixed error with charset reference in setup/\n- Clear Search in Package Browser when clicking on a Tag\n- Added Search bar to Package Browser, now can search entire repository\n- Fixed height of Package Browser to not go too far down screen\n- Fixed modRestSockClient to properly strip HTTP headers and return only XML\n- Added modStaticResource methods: getSourceFile() and getSourceFileSize()\n- Fixed bug in setup/ script with new transport package fields\n- Fixed modCacheManager to not cache reg* calls that will cause breakage on similar calls to reg* method\n- Added 'package_name' and 'metadata' fields to modTransportPackage for future development\n- Fixed styling commits; also fixed bug on Package Management when not selecting default provider\n- Added help buttons to Resource pages\n- Moved TV categories in Resource edit page to tabpanel, also cleaned up button styling\n- Fixed table styling. This is temporary until all tables are ported to ext grids. This affects welcome pane, system info, and online users.\n- Fixed bug where package browser would close on ESC key\n- [#MODX-1489] Allow spaces in Category names\n- [#MODX-1497] Fixed username not being sent in new user email\n- Fixed NOT NULL error in modManagerLog\n- Revamped Package Management UI, changed Provider hooks to REST-based, massively improved downloading UI\n- Fixed styling on the search page.\n- Fixed styling on the actions page.\n- Fixed styling on the manager logs page.\n- Fixed triggerfields in windows in Safari\n- Changed the text-size and and top margin of the Main Navbar Submenu span for more readability.\n- [#MODX-1426] Added connect check to assist with mysql_get_server_info in setup\n- Few style changes: Changed Button style text color to black - Previously it appeared that buttons were disabled. Changed Text color inside of combo boxes to black - As before it looked like the element was disabled.\n- Modified the date fields to show a drop-down box rather than the date image. Changed the text-size and spacing of the Main Navbar to 12px.\n- Fixed styling of the welcome panels.\n- Fixed some issues with OnDocFormSave, plus standardized how to render fields/html to update forms\n- Fixed bug with default values, @ bindings and other things on checkbox/radio TVs\n- Prevent tree from expanding too much on quick create, cleaned up js\n- Assigned user id/username to [[+modx.user.id]] and [[+modx.user.username]] for easier access\n- Cleaned up last PHP4 remnants to PHP5-only\n- [#MODX-1483] Fixed bug with TV saving in resource create processors\n- Recompiled MODx.Console to use Ext.Direct, now should be a bit more stable. To end a MODx.Console session, pass 'COMPLETED' to the registry.\n- Resizing the left tree now properly resizes content in the right panel and is stateful\n- Added resizability to leftbar tree\n- Removed no-longer-necessary js file references in resource controllers\n- Consolidated filetree css/js into main css/js files\n- Fixed logic error that caused removing setup directory to fail\n- Combined some common JS files, cleaned up login page css, other optimizations\n- Consolidated filetree extension CSS, removed unnecessary filetree files\n- Consolidated CSS files in templates/default/css to one single file to reduce load times from @imports\n- Added rowactions to package grid\n- Improved code in @DIRECTORY binding to be more efficient and take advantage of DirectoryIterator\n- [#MODX-1478] Fixed @SELECT binding\n- [#MODX-1474] Fixed bug with multiple list-boxes\n- [#MODX-1476] Fixed bug with TV default values with non-inherit tvs, also bug with radios/checkboxes and set to default\n- [#MODX-1479] Fixed bug with duplicate DOM ids in User Group tree\n- [#MODX-1480] Fixed bug with wrong permission reference in property set remove processor\n- Added emptyText to local and property grids\n- [#MODX-1477] Added emptyText config param with default 'No data to display' message to empty MODx grids\n- documentObject was not getting set from cached Resources.\n- Added inline help that loads official MODx documentation in a window\n- [#MODX-900] Fixed erroneous text on site_status setting description\n- Added (Inherited Value) flag to TVs that are inheriting their value\n- Added category titles to TV editing panel\n- [#MODX-1354], [#MODX-1475] Fixed @INHERIT and other bindings in TV inputs\n- Fixed bugs with dirty status not firing for certain TV input types\n- Fixed CSS for login page\n- Fixed issue where default connection charset was not persisting in setup for upgrades\n- CSS tweak to get windows working properly\n- Major styling updates (thanks lossendae!)\n- [#MODX-1473] Fixed bug with modUser and modUserProfile PK's getting mixed, causing errors if PKs for each object were different\n- Added city field to user UI\n- Optimizations to Resource panel\n- [#MODX-1466] Made \"back\" from Access Policy edit redirect to Access Controls page, made Access Controls tabs stateful\n- [#MODX-1471] Added scrollOffset: 0 to grids to hide empty space on right side\n- [#MODX-1469] Fixed dir handling in setup\n- [#MODX-1388] Updated documentation for modX.getTree and modX.getChildIds\n- [#MODX-1318] Prevent ordering of elements in dragdrop since order defaults to alphanumeric\n- Made charset in setup/ a dropdown of available charsets\n- Fixed collation grabbing for setup/\n- [#MODX-1090] Added 'Rename File' window to directory tree\n- Vast improvements to setup, including removing of mootools, using ExtCore now, simplified UI workflow to remove unnecessary AJAX calls, added in database creation checking, collation specification, etc\n- Fixed bug with modPackageBuilder that would ignore the specified path for a Namespace\n- [#MODX-1207] Changed modSession.id column to varchar(40) to support session.hash_function=1 with session.hash_bytes_per_char=4.\n- Simplified and optimized session handling, removing older PHP workarounds and adjusting preset system settings.\n- Make sure non-static Resources with binary content types get processed and output.\n- [#MODX-1450] Added paging to Template combobox to allow for large numbers of templates\n- [#MODX-1443] Tree sorting now works for modMenus\n- Removed deprecated system settings from build\n- [#MODX-1448] Fixed issue with container checkbox not persisting\n- [#MODX-1426] Fixed issue with MySQL checks on non-standard\n- [#MODX-1437] Fixed duplicate policy\n- Fixed some issues with Form Customization\n- Added 'address' field to modUserProfile\n- Added ability to edit the (anonymous) user group from the user group editing panels\n- Fixed typo in usergroup get processor\n- [#MODX-1018] Fixed bug with having to click the Clear Filter button in a settings grid twice\n- [#MODX-1380] Fixed bug with expanding node when quick creating a resource in it\n- [#MODX-1326] Fixed the access denied logout form, added styling\n- [#MODX-1423] Fixed error with duplicating a template\n- [#MODX-1409], [#MODX-919] Fixed issue where tag symbols were being stripped in Elements and breaking filtering and nested tag functionality\n- [#MODX-1347] Fixed user validation for username missing error\n- Extrapolated RTE logic to make it generic\n- Added OnRichTextBrowserInit to allow for 3rd Party RTEs to hook into MODx.Browser\n- Added system setting \"allow_multiple_users_per_email\" to allow users to have a single email shared across users. Defaults to true.\n- [#MODX-972] Fixed bug when property description was changed, grid wasnt updating\n- [#MODX-1390] Fixed docs for $modx->sendUnauthorizedPage();\n- [#MODX-895] Fixed possible rendering issue with error log scroll bar\n- Optimized setup pre-install checks, now checks both mysql client and server versions\n- [#MODX-1404] Fixed mysql version checks to only show a warning if the client/server is incorrectly setup to where PHP cannot determine the versions.\n- Package Management now restricts downloading/updating Extras to their supported MODx versions (ie, you can't download packages that support only beta-3 if you have beta-4 or beta-2)\n- [#MODX-1310] Fixed expand/collapse toolbar items in trees\n- [#MODX-1361] Make sure cache (including Smarty files) is cleared after install\n- [#MODX-1372],[#MODX-1376] Marked deprecated functions as so in phpdoc comments\n- [#MODX-1378] Fixed bug with adding a None role to a user group in the User -> Access Permissions tab\n- [#MODX-1375] Fixed documentation for modX.getRequest\n- [#MODX-1374] Fixed documentation for modX.getRegisteredClientScripts\n- [#MODX-1370] Fixed quick create to set modResource type to modDocument properly\n- [#MODX-1373] getLoginUserName and getLoginUserId now return boolean false if no user is logged in\n- [#MODX-1369] Fixed validation errors and possible loophole in error processing for user processor flow\n- Fixed column alignment with radio/checkbox TV inputs\n- [#MODX-1350] Fixed issue where reset to default wasnt working with radio TV inputs\n- [#MODX-1360] Fixed issue where publishedon was being reset in quick update\n- Sanity fixes to misc processors\n- Added access modifiers to methods in modElement\n- Moved name character sanity checks for Elements to element class.\n- Cleaned up element processors, added missing permission checks, filled out plugin event calls\n- [#MODX-1355] Fixed erroneous label for quick create resource on Contexts\n- [#MODX-1352] Remove stay-buttons from user update screen\n- [#MODX-1349] onDirty now fires on triggerfield-based TVs\n- Cleanups to getList processors, bugfixes for grids\n- [#MODX-1317] Fixed erroneous label for quick create resource; should be Document\n- [#MODX-1316] Added menu title to quick create/update resource\n- Fixed issues with User grid\n- [#MODX-1325] Fixed console's download to file functionality\n- [#MODX-1327], [#MODX-1340] Fixed issue with generation of new password\n- Fixed locking\n- Lots of PHP5-only optimizations", "MODX Revolution 2.0.0-beta-4 (LastChangedRevision: 5880, LastChangedDate: 2009-10-19 09:04:47 -0500 (Mon, 19 Oct 2009))\n====================================\n- If memory limit is lower than 24M, force to 128M if possible\n- Fixing setup text for memory limit checks.\n- [#MODX-1080] Make sure traditional distribution doesnt need base directory writability\n- Added modInstallTestSvn class for handling SVN-specific setup tests\n- Fix to setup contexts controller to read existing paths on upgrade.\n- setup/ memory_limit checks now only need to be 24M for setup/ to run.\n- Updated to xPDO 1.0 revision 363 to fix \"Error saving changes to parent object fk field action\" messages being logged during install.\n- Fixed issues with category remove dialog and lexicon topic grid\n- [#MODX-1294] Fixed possible obscure problem when using Preview after changing the alias in a Resource\n- [#MODX-1278] Fixed issues with checkbox TVs and default values, fixed the 'set to default' button for complex inputs\n- [#MODX-1280] Fixed issues with the user create processor\n- Added OnBeforeUserActivate, OnUserActivate events\n- Added 'active' boolean field to modUser. Defaults to 1.\n- Added OnCreateUser, OnDeleteUser, OnUpdateUser events\n- [#MODX-1170] Fixed issues with Export Topic\n- [#MODX-912] Fixed isinrole/ismember output filter\n- [#MODX-677] Made capitalization consistent on Resource edit/create screen\n- [#MODX-1251] Fixed issue with server offset displaying incorrectly\n- [#MODX-896] Fixed issue with server_offset setting description\n- [#MODX-928] Fixed issue where parent resource wasnt refreshing properly\n- [#MODX-777] Made consistent the checkDirty behaviour of save buttons across manager\n- [#MODX-938] Added check to build to check if core+core.transport.zip were removed before build starts.\n- [#MODX-629] Added missing automatic_alias setting to build\n- [#MODX-790] Fixed issue where couldnt browse back to root directory with MODx.Browser\n- [#MODX-902] Fixed empty warning message for removing category\n- Fixed bug with removing categories\n- Fixed issue where couldn't drag a resource onto a resource with no children\n- [#MODX-1130] Fixed issue with parent triggerfield; also redid how tree hrefs load so that clicking on a node in the tree to load url can be disabled\n- [#MODX-1133] Fixed issues with hotkey behavior\n- [#MODX-1230] Fixed issue where drag Resource to symlink/weblink content field would add tags as well\n- [#MODX-1273] Added OnLoadWebPageCache event invocation to modRequest->getResource().\n- [#MODX-1273] Fixed events in User update/create form\n- Enabled compression of manager JS scripts by changing the Setting \"compress_js\" to true.\n- Upgraded ExtJS to ExtJS 3.0.2\n- [#MODX-1270] OnManagerCreateGroup and OnWebCreateGroup events now fire\n- [#MODX-1237] Fixed warning in modParser with regards to uninitialized variable\n- [#MODX-979] Added password_generated_length (the length of the auto-generated password) and password_min_length (the minimum length for a password)\n- Cleaned up usergroup processors\n- Added sanity checks to usergroup processors\n- Prevent possible issue on usergroup update that would wipe related objects\n- Prevent possible issue that would allow user to remove Administrator group\n- Removed some legacy todo statements\n- Moved Element category reset on modCategory object remove to modCategory class\n- Cleaned up modResourceGroup, modTemplate helper methods\n- Added modUser::joinGroup(group,(optional)role) and modUser::leaveGroup(group) for easier development\n- Optimized getrecentlyeditedresources processor\n- Make sure config.js.php outputs proper headers\n- Commented out Content-Length headers on lang.js.php, for some reason was slowing down servers\n- [#MODX-1256] Fixed issue with Resource tree not being visible in Resource Groups page\n- Fixed issues with Import HTML/Resources pages; properly convert to MODExt\n- [#MODX-1202] Fixed issue where Element name was missing in Duplicate window\n- [#MODX-1233] Fixed bug where categories could only be renamed once before needing to reload page\n- [#MODX-1248] Fix bug that could wipe TV values if tab wasnt loaded\n- [#MODX-1241] Fixed Preview button on update panels\n- Prettying up of TV fields\n- Now display SVN revision number with version in top left of mgr header\n- Fixed issues with TVs setting values incorrectly\n- Added \"Set to Default\" button on TVs that will reset the TV's value to it's default value. TV Resource values can now be set to blank as a valid value.\n- [#MODX-924] Fixed errors in various system setting descriptions\n- [#MODX-935] Tooltips in Resource tree now do not show if no description or longtitle is set\n- [#MODX-1120] Now shows TV names in tag form below the caption in the TV editing panel in Resource editing\n- Fixes to plugin event calls in controllers\n- Fixes to filetree to enable in Ext3\n- [#MODX-1112] Fixed issue where checkboxes in grids werent firing dirty statuses\n- [#MODX-1229] Fixed issue where default hidemenu setting in Create Static Resource was setting incorrectly to true\n- Added some extra variables for RTE firing; also made sure MODx.loadRTE fires on new resource creation. Fixes [#TINYMCE-9], [#TINYMCE-8]\n- [#MODX-523] Fixed copy issue in console by providing \"Download to File\" link\n- [#MODX-649] Fixed issue where comboboxes were not loading proper displayValue when first rendered\n- Added category combobox to quick update/create windows\n- [#MODX-1019] Added missing site_unavailable_page System Setting.\n- [#MODX-1226] Removed modResource->checkChildren() method; isfolder should not be set based on presence/absence of children.\n- [#MODX-1213] Fixed issues with WebLink creation and loading\n- [#MODX-1178] Fixed issue where checkbox TVs were unable to be set to false; properly rendered values into a hidden field\n- [#MODX-1204] Implemented $matchAll for modUser::isMember, that allows exclusive and inclusive group membership checks\n- [#MODX-1203] Now preserves state of open tabs in left bar\n- Added \"Form Customization\" page, which emulates Evolution ManagerManager functionality and integrates it into the core\n- Revamped modMenu DB structure to allow for more proper dynamic menus; 3PCs will need to now refer to the Components menu as 'components', as the \"id\" field has been dropped and \"text\" is now the PK\n- Fixed DOM issue with Profile page\n- Improved core transport build script, lowered build times\n- Fixed issue where hiding the alias field would cause it to be erased\n- [#MODX-1169] Fixed issue where unchecking Container on a Resource that had children would hide them from the tree\n- [#MODX-1125] Fixed issue where Properties were being lost on new Elements\n- Fixed some dirty field problems in Element/Resource forms\n- [#MODX-1167] Improved isFolder checkbox tooltip\n- [#MODX-929] Changed default click functionality in Tree menu to edit Resources, unless does not have permission to, will then go to View\n- Fixed navbar structure on main menu to properly handle infinitely deep nested menus. Needs help from a CSS guru on the CSS end.\n- [#MODX-1161] Fixed bug with height argument on modX::getParentIds\n- Documentation updates to modResource class\n- [#MODX-1189] Fixed issue with TV values not setting properly with modTemplateVar->setValue\n- Added modResource->getTVValue, which gets the value of a specified TV for the Resource\n- [#MODX-1177] Adjusted Lexicon Management text to properly represent functionality\n- Added more metadata to Lexicon Topic exports\n- [#MODX-1191] Fixed issue where Namespace combo was conflicting with other DOM IDs in Lexicon Management\n- Changed Accordion to Tabs in left menu\n- In all Resource panels, Moved Page Settings back to right side, moved Template to top, moved Published to top right\n- [#MODX-1173] Added modResource->hasChildren() function. Returns # of children for the Resource.\n- [#MODX-689] Fixed error when using @SELECT binding with Template Variable Input Option values.\n- Fixed issues with modMenu creation/editing\n- [#MODX-1132] Various fixes to the user editing page\n- [#MODX-1123] Fixed bug where properties were not saving on new elements\n- [#MODX-683] Changed title for 1st tab on Resource edit screen\n- [#MODX-1118] Tweaked MODx.combo.ComboBox and other store references to possibly fix local store bug\n- Fixed issue with Sort By dropdown in the Resource Tree\n- Fixed issues with User Group update page\n- Added modAccessPermission class to properly handle access policy permissions\n- Adjusted UI to handle model change\n- Added logic in setup install to clear sessions table after install to prevent access permission changing problems (and is a good general practice anyway); users will have to re-login after setup/ is run.\n- Cleaned up access policy grid\n- Default sort roles by authority\n- Removed no-longer needed Security pages; now done in Access Control and User Group edit screens\n- Started cleanup of Security system; changed 'Authority' listing on User Group page to a more correct \"Minimum Role\".\n- Added some IDs to resource edit page\n- [#MODX-1124] Took Templates off the list of attachable elements in Tools | Property Sets", "MODX Revolution 2.0.0-beta-3 (LastChangedRevision: 5593, LastChangedDate: 2009-07-30 11:14:17 -0500 (Thu, 30 Jul 2009))\n====================================\n- Fixed issue with scrollbars and height in tree context menus\n- [#MODX-963] Fixed issue with scrollbars and height in grid context menus\n- Fixed possible error in lang.js.php\n- [#MODX-982] Added param stringLiterals to directory/getList processor\n- [#MODX-978] Updated PHPMailer to 2.0.4\n- [#MODX-960] Fixed DOM issue with User Group creation/editing screen\n- Added ability to drag/drop files in file tree into fields\n- Fixed issue with file tree hiding files\n- [#MODX-960] Fixed erroneous header in Manage User Groups and Roles\n- [#MODX-965] Removed Disabled field from Package grid since it currently is unapplicable\n- [#MODX-964] Fixed issue with toolbar buttons in package download tree by removing unneeded buttons, fixing refresh button\n- [#MODX-966] Changed Package Management grid to be easier to read, removed unnecessary information\n- [#MODX-962] Fixed issues with User panel screen\n- Replace deprecated split() call in magpierss class with explode().", "MODX Revolution 2.0.0-beta-2 (LastChangedRevision: 5416, LastChangedDate: 2009-07-16 13:15:41 -0600 (Thu, 16 Jul 2009))\n====================================\n- [#MODX-1029] Fixed incorrect URL references in browser controller template\n- Updated version info for beta2 release\n- [#MODX-942] Made sure all get-based processors use REQUEST, not POST\n- [#MODX-937] Added 'Download Extras' button to package grid which loads modxcms.com provider\n- login processor does not return site_url in response by default.\n- modResponse->outputContent() allows programmatic options to configure max_parser_iterations.\n- Updated xPDO to revision 341: package uninstall preserves and restores file resolver data\n- Changed key shortcuts to always require ctrl+shift to prevent browser collisions\n- Added in field for description key in modMenu windows\n- [#MODX-931] Added isequal, isequalto, and notequalto as modifier aliases to default Output Filter\n- Fixed issues with pagination on settings grids\n- Fixed ENTER key issues on quick create/update windows\n- Added &language option to lexicon tags.\n- Added ability to load lexicon topics via tag: [[%key? &namespace=`mynamespace` &topic=`mytopic`]]\n- [#MODX-910] Fixed issues with gte/lte/gt/lt output filters\n- [#MODX-921] Added \"isempty\" as an alias of \"ifempty\" in output filters\n- [#MODX-920] Fixed wordwrap output filter\n- [#MODX-914] Added isnotempty and hide output filters\n- [#MODX-913] Added isloggedin and isnotloggedin to output filters\n- Upgraded ExtJS from 2.2 to 3.0\n- [#MODX-925] Fixed issue where name couldnt be changed on duplicate resource window with resources with children\n- [#MODX-911] Fixed dragability issue when assigning resources to resource groups\n- [#MODX-901] System Settings grid search now searches descriptions\n- Added 'afterLayout', 'loadKeyMap', and 'loadAccordion' events to MODx.Layout\n- Fixed bugs with File TV input renders\n- [#MODX-887] Properly standardized POST/REQUEST access methods for element processors\n- Fixed issues with user emails being sent in plaintext with no linebreaks; now HTML-based for the time being\n- Package Download tree now disables already downloaded packages.\n- [#MODX-885] Fixed missing break statement in cat output filter\n- [#MODX-844] Fixed ucfirst output filter, added ucwords output filter\n- [#MODX-869] Added missing descriptions for certain menu items\n- [#MODX-868] Fixed bug on settings grid where filter box was not firing on enter key\n- Fixed bug where hidemenu was not persisting in Quick Update Resource\n- Fixed bug with tree mask rendering before panel is rendered\n- [#MODX-747] Fixed issues with access grids update windows\n- [#MODX-803] Fixed DOM issues with TV mgr input property renders\n- [#MODX-805] Fixed attribute issues with TV web output renders\n- [#MODX-859] Changed login page loader box to say 'Loading...' instead of 'Saving...'\n- [#MODX-860] Fixed z-index issues across manager\n- Added a custom loadMask to MODx.tree.Tree objects to display when they're loading but not affect page focus\n- Added a custom loadMask to the Package Management download tree to display while loading the remote provider payload\n- Added in icon for package files\n- Added fsockopen as a fallback for transport package if allow_url_fopen or cURL is not enabled\n- [#MODX-856] Added cURL method of grabbing transport packages when allow_url_fopen is set to false\n- Fixed bug in property update where list grid was not hiding if list xtype was previously selected but not now\n- Fixed import properties where it was not properly handling descriptions\n- Fixed bug where ExtJS couldnt handle text/json header responses with fileUpload set to true in form panels\n- Fixed some DOM issues with Package Management\n- [#MODX-833] Temporary fix for modManagerLog message showing up in console\n- [#MODX-853] Changed source caption of view resource data\n- [#MODX-809] Adjusted formatting of View Resource data fields\n- Fixed bugs with Resource data page not loading fully, glitching tree\n- [#MODX-772] Fixed bug where plugin events were not showing enabled if filtered by name\n- Fixed user system event calls to pass proper arguments\n- Fixed bug where you could only load 1 Quick window at a time\n- Fixed bug with duplicate resource\n- [#MODX-845] If no setup options are specified, package installation will automatically proceed\n- Added parameter to the getNodes processor for resources/elements called 'stringLiterals' which, when true, does not encode the JS literals\n- Layout can now be toggled between tabs (default) and portal panels via the setting 'manager_use_tabs'\n- Nuked the Loading Box in MODExt\n- Changed clearCache key shortcut to CTRL+U (CTRL+SHIFT+U for PC users)\n- Fixed issue where folder resources couldnt be drag/dropped\n- Added some key-events: CTRL+H for hiding accordion, CTRL+U for clearing cache, CTRL+N for Quick Create Resource (PC users will need to add SHIFT to all those calls)\n- Fixed portal issues with Safari\n- Added a few events to MODx. JS object, cleaned up code\n- Added sanity checks to context/category create/update processors\n- [#MODX-766] Added check to prevent settings starting with numbers\n- Added ability to update plugin events and dynamically manage plugins associated with them by right-clicking on them in the Plugin Event grid\n- Added 'beforeSubmit' listener to MODx.Window\n- Adjusted TreeDrop code to allow for RTEs to utilize drag/drop features\n- [#MODX-827] Fixed typo in resource container help string\n- Added prevention fix to prevent dragging of non-elements/resources into content panes\n- [#MODX-770] Fixed bug with creating Symlink\n- Fixed issues with creating and editing a static resource\n- Fixed bug with treedrop that set boolean values to string representations; changed to 1/0\n- Fixed missing context menu item to remove new properties in a property set\n- Added functionality for Element Tag Builder to use descriptions of properties\n- [#MODX-817] Redid Clear Cache window to use MODx.Console\n- Lexiconized missing \"Copy to Clipboard\" string\n- Slight tweaks to MODx.Console to get messages to display final ending messages properly\n- Changed invokeEvent missing event warning to debug msg to prevent it from logging in every console output\n- [#MODX-818] Fixed issues with Quick Create where it didnt work in FF, missing lexicon strings\n- Added Visual Element tag builder when you drag/drop an element into a field\n- Resources/Elements can now be dragged from tree straight to Resource Content pane.\n- Removed Spotlight effect on dialogs; was unnecessary.\n- Fixed bug in Namespace creation window that was preventing namespace from creating\n- Added refreshes to comboboxes in Lexicon Management to refresh combos on Namespace/Topic creation to keep panels up-to-date\n- Fixed Safari issue with Element tree displaying funky on certain pages\n- Fixed issue in Safari where combobox trigger was on left side\n- Only set lexicon entries for context/user settings if they dont exist as system settings\n- Fixed issue with Actions panel causing accordion DOM to bug\n- Fixed issue with Quick Update not persisting class_key\n- Fixed some issues with persistent settings for Quick Update Resource\n- Fixed issue with Quick Update Resource content field being too long\n- Fixed invalid lexicon entry reference for quick create resource\n- Added Quick Create/Update Resource\n- Preview context menu option now is \"smart\" and builds FURLs and separate context references\n- Fixed invalid topic reference issue with modLexiconEntry::clearCache()\n- Fixed headers for connector responses\n- Added Quick Create/Update for all Element types\n- Fixed bugs with category setting in Element processors\n- Added Clear Cache checkbox option to all Element type forms\n- Fixed bug with Category dropdown\n- Fixed tv input properties forms from double-rendering\n- [#MODX-804] TV fields now fire resource change event\n- Fixed bug in Safari with TV fields being uneditable if panel is dragged\n- [#MODX-745] Added 'cancel' button to go back to policy page when updating a policy\n- [#MODX-573] Removed no-longer-applicable 'role' column from users grid, fixed capitalization issues in processors\n- [#MODX-762] Added in missing lexicon entries to hardcoded strings\n- Added modx.localization.js for i18n translations\n- Added indexes on modLexiconEntry table\n- Properly formatted lexicon strings still using sprintf\n- Fixed bug where created was not set on transport package creation\n- Made sure package grid paginates correctly if number of packages installed exceeds 20\n- Fixed Last Modified On on Lexicon grid\n- Optimized action, menu, language, content-type, lexicon, namespace processors\n- [#MODX-765] Added fix to prevent creation of blank system settings\n- Fixed bug in Safari with TV widget properties rendering\n- Consolidated resource getNodes processor, added access policy checks\n- Added sanity check to toJSON function in modConnectorResponse\n- Properly refactor element tree to point to correct processor\n- Added delegate processors for different modes in element tree\n- Updated Context policy attributes for missing attributes\n- Fixed invalid category reference on chunk update processor\n- Added log error messages if save()/remove() fails on modElement derivatives\n- [#MODX-771] Fixed invalid lexicon string reference in element tree\n- Added WARN log message when executing a system event that doesn't exist\n- Filled out missing access policy checks in element processors\n- Fixed incorrect and missing permission check in snippet get/getList processors\n- Fixed invalid lexicon reference in template processors\n- Optimized templateTV getList processor to use only one query\n- Optimized plugin event getList processor to use only one query\n- [#MODX-194] Added sanity checks to element names\n- [#MODX-792] Added check to prevent user from creating blank context, other sanity checks\n- [#MODX-475] Prevented adding contexts with _ in name; will auto-strip\n- [#MODX-796] Fixed check for valid passwords in setup\n- Fixed problematic reference to $_lang\n- Fixed improper log message reference in lexicon's reloadFromBase processor\n- Additional access control defects and warning messages resolved for anonymous users.\n- Fixed access control defect which prevented multiple policies from being respected per principal.\n- Fixed issue with Policy Attributes not adding b/c id was not passed in\n- Added 'save' event fire to Element/Resource formpanels\n- Properly setup on*FormRender events for Element classes\n- Added MODx.onSaveEditor check, which will fire on form save, that allows 3rd Party Components to execute JS code on Element/Resource saves\n- Major refactoring to modx.actionbuttons, to render faster, as well as properly register events and button configs\n- Allowed OnRichTextEditorRegister to return a string as well as an array\n- Added MODx.releaseLock(id), which releases the lock on a Resource for a given ID\n- Added MODx.sleep(ms), which sleeps the UI for a given number of milliseconds (useful in async calls)", "MODX Revolution 2.0.0-beta-1 (LastChangedRevision: 5070 , LastChangedDate: 2009-05-28 16:20:08 -0500 (Thu, 28 May 2009))\n====================================\n- Fixed issue with cacheable toggle on derivative Resource pages\n- Fix error message when reading expired messages in modDBRegister.\n- Fixed issue with login page JS\n- Fixed issue with derivative Resource classes JS not loading Page Settings data into submit\n- Fixed issue with utilities JS not loading at right time\n- Updated build.xml to produce beta releases.\n- Quick fix to prevent blank attribute referencing\n- Fixed issue with package attributes and skipping blank options\n- [#MODX-723] Fixed issue where preview pane was picking up CSS from preview\n- Updated xPDO to revision 333.\n- Fix issues with Page settings defaulting to 1 on resource creation\n- Adjusted order of JS utils loading to make for easier min-concat loading\n- Cleanups to JS to prepare for beta-1\n- Lexicon updates\n- Updating outdated copyright notices in source code headers.\n- Fixed hardcoded version number in setup.\n- Added request_controller system setting to indicate the front-controller file (default=index.php).\n- Fixed array_merge warnings in modLexicon.\n- Added back support for anonymous user access control.\n- Added support for returnUrl parameter to be sent to login processor to allow unauthorized responses to return to the original requested page directly (NOTE: this overrides manager_login_startup and login_startup parameters, but does not work with POST requests: these will simply return to the URL with only GET parameters).\n- Export lexicon now prompts for download of exported file\n- Enhanced User Group update/create screen to now have grids that allow you to assign Resource Group / Context permissions to that user group. This will help clear up confusion with the access relationships.\n- Fixed scope issue in accordion.css that was causing odd behaviours with panels in the main content\n- Adjusted setup procedures to allow for more lexicon support for pre-load checks\n- Adjusted setup lexicon to allow for multiple topics; conformed upgrade scripts and other references to match\n- Consolidated similar code in setup, esp. with regards to fatal errors\n- Added smarter checks for xPDO failures in connectors\n- [#MODX-744] Fixed issue with invalid display of num cleared on cache claering\n- Fixed bugs with updating packages from a remote provider\n- Made sure package attr returns '' if false\n- Fixed manager log to show username, not user ID\n- Standardized derivative resource form panels to move page settings to left\n- Tweaked tree menu headers\n- Minor IE overrides for top navigation and accordion panel.\n- Added support for modLinkTag properties as url parameters, with context reserved to indicate a context to send to makeUrl().\n- Fixed error in modLinkTag when passed invalid data.\n- Added '@RESOURCE' binding alias so as to deprecate @DOCUMENT binding\n- Fixed default language setting for modLexicon\n- Fixed a couple issues with the page settings checkboxes for resources\n- Removed deprecated _tx_.gif\n- Removed home icon and replaced with tab\n- Adjusted CSS to align main content page vertically\n- Trees now have fun new icons representing their types (this includes the resource, element and file trees)\n- Cleaned up the default.inc.php lexicon topic to remove any no-longer-used entries\n- Fixing typo in subtract output modifier\n- Fixed improper reference in TV property renders for mgr context\n- Updated xPDO to revision 329.\n- Improvements to sendError() behavior.\n- Added lock stealing processor and updated remove_locks processor.\n- Added steal_lock:true policy attribute to default Resource policy to allow lock stealing permissions by ResourceGroup.\n- modTemplateVar: Fix getValue() on `value` field by storing and verifying the value requested is cached by the same resource.\n- modResource: Add resourceId value to getMany() on modTemplateVar to identify the resource caching a value on the modTemplateVar instance.\n- modX: Set logTarget based on XPDO_CLI_MODE; ECHO for CLI and HTML for non-CLI requests.\n- modX: Add sendError() function to provide customizable, named error pages on FATAL or other critical error situations.\n- modX: Refactored sendForward(), sendErrorPage(), sendUnauthorizedPage() functions to allow an array of options and better handle FATAL errors.\n- modCacheManager now Caches related modContentType data to prevent unnecessary database connection/query on fully cached pages.\n- Fixed problem with modStaticResource truncating the content to the size of the static file by setting the content length header on non-binary content types.\n- Fixed problem with modStaticResource non-binary content types rendering the path to the static file rather than the actual content of the file.\n- Calling modX->log(MODX_LOG_LEVEL_FATAL) or modX->messageQuit() now logs the error to file and then renders {MODX_CORE_PATH}errors/fatal.include.php.\n- Updated to r325 in xPDO: xPDO method changes to getOption() and _log().\n- Update 'setup-options' ability in transport packages to allow for script-based setup options that will properly handle upgrades to setup options default values\n- Updated to r323 in xPDO: Revise xPDOTransport::writeManifest to make 'setup-options' be able to be an executable script to allow for dynamic form ability\n- Updated snoopy class to version 1.2.4 (used by magpierss).\n- [#MODX-535] Removed automatic setting of isfolder based on presence or absence of children.\n- [#MODX-499] Site start Resources now return base_url from modContext->makeUrl() if no scheme is specified (i.e. when expecting relative links).\n- Improved error reporting on modX->makeUrl() to show original $id value being passed in on failures.\n- modLinkTag no longer returns empty values on first pass of parser, allowing delays until the value returns a valid value.\n- Implemented modResource editor locking (added modResource methods: getLock(), addLock($user), removeLock($user)).\n- Implemented modResource locking features in all appropriate processors.\n- modResource->checkChildren() now uses modX->getCount() to determine if children exist.\n- Added steal_locks attribute to Context access policy.\n- [#MODX-728] Made sure config check dialog is hidden if no warnings are present\n- Package Installations will now skip license agreements / readme panels if none are specified\n- Made sure More Info in download panel can scroll\n- Fixed issue with spacing in setup options panel of package install\n- modCacheManager->generateScript(): Fixed PHP notice in log message on error.\n- modInstall: Modify _modx() function to call setDebug with E_ALL & ~E_NOTICE instead of E_ALL & ~E_STRICT.\n- Optimized queries in element tree to eliminate subqueries or queries in loop, reducing to O(n) instead of O(n^2n)\n- Made clear cache results a bit smaller\n- Refresh trees after clear cache\n- [#MODX-609] Clear cache menu item now loads results in an alert dialog. No longer loads a separate page.\n- Fixed to template getlist processor\n- [#MODX-671] Fixed bug with resource group access permissions being checked when not assigned\n- [#MODX-699] Fixed to allow usage of login processor without lexicons\n- Added Import/Export to element properties grids, which allows for file-based transporting of properties.\n- Fixed issues with comboboxes dropping down a blue screen\n- [#XPDO-28] Fixed problem with multiple file resolvers on vehicles with similar basenames cause directory contents to merge unexpectedly.\n- fixed PHP notice for missing elementType variable\n- fixed subcategory elements missing from display (was counting elements in parent category rather then subcategory to determine if the subcategory should be displayed)\n- Fixed issue with default properties in TVs being locked\n- Fixed no onTVFormPrerender\n- Made sure clearDirty is fired on TV panels\n- Tweaked the css and updated copyright year.\n- Refactored all index.php gateways to support constructor options set as $options in the various config.core.php files.\n- modCacheManager/modCache: Introduced cache partitioning allowing various cache provider implementations to target specific MODx cache partitions and provide custom (system/context/user) settings for configuration options to each: cache_system_settings, cache_context_settings, cache_resource, cache_scripts, cache_lexicon_topics, cache_action_map\n- modAccessibleObject: Refactored object and collection loader logic to improve cache hit rates.\n- modRequest: Fixed warning for undefined variable $fromCache.\n- modSessionHandler: Refactored write() method to only update access time when the session data has changed or at specified intervals before the data is made available for GC.\n- modSessionHandler: Added support for cache_db_session, a new configuration setting to allow session data to be cached when cache_db is enabled.\n- modTemplateVar: Allow getValue() to use a `value` field for data if already populated for a specific resource.\n- Commented out missing image in welcome.tpl (temporary)\n- Added couple of bugfixes to modDBRegister to prevent duplicate payloads and update existing messages.\n- Fixed bug where QuickUpdateChunk was persisting values\n- Added fix to prevent DOM id problems\n- Added clearCache checkbox to chunk editing to allow toggleable cache clearing\n- Optimized chunk processors\n- Added 'Quick Update Chunk' and 'Quick Create Chunk' options to Elements tree, which allows you to quickly edit or create chunks via a window straight from the Element tree on any page\n- [#MODX-718] Fixed bug where elements without a category wouldn't show\n- [#MODX-697] Fixed problem with deprecated role topic still in action build scripts\n- [#MODX-705] Removed random numbers causing Radio TVs to render improperly\n- Fixed bug that caused policy data to be erased when creating/saving/removing policy data\n- [#MODX-711] Fixed Update Context screen to properly pass correct PK\n- modDbRegister: fixed bug with expired messages not being removed if remove_read => false\n- modDbRegister: allowed messages to be updated/overwritten\n- Fixed modCacheManager::prepare() - was returning false on already-prepared contexts\n- Added support for nested categories for elements; categories can now have subcategories\n- Fixed to treestate to properly set treestate ID so restore can work properly\n- Fixed call to onDocFormRender to make sure ID is passed on Resource update\n- Fixed to getFiles processor for MODx.Browser to properly store URL parameter with the base_url prefixed\n- [#MODX-712] Fixed errors creating context settings\n- modX: Fixed potential error when invokeEvent() is called and executes a plugin with property sets and pluginCache does not contain the object\n- modCacheManager: Fixed error when building the pluginCache with property sets\n- modCacheManager: Fixed typo in parentSql that was breaking use alias paths option.\n- modCacheManager->generateContext(): Added support for Resources to be generated in multiple contexts via modContextResource.\n- modParser: Removed errant log() statement in parseProperties().\n- modParser: Fixed problem in parsePropertyString() when passing `escaped` property values containing semi-colons (;).\n- Added in necessary reloading functions to ColumnTree\n- Fixed issue with column tree's context menu overriding the ID\n- modManagerResponse: Detect if controller responses are error arrays and render using error.tpl appropriately.\n- [#MODX-693] redirect bug - modResponse logic error\n- Moved core/config/version.inc.php to core/docs/version.inc.php\n- layout/tree/resource/getnodes.php: Additional optimization to reduce memory usage and improve performance when opening Resources containing a large number of children.\n- modConnectorResponse->toJSON() optimized to greatly reduce memory usage and improve performance with large result sets.\n- [#MODX-691] allow User Settings to be saved from prop. grid\n- Fixed bug with documentMap\n- Fixed issue with default tv render panel for resource page\n- [#MODX-690] Fixed a few events names registered in the system_eventsnames table during build/install\n- Added id's to element and category nodes for informational purposes (missed one spot).\n- Added id's to element and category nodes for informational purposes.\n- Updated drag and drop behavior to update context_key of all child Resources when dropping a container on a different context node.\n- Modified modTransportPackage.manifest field from MEDIUMTEXT to TEXT in order to handle large manifests.\n- Fixed aliasMap broken in recent cacheManager refactoring.\n- Added helper functions to MODx.tree.ColumnTree\n- Added DD events to ColumnTree\n- Added missing column tree CSS\n- Added UI for adding property sets to PluginEvents\n- Added cacheManager object checks to verify for PHP4 installs\n- modCacheManager->generateResource(): added validation of the modResource primary key before attempting to cache a record.\n- modUser: modified storage of session data to use the modUser primary key value to isolate values associated with a specific user; this will allow users to login as multiple users on the back-end and/or front-end without affecting the session data associated with a specific user.\n- modX->_initSession(): Enable session_gc_lifetime configuration setting to set session.gc_liftime ini setting regardless of what session handler is configured.\n- modPluginEvent: Added the ability of plugins to utilize Property Sets by allowing a plugin registered to a particular event to attach a Property Set and make it available during processing.\n- Fixed warning with loading of RTEs in resource page\n- [#MODX-674] Fixed content-dispo combobox bug\n- Removed allowBlank: false check on menuindex to allow for dynamic creation\n- Added in missing lexicon entries for prior menuindex commit\n- [#MODX-678] Added back in 'menuindex' field to resource panels\n- Added missing modX::__construct() options parameter.\n- Allow for extending of MODx.panel.ResourceTV by making reference to modx-resource-template field dynamic\n- Fixes for RTE loading\n- Fixed issue where smarty template path was not being reset if 3PC set path to something else\n- modX constructor now accepts a second parameter containing an array of options to be set in the config\n- Major refactoring of modCacheManager to provide more granular caching options\n- modCacheManager now accepts options, based on changes to xPDOCacheManager, and provides access via getOption()\n- generate*() methods now all return data as well as cache it to a specified cache_handler unless otherwise configured\n- modX->getCacheManager() no longer supports MODX_CACHE_DISABLED or config['cache_disabled']; the cacheManager is required, though you will still be able to effectively turn off all caching in the future via this setting (this will be worked back in)\n- manager/controllers/system/refresh_site.php changes to better target things to remove from the cache\n- Introducing modDbRegister and the modx.registry.db package, providing a database modRegister implementation.\n- Added new system settings for individual cache areas, i.e. cache_system_settings, cache_context_settings, cache_lexicon_topics, cache_scripts, etc.\n- modCacheManager: Various fixes and adjustments to latest refactoring, including clearCache improvements.\n- manager/controllers/system/refresh_site.php: Improvements to default clearCache call.\n- modCacheManager: converted generateActionMap() to support configurable cache implementations\n- Updated modAction->rebuildCache() and modManagerRequest->loadActionMap()\n- Additional tweaks to manager/controllers/system/refresh_site.php\n- Updated xPDO externals to revision 308\n- Removed unnecessary comments from the reg* functions\n- Moved all manager pages JS/CSS to inside HEAD tag using the reg* functions; this improves speed and validation of the manager\n- Fixed the way 3PCs handle their controller files. NOTE!!! This means that you no longer need a \"core/controllers\" file in your 3PC; just set the namespace path correctly, then set the controller in your modAction.\n- Added an ability for mgr pages to utilize regClientStartupScript and other reg* functions to make pages load faster and move JS/CSS to HEAD tag\n- modX->getEventMap() - Made sure prepare() creates a valid statement before calling execute()\n- Updated modStaticResource to set headers in getFileContent() for now, though this needs to be refactored for flexibility.\n- Fixed issue with saving TVs from create resource processor\n- [#MODX-637] Fixed issue with TVs not reloading on changing template in new resources\n- [#MODX-663] Fixed various issues with modAction creation\n- Fixed issue with MODx.Browser uploads not refreshing the main view\n- Fixed publishedon default date setting\n- Fixed date TV default value\n- Fixed default setting for symlinks\n- Fixed issue with Symlink/WebLink class_key storing\n- Fixed issue with textfield editing in Safari on Property Set grid\n- [#MODX-662] Fixed duplicate issue with elements\n- Fixed issue with property sets page and property lock\n- Fixed name issue on duplicating elements\n- Fixed symlink page setTimeout issue\n- Fixed missing file inclusions\n- Fixed element tree where categorized templates weren't showing\n- Added editing ability to resource's publishedon date\n- Fixes to package downloader panel due to ID conflicts\n- Adjusted modTransportPackage::transferPackage to rename incoming file to [signature].transport.zip rather than basename($source)\n- Fixed xml/json response classes to properly work\n- Added permission \"unlock_element_properties\", which gives ability to unlock editing of default element properties.\n- Added implementation of above permission into element properties grid\n- Fixed some logic issues with the lockMask\n- [#MODX-561] Added \"Locked\" ability to default properties for elements\n- [#MODX-633] Fixed issue with add another not respecting parent\n- Fixed TV access panel not working on new TVs\n- Fixed state management with tree nodes\n- [#MODX-661] Fixed URL TV input, where it was not setting prefix value\n- [#MODX-659] Fixed bug where root-level docs couldnt be updated b/c of parent issue\n- Fixed bug with parent being assigned to 0 always in derivative Resource classes\n- Made sure bad resources (where parent = id) are ignored when building the context cache files.\n- Fixed parent bug in controllers\n- Fixed transport.data.php with 'namespace' key on modActions\n- [#MODX-622] Updated top menu structure to be more consistent.\n- Fixed error if properties are null\n- [#MODX-651] Fixed bug when deleting a propset, would not empty grid\n- Fixed to resource page combos not setting display value correctly\n- [#MODX-658] Fixed issue where in TV -> Create, templates were not showing\n- Fixed template nodes to properly sort by templatename\n- Adjusted resource menus and such to refer to a 'Resource' without a specific class_key as 'Document' when applicable, with the exception of talking about Resources in the generic sense\n- Added Duplicate option to Property Sets\n- Fixed bug where template inheritance for resources wasn't happening\n- Fixed symlink page\n- [#MODX-632] Updating xmlrpc to 2.2.1\n- Corrected logic in setup to allow forced PDO emulation mode (XPDO_MODE == 2).\n- Added `category` field to modPropertySets; they can now be categorized\n- Enhanced UI to support new modPropertySet category ability\n- Modified MODx.Window so that the ENTER key submits the form\n- Added more IDs to element forms\n- Added ability to \"remove\" overridden properties, but only ones that are not in the default propset (ones that are should \"revert\")\n- Fixed OnWebPagePrerender event not firing as expected.\n- modOutputFilter: Refactored date modifier to return '' if the timestamp encountered == 0 or -1.\n- modOutputFilter: Added strtotime modifier.- Refactored connectors to execute in the context from which they are called, rather than their own context.\n- Updated xPDO to revision 304 for new xPDOFileVehicle feature to respect XPDO_TRANSPORT_RESOLVE_FILES options.\n- [#MODX-562], [#XPDO-24], [#XPDO-25], and [#XPDO-26] Updated xPDO to revision 302 to resolve various issues regarding transport packages and model generation.\n- [#XPDO-23] and [#MODX-604] Updated xPDO to revision 298 to resolve nesting error when logging messages during installation with improper cache directory permissions.\n- Added modPropertySet->getElements() method as shortcut to get all proper modElement instances available to the set.\n- Added overridden modElementPropertySet->getOne() to get related Element using the proper element_class value.\n- [#XPDO-21] Updated xPDO to revision 290 for updates to xPDOObject::addOne() and addMany().\n- [#MODX-553] Unpublished and deleted Resources now ignored properly in modRequest::getResource().\n- [#MODX-553] Core setup now automatically adds an ACL to the web context for members of the Administrator group.\n- Core setup now updates the Administrator group ACLs for accessing the mgr and connector contexts with an Authority of 0 (highest authority).\n- Modified OnUserNotFound event handling not to rely on references which no longer work properly with recent changes to property handling.\n- Added overridden modElement->get() to handle converting legacy property strings stored in the database.\n- Added modPropertySet class to represent persistent sets of properties that can be applied to modElement instances.\n- Added support for modElements to relate modPropertySet objects via modElementPropertySet (many-to-many).", "MODX Revolution 2.0.0-alpha-6 (LastChangedRevision: 4485 , LastChangedDate: 2008-11-25 11:58:49 -0600 (Tue, 25 Nov 2008))\n====================================\n- [#MODX-395] i18n'ed the modMail classes, added lexicon topic 'mail' for handling mail strings\n- Added check to make sure user cannot browse to subdirs with ../ in connector processor fetching\n- [#MODX-482] Implemented code to remove setup/ directory when box is checked.\n- [#MODX-408] Fix atrocious grammar in mail reception message\n- Fixed labels for static resource page\n- [#MODX-518] Make sure clearing cache clears registry output from package\n- Fixed in_array() checks against $_currentTimestamps in xPDOObject::save() that prevented timestamp/datetime fields from saving 0 values.\n- [#MODX-512] Fixing check in setup to make sure core/packages is writable\n- Fixed bug with RTE loading and saving\n- Changed 'Provisioner' references to 'Provider' in UI for nomenclature consistency purposes\n- Added lexicon load to resource processors\n- Fix error on resource view when template is empty.\n- Added namespace filter to settings grid\n- Fixed import trees\n- Hide the resource ID field if a new resource\n- [#MODX-514] Fixed issue with pub_date/unpub_date not being reset properly\n- [#MODX-484] Added missing ht.access sample to web context files in included in transport package.\n- Modified modWorkspace vehicle attributes to XPDO_TRANSPORT_UPDATE_OBJECT => false\n- Updated xPDO to revision 284 for new xPDO package-aware vehicle features when loading classes.\n- Slight styling improvement to grid to make alt-rows more apparent\n- Added clearCache() functions to modLexiconTopic, modLexiconLanguage\n- Added 'collapsible' options to the options tabs of resources. Can now collapse them to show only the content editor.\n- Prevent blank property value names\n- Adding css classes to modext components for easier styling\n- Fixed some issues related to installation of packages, namely dealing with the setup-options attribute and resolver handling\n- Added _build/build.local.xml to prepare an svn development copy for execution; builds core transport, minifies and concats the javascript and puts it in place, etc.\n- Slight fix to login box and css styles to get checkbox checked css to render properly\n- Updated xPDO to revision 281 to get fix to xPDOObject::save() when updating fields with NULL values.\n- Styling updates; make form fields bigger, tabs bigger, menus bigger...basically pretty up the UI\n- Fix to typo in createTable in modInstallVersion\n- Implemented version-specific upgrades to setup/\n- Updated xPDO to revision 275 (xPDOObject datetime/timestamp handling improvements, xPDOTransport pre-existing object restoration features, and more).\n- Changed System Events action to Error Log Viewer, which now allows you to view (and clear) the error log from the manager\n- [#MODX-509] Fixed issue with refreshing of incorrect node in dragdrops on trees\n- Fixes to CSS in setup, moved error box to fixed bottom right, i18n'ed more stuff, cleaned up HTML and simplified outputs\n- Fixed issue where the path for processors could not be overridden by changing the parameters for handleRequest in modConnectorRequest to an array of options\n- [#MODX-501] Fixed issue where trees didn't refresh when package was installed. All trees now refresh.\n- Fixed bug with duplicating resources\n- [#MODX-505] Fixed issue with creating weblink redirecting improperly\n- Fixed issue with emptying recycle bin and root-level resources\n- [#MODX-508] Weblinks are now not hidden by default\n- Fix missing published checkboxes in resource derivative classes\n- Applied patch to fix issue with label click of checkboxes not changing value\n- [#MODX-507] Fixed bug where Published checkbox wasnt showing in resource panel\n- Fixed bug in filetree that would scroll up topmenu\n- [#MODX-507] Adding in textbox for parent ID for now, will come up with better solution later\n- [#MODX-506] Fixed bug where cache wasn't cleared on drag/drop in tree\n- Fixed bug in modPackageBuilder that was preventing deletion of existing package directories and files.\n- Added constants MODX_INSTALL_MODE_NEW, MODX_INSTALL_MODE_UPGRADE_EVO, MODX_INSTALL_MODE_UPGRADE_REVO\n- Extracted install->test() to a separate class, then i18n'ed the test strings\n- LOTS of phpdoc additions to all processors, including parameter lists for each processor\n- Removed any last trace of modules from Revolution\n- Added phpdoc information to processors\n- Properly clear cache on install/uninstall/remove of packages\n- Removed \"require_once MODX_PROCESSORS_PATH.'index.php';\" from all processors\n- Only show 'Update Package' if the package comes from a provider\n- Fixes to get browser working with TinyMCE\n- Fixed issue with forced removing of packages not properly removing the resolvers\n- Standardized modRequest/modResponse methods across all derivatives (i.e. modRequest::handleRequest() always calls modRequest::prepareResponse(), which calls modResponse::outputContent()).\n- [#MODX-478] Fixed typo in lexicon import/export that prevented window hiding\n- Fixed issues with Symlinks\n- Fix to TV output/input renders when loading in a context other than web/mgr\n- Fix to invokeEvent to prevent unwanted caching of event name if plugin executes more than one event per runtime\n- [#MODX-424] Added readme viewing to package grid\n- Added ability to delete multiple element properties at once via a multiple row handler\n- [#MODX-488] Removing double click from properties grid for 'name' field to prevent unwanted breaking\n- Added back in setDirectory to modConnectorRequest\n- [#MODX-292] Properly format system settings editedon value\n- [#MODX-293] Properly format editedon for lexicon entries\n- [#MODX-481] Fixed rendering issues in element property grid columns\n- [#MODX-479] Fixed issue where first snippet property edited didn't show value\n- [#MODX-480] Fixed issue with lexicon entry update/create not loading proper topic\n- [#MODX-474] Removing package builder menu item from build script\n- [#MODX-456] Fixed issues with element property grids\n- Fixed MODx.grid.LocalGrid store bugs when dealing with grouped data\n- added pageSize and pageStart config items to MODx.grid.Grid\n- Fix to MODx.grid.Grid in case listeners are provided, dont ignore context menu\n- [#MODX-466] Fixes to dropdowns for element categories, field issues\n- [#MODX-115] Some fixes to rendering issues with comboboxes/datefields on Safari\n- Updated xPDO to rev 265 for improvements in xPDOValidator allowing multiple rules to be evaluated per column.\n- Refactored modError completely, removing all derivative classes and introducing modManagerResponse and modConnectorResponse to handle formatting modError responses appropriately.\n- Added modRequest::registerLogging() and relocated logic for detecting and taking action on register logging parameters out of loadErrorHandler().\n- Refactored modArrayError to remove Smarty dependencies, moving them to a new derivative, modSmartyError which the manager UI can utilize explicitly.\n- Added element property panel to all Element panels for managing default properties (except Modules).\n- Added modElement->setPlaceholders() to set placeholders and return any global placeholders that might need to be restored after an element is processed.\n- modChunk and modTemplateVar now restore any placeholders from the global scope after processing any local properties with the same name.\n- Added properties as local placeholders when processing modTemplateVar instances to match behavior of modChunk/modTemplate.\n- Updates to snippet property editor.\n- Added properties to modTemplateVar to make them consistent with all other elements.\n- Modify modX::getChunk() and runSnippet() to process those elements as non-cacheable instances.\n- Added modResource::getContent() and setContent() functions for extensible control of accessing raw source content.\n- Modify modElement::setProperties() and modTag::setProperties() to handle various property data formats.\n- Updated modParser::parsePropertyString() to handle local property xtypes from UI and convert legacy types.\n- Added isCacheable() and setCacheable() to modElement and modTag classes for direct, extensible control of caching.\n- Modified behavior of modTemplate/modChunk not to prefix properties turned into placeholders with the name of the element.\n- Added getContent(), setContent(), getProperties(), and setProperties() to modTag and derivatives.\n- Added modParser::parsePropertyString() to parse element properties from string or array representations.\n- Updated modElement::process() behavior to check cache sooner and avoid unnecessary source content access and other processing.\n- Additional foreign key and sorting indexes added to modElement classes.\n- Added properties to all modElement classes except modTemplateVar.\n- Added setProperties() to modElement for setting a set of default properties that will be used by the element.\n- Added getProperties() to modElement for getting the properties to be used when processing the element.\n- Added getContent() and setContent() function to modElement and provided overrides in the appropriate subclasses.\n- Removed modTransportPackage::loadTransport(); the manifest should always be loaded from the file.\n- Updated xPDO to rev 262 for improvements in the xPDOTransport manifest format.\n- Updated xPDO to rev 258 for bug fix in new xPDOObject::_setRaw() function with array and json phptype fields.\n- Updated xPDO to rev 256 for bug fix in xPDO::getSelectColumns() and new xPDOObject::_setRaw() implementation to resolve issues with native php types when using fromArray().\n- Added modPackageBuilder->setPackageAttributes() function for easily adding transport-level attributes to a package.\n- Updated xPDO to rev 252 to get new features allowing transport packages to carry transport attributes.\n- Added numerous foreign key and sorting indexes to site_content table (modResource) to improve performance of common queries.\n- Changed modX::changePassword() implementation to call modUser::changePassword().\n- Added getResourceGroups() and getUserGroups() to modUser class to retrieve those things and cache in session.\n- Renamed and moved modX::_checkPublishStatus() to modRequest::checkPublishStatus() and renabled this functionality.\n- Deprecated and moved modX::checkPreview() implementation to modResponse.\n- Added view_offline attribute to default Context access policy.\n- Removed deprecated and invalid modX::makeFriendlyURL().\n- Removed deprecated modX::webAlert() function.\n- [#MODX-364] Results of regClient*() functions are now cached into the Resource cache files to solve error on cached pages with cached snippets.\n- Removed deprecated modX::mergeDocumentMETATags() and moved feature to modResource::mergeMetatags() and modResource::mergeKeywords().\n- Removed deprecated modX::makeList() function.", "MODX Revolution 2.0.0-alpha-5 (LastChangedRevision: 4273 , LastChangedDate: 2008-10-09 12:42:42 -0500 (Thu, 09 Oct 2008))\n====================================\n- [#MODX-88] Move version checking to setup script and add notifications.\n- [#MODX-66] Change the way properties work within the scope of a chunk; placeholders set by the chunks properties are now removed after the chunk is processed.\n- Added modX::unsetPlaceholder() and modX::unsetPlaceholders() functions.\n- [#MODX-329] Fixed error with browser \"remembering\" user even when \"remember me\" is not checked. Was always using the system setting regardless of rememberme.\n- [#MODX-380] Created modSymLink resource class which forwards requests to other resources without changing the URL (as opposed to modWebLink which redirects).", "MODX Revolution 2.0.0-alpha-4 (LastChangedRevision: 4213 ,LastChangedDate: 2008-10-01 12:18:41 -0500 (Wed, 01 Oct 2008))\n====================================\n- Updated xPDO to rev 248\n- More log messages for modPackageBuilder\n- Fixed some bugs with MODx.Browser\n- Enabled specific path setting for MODx.Browser\n- Fix to remove redirect to system settings if version info differs.\n- Added MODX_SETUP_KEY to setup to identify the distribution type and allow setup logic to be conditional based on this information.\n- Introduced additional default policy attributes and policy checks throughout the controllers and processors for more robust access control.\n- [#MODX-349] Added processor and menu item to reload your own access policies without logging out and logging back in.\n- [#MODX-349] Added processor and menu item to flush all user sessions from the database.\n- [#MODX-349] Modified user policies to cache policies by Context; previously policies cached for one context were being applied to other contexts when switching or accessing both from the same browser session.\n- Updated xPDO to revision 246 to fix problem with modLexiconEntry rows being duplicated in upgrades after deleting modLexiconFocus records.\n- Modified Ant build to automatically compress and concatenate js files (SVN users cannot use compress_js option without performing the complete-wc task in build.xml).\n- Updating xPDO to revision 234.\n- Added support for logging to registers through any modError instance when loaded by modRequest::loadErrorHandler().\n- Removed modRegisterHandler and added logging helper functions to modRegistry.\n- Updating xPDO to revision 233.\n- Updated modAccessibleObject::loadCollection() based on xPDO::loadCollection() changes.\n- Updating xPDO to revision 231.\n- Various model updates to reduce memory usage [convert foreach with fetchAll() calls to while with fetch()].\n- [#MODX-137] Locked Elements now editable by users with the Admin policy attribute edit_locked (not locked as in being edited by another user, but locked explicitly in the Element attributes).\n- Moved makeUrl logic to modContext class and modX now determines which context to use when building the URL.\n- Introduced modX->getContext() to retrieve, prepare and store context configurations in modX->contexts array for reuse during the single request\n- Added _config, _systemConfig and _userConfig to hold on to various parts of the configuration settings before they are merged for use, allowing other functions to remerge the settings as needed.\n- Fixed modX->switchContext() to clear all contextual/user setting overrides and reload the bootstrap _config, _systemConfig, and make use of the modX->contexts array.\n- Implemented UI ability to choose vehicle-specific attributes when adding vehicles to packages\n- Added dynamic value replacement of {setting_key} in user settings in modX->getUser().\n- Added function to grab the request parameters to MODx.request\n- Added missing permission check on empty_cache attribute on refresh_site controller/processor.\n- Updated xPDO to revision 218.\n- [#MODX-282] Fixed bug where grid would show non-existent page in lexicon/settings grids\n- Removed permission check on logout action; doesn't make much sense.\n- Proper formatting of editedon time in system settings grid\n- Added System Settings \"Update Setting\" window for more detailed editin\n- Rebuilt core data files for the transport.core.php script and made correction to core namespace path to the value {core_path} which is calculated at run-time.\n- [#MODX-263] Access policy update grid moved to separate page\n- Created panel for editing access policies\n- [#MODX-277] Changed 'setting' to 'name' at top of System Settings grid\n- [#MODX-283] Fixed combo-boolean combobox to prevent overwriting of form variables. this was a bizarre bug.\n- Allowed modPackageBuilder to now use dynamic, on-the-fly namespaces. Separated out registerNamespace() from create()\n- Added support for loading extension_packages via configuration settings before the session is initialized.\n- Fixed dynamic value replacement of {setting_key} in system and context setting generators.\n- Updated xPDO to revision 216.\n- Added class_key field to modUser class/table to support modUser derivatives.\n- Fix to new modLexiconEntry table structure (was not installing due to NOT NULL and no default value).\n- Removed modResource::hasAccess() function to make sure and avoid confusion with security.\n- Add default admin user to the Administrator modUserGroup with a modUserGroupRole of 2 (SuperUser) on new installs and upgrades.", "MODX Revolution 2.0.0-alpha-3 (LastChangedRevision: 3867, LastChangedDate: 2008-07-22 08:44:38 -0500 (Tue, 22 Jul 2008))\n====================================\n- [#MODX-210] Changed no-longer-valid help text for resource panel\n- [#MODX-216] Fixed bug with pub_date/unpub_date for the Resource panel\n- [#MODX-213] manually entered passwords not being displayed after saving\n- Added editability to packages grid\n- [#MODX-205] Fixed category saving\n- [#MODX-196] Fixed snippet category error in IE7\n- Created modInstallError for base processing methods\n- Added object support to modInstallJsonError\n- [#MODX-201] Fixed bug with Category combo that prevented adding in a custom category\n- [#MODX-200] Added colored Not Installed text to not installed packages\n- [#MODX-70] Removed top buttons, as they are unnecessary and cause more problems than they are worth.\n- [#MODX-174] Language setting in setup is not loaded.\n- Note: renamed the language file to en.php to match the adopted IANA standard codes (see #MODX-187)\n- [#MODX-26] Manager User creation problems\n- Corrections to new user account email\n- Added MODX_URL_SCHEME define and url_scheme configuration setting\n- Added MODX_HTTP_HOST define and http_host configuration setting\n- Changed \"Modules\" top menu to \"Components\" top menu. Component developers are encouraged to put their 3rd party menus in there.\n- [#MODX-83] Radio Options not working in TV\n- [#MODX-103] Fixed blank template change warning message.\n- [#MODX-173] Language setting in manager pages is not loaded.\n- Removed ucwords on getlist processor for lexicons.\n- Fixed feed_modx_security/news keys in the build file.\n- [#MODX-184] Fixed show in menu checkbox, should have been labeled \"Hide Menu\" since the opposite is true in the database. Changed to match DB column properties.\n- [#MODX-190] Fixed bug with missing duplicate snippet error message\n- Added check for existing name in snippet duplicate processor\n- Updated build.src.url to branches/revolution\n- Fixed import html/resources\n- Fixed action pointer if version is incorrect", "MODX Revolution 2.0.0-alpha-2 (LastChangedRevision: 3841, LastChangedDate: 2008-07-15 09:18:24 -0500 (Tue, 15 Jul 2008))\n====================================\n- Adopting new product name, MODX Revolution, and changed version to 2.0.0\n- Fixed bug with content type grid\n- Replaced 'gender' with Role column in Users grid\n- [#MODX-182] Fixed invalid reference in tv/create.js\n- Fixed TV input type dropdown, added proper processor/connector\n- changed xPDOCriteria calls to more abstract newQuery ability\n- Added attachment capabilities to modMail/modPHPMailer classes\n- Added setHTML method to modPHPMailer\n- Updated documentation for modValidator class\n- Added explicit header call to set text/json; charset=UTF-8 on responses from modJSONError\n- Remote package installation now works.\n- Fixed invalid schema relationships with transport providers/packages\n- Included check for xPDO transport service config to prevent warning\n- [#MODX-108] Added more database info to the site info page - contrib by sottwell\n- Finished UI for modStaticResource\n- Added some inline documentation to widgets for help\n- Set a more appropriate default resolver target\n- Removed unnecessary package parameter from modPackageBuilder::buildSchema\n- Removed unnecessary package setting\n- Added buildSchema function to modPackageBuilder\n- Added tooltips to elements and contexts in the resource/element trees\n- Fixed bug in Module update page\n- Added a qtip to document tree nodes so they display resource longtitle/description in a tooltip\n- Moved styles to gray theme to prepare for css work\n- Weblinks now functional\n- Fixed slight bug with FF3 and panel collapsibility\n- Fixed plugin properties\n- [#MODX-162] Fixes problem where vehicle grid is not refreshed on 2nd build, as well as resets the form\n- Added 'success' event to MODx.FormPanel\n- [#MODX-172] Fix to option values for setup in IE 6. Fix by kmd.\n- [#MODX-166] - Fixed config cache issue - fix provided by kmd\n- [#MODX-165] could not save Template element - fix provided by SA\n- Fixed and cleaned up the actions/menus JS and combos\n- Removed unnecessary tertiary expression (check is already handled by the function)\n- [#MODX-131] Fixed Apache crash and enabled Tools -> Action\n- Added fix to _() JS function to allow for parameter passing:\n String: 'Testing: [[+hello]]';\n JS call: _('testkey',{'hello': 'Success!'});\n Result: 'Testing: Success!';\n- [#MODX-148] Added support for [[+placeholder]] tags in lexicon strings. i.e., with a lexicon string with key 'test' and value: 'Test me: [[+hello]]'\n Programmatically:\n $modx->lexicon('test',array('hello' => 'Success!');", " Tag:\n [[%test?hello=`Success!`]]\n- Fixed to typo on system info JS\n- Added namespacing ability to the addDirectory() and load() methods of modLexicon. Used like so:\n $modx->lexicon->addDirectory('pathhere/','testNS');\n $modx->lexicon->load('testNS:fociname');\n- [#MODX-102] fixed missing lexicon entries in php4\n- Added OnHandleRequest event, invoked before anything occurs in modRequest::handleRequest().\n- Set the modLexicon::_lexicon to an empty array even if nothing was loaded.\n- Added modX::switchContext(string $contextKey) function to make it easy to switch contexts using a plugin and the new OnHandleRequest event.\n- Fix to properly submit the content field for resources (should also handle multiple RTEs now)\n- Fixed typo in lexicon reference in event getlist\n- Fix to MODx.load to return multiple objects if they exist\n- General JS doc updates\n- Added MODx JS class, which allows for xtype loading via MODx.load()\n- Some JS doc updates\n- Fixed modErrorHandler to ignore suppressed errors like a proper error handler is expected to.\n- [#MODX-109] Fix bug with profile page loading of date.\n- Reconfigured context update window to separate into tabs for easier viewing and rendering\n- Changed TV resource group panel to a grid, instated proper remove/update code\n- [#MODX-126] Implemented 2 new modSystemSettings: feed_modx_news and feed_modx_security for dynamic setting of the RSS feeds in the welcome pane of the manager\n- [#MODX-137] Removed locked check until a resolution is made on locked elements.\n- [#MODX-119] Corrected issue with file editor stripping out SCRIPT tags. Was using $_REQUEST instead of $_POST so the values were sanitized by the request handler.\n- Updated Template management to a MODx.FormPanel\n- Altered the way modLexicon loads multiple foci for PHP4 compatibility\n- Added modLexicon::addDirectory, which adds a directory when loading lexicon foci\n- Properly load TV widgets and i18n their strings\n- Fixed bug with modLexicon and $modx reference\n- [#MODX-133] Prevent elements from being dragged into different types\n- [#MODX-125] Fixed saving pub/unpub date on resources\n- [#MODX-106] Removed assets/images check.\n- Configured Object field in Package Builder to be a combobox that loads a dropdown of the selected class_key\n- Added ability to remove vehicles from not yet built package\n- Added MODx.grid.LocalGrid as abstract class of local-data-based grids\n- Added MODx.panel.Wizard as abstract class of wizard panels\n- [#MODX-121] Fixed top menu loading incorrectly when clicking on icons\n- Fixed TV management page, specifically with TV->Template access\n- [#MODX-118] Fixed bug with creating/removing/updating directories from Directory tree\n- Added MODx.combo.ContentDisposition\n- Added ability for MODx.toolbar.Actionbuttons to support formpanel as an alternative for form config parameter\n- Added $modx->config properties to MODx.config JS array sent\n- Fixed update resource TV loading\n- [#MODX-113] Fixed bug in Safari with scrolling in grids, apparently Safari doesn't like Ext's autoHeight\n- Removed legacy tpl's in settings/ dir\n- [#MODX-107] Fixed tree refreshes when resource is saved, both in create and update. Update will now refresh only the parent node of the resource being saved, which speeds up save time\n- Fixed issues with TV Panel loading improperly on new resource\n- [#MODX-114] Prevented JS error from occurring when using page settings checkboxes\n- [#MODX-116] Fixed text for removing a category\n- Fixed Resource pages to allow for Resource Groups to be assigned access prior to Resource creation, as well as making grid not save until 'Save' is clicked\n- Fixed Template pages to allow for TVs to be assigned access prior to Template creation, as well as making grid not save until 'Save' is clicked\n- Fixed TV pages to allow for templates to be assigned access prior to TV creation, as well as making grid not save until 'Save' is clicked\n- Fixed module update, removing legacy code\n- Fixed plugin event grid: now can be used via create or update, also properly handles events, does not save until \"Save\" button is clicked on action bar", "MODx 0.9.7-alpha-1 (LastChangedRevision: 3664, LastChangedDate: 2008-04-28 12:43:15 -0500 (Mon, 28 Apr 2008))\n- Updated ExtJS from version 2.0 to 2.0.1\n- [Trac#20] When creating new document, make the 'Log Visits' checkbox respect the main configuration setting.\n- [Trac#9] Converted Database Tables tab in System Information to use Ext Grid.\n- [Trac#40] Default role settings are now set correctly when saving roles to the database.\n- [Trac#4] Converted Modules section to use Ext interface.\n- Added new resource import routine for creating resources from static content on the file system, as any valid modResource derivative.\n- Introducing context support to the manager resource trees.\n- [Trac#32] Display correct message counts for the Inbox section on the Welcome page.\n- [Trac#31] System Configuration page always showing 'New Install' message. Refactored code to use $modx->version.\n- [Trac#25] Several bugfixes and refactorings to make the Messages section function correctly.\n- [Trac#6] Remove Locks not working from the top menubar.\n- Removed custom_contenttype from system_settings and manager interface.\n- Converted and refactored Import HTML tool for the new APIs.\n- [Trac#29] Resource checkboxes on settings tab not showing accurate values when editing.\n- [Trac#28] Cache not cleared when resources are saved and the clear cache checkbox is checked.\n- [Trac#27] Cached modResources were not loading or rendering since getResource() moved to modRequest from modX. Cache files generated with new reference to the modX object ($this->modx vs $this).\n- Remove logic in modResource::addOne() that was disallowing binary content types.\n- Add conditional to check for $GLOBALS['https_port'] before attempting to use it.\n- Several fixes to modResource processors involving saving of boolean fields via checkboxes; make sure POST is filled with unchecked fields having a value of zero.\n- Upgrades now work for previous 0.9.7 installations\n- Add-on installation has been removed from setup in preparation for adding it to the manager itself.\n- Removed modManager095 and all related legacy support for ManagerAPI extender, moving this functionality to modManagerRequest.\n- Added/updated delegate controllers, templates, and processors for modWebLink and modStaticResource.\n- Added new static resource option to document tree context menus.\n- Fixed bug with chunk update processor deleting the chunk content.\n- [Trac#19] Bugs with password on user creation/update; was saving plain password (not encoded).\n- Introduction of new setup using transport packages (new installs only for now).\n- Modified modRequest::sanitize() to no longer strip old-style tags.\n- Moved MODx classes and maps out of core/xpdo/om/modx095 and into core/model/modx.\n- [xPDO] Add support for package specific include paths for models.\n- Refactored INCLUDE_ORDERING_ERROR to manager/includes/accesscheck.inc.php\n- Begin adding input and output filtering to all MODx elements and tags (modElement and modTag derivatives), including default filter implementations based on phX (not yet working).\n- Begin refactoring modx095 package to utilize xPDOQuery (modResource::getOne()).\n- [xPDO] Fixed error in xPDOObject::remove() that was trying to call the toCache function on xPDOObject rather than xPDO.\n- Added checkForLocks func to modx.class.php\n- Added checkIfIn to modmanager095.class.php, to do the annoying check if in manager in all the pages\n- Added splitter class for tables to get the line effect found in user management\n- Added ul.no_list to get list effect without bullets\n- Added formhandler.js - handles validation in forms by sending form through AJAX call. If response != true, then outputs response to a div with id 'errormsg'. Also evaluates JS scripts in the response.\n- Updated MODx model for modUserSettings and modWebUserSettings with appropriate primary key indexes and field types.\n- Updated installer SQL to remove the previous indexes and add the primary key index.\n- Fix to modX :: insideManager() to make sure there is a context object initialized before trying to get the context key.\n- [xPDO] Introduction of xPDOQuery for building SQL queries using only objects and the API.\n- [xPDO] Fix to timestamp phptype handling when stored as integer dbtype in database.\n- Modified modResource constructor to set createdon and createdby fields appropriately.\n- Fix for mcpuk GetUploadProgress script (see http://modxcms.com/forums/index.php/topic,11712.msg79581.html#msg79581)\n- Separated styles into their function, for easier manipulation and management\n- Ongoing Conversion of manager pages to xPDO, cleaning up XHTML\n- Emulated PDO can now be forced in PHP 5.1+ when PDO class is already available, but the required drivers are not available.\n- Added $modx->getTree() function for easily getting a tree structure of MODx resource ids in the current context.\n- Modified $modx->resourceMap to a simpler structure and optimized getParentIds() and getChildIds() functions. $modx->documentMap still holds the old structure but is deprecated.\n- Refactored entire caching layer, based on changes to xPDO. Files are now spread amongst logical directories, and automatic temp directory detection was also added.\n- Translated all core files and data in the core distribution/installation to the new native tag format.\n- Optimized modParser, removing run-time translation with modParser095 from normal execution and added modTranslate095 utility class, which can translate tags in database and file content, writing a log of the translation and/or making the changes to the database and files. modParser095 is experimental, and not recommended, as there are too many issues with mixed tags being parsed incorrectly.\n- Fix to make sure modX::parseChunk removes replacement placeholders for empty values.\n- Updates to MakeForm class.\n- Added modXMLRPCResource, modXMLRPCResponse classes and supporting code, including modified XML-RPC for PHP code (from version 2.1). You can now create resources that represent XMLRPC servers and clients.\n- Altered session cookie expiration that was getting set automatically on all sessions based on the default session cookie lifetime. Lifetime is now only applied if a session value is set for each context.\n- Added check to verify keys passed to modX::getPlaceholder() are valid strings to avoid PHP errors.\n- Various additional changes to prevent errors from revealing critical database credentials and connection information.\n- Fixed bug with system settings getting overwritten on mutate_settings manager page.\n- Merged from trunk (0.9.5.1-RC1) at revision 2251.\n- Latest updates and bug fixes from xPDO project.\n- Add ability to locate and use original manager/config/config.inc.php to upgrade directly on legacy installations.\n- Applied fixes to modResponse::outputContent(); was not assigning regClient script replacements to the output.\n- Changed parseChunk to parse new style tags to avoid any accidental matches on mixed tag situations.\n- Changed modChunk and modTemplate logic to create placeholders from any properties of the elements prefixed by the name of the element + '.' (added the .).\n- Fixed alias path generation, was reversing the order of parent paths in the resourceListing.\n- Fixed problems with recent changes to modRequest::sanitizeRequest() which was again truncating $_POST vars in the manager when encountering MODx tags.\n- Fixed generation of context cache files; was generating an eventMap for the mgr context at all times.\n- Fix to logic in modDocument::getMany('modTemplateVar').\n- Merge with 0.9.5.1 trunk at revision 2205.\n- Parsing adjustments to better deal with mixed old and new style tags.\n- [xPDO] Significant xPDO core update to prepare for SQLite, PostgreSQL and other ports.\n- Fix bug in install/upgrade SQL when resetting user and system settings for manager_theme.\n- Added some new configuration options for session handling and various caching features; more to come.\n- Minor changes to reduce number of unique db connections used during a request.\n- Various PHP 4 warnings fixed when assigning values by reference directly from functions (only variables can be assigned by reference in PHP 4).\n- Various improvements to MakeTable class based on usage in user_management and other manager interfaces.\n- Begin replacing Datagrid usage in manager with MakeTable (user_management, web_user_management, manage_modules, docmanager module); lots more Datagrids to replace.\n- Various changes to DataGrid and DatasetPager to try and support existing usage.\n- Fix for @EVAL bindings with more than one line of code.\n- Adjustments to modParser::collectElementTags() to better handle invalid tags (i.e. mispelled snippet names) with nested tags.\n- Adjustments to modParser095::translate() to properly handle translation from old to new configuration tags [(email_sender)] to [[++email_sender]].\n- DBAPI::escape() adjustment (again) to avoid certain issues when using native PDO along-side legacy manager code calling the mysql extension.\n- Removed & from getMany call in modCacheManager to prevent PHP warnings in PHP 4.\n- [xPDO] Added additional logic to xPDO::loadClass() which will return an error immediately if no class name is provided.\n- Adjusted modDocument::getMany() signature; added $cacheFlag= false parameter.\n- Remerged mutate_content.dynamic.php to fix several problems saving documents.\n- Adjusted queries in refresh_site.dynamic.php.\n- Added session table to install script due to failure of auto-table creation on some environments.\n- Removed unnecessary if statement around session_set_save_handler() in modX::_initSession(); the actual problem was auto-table creation was failing.\n- Fix DBAPI::escape() function; PDO::quote() adds single-quotes unlike the legacy mysql escape functions and this was causing content truncation.\n- [xPDO] xPDOCacheHandler class updated to allow configuration properties to determine a class for handling xPDO object and result set caching.\n- modX::_initSession() updated to better handle situations where session_set_save_handler() fails when trying to override default PHP session handling.\n- [xPDO] Modified fromArray() so it is not responsible for determining the _new attribute of xPDOObject instances. This is the responsibility of xPDO::getObject(), which uses xPDO::load(), and xPDO::getCollection().\n- Fix datasetpager error with PDO changes so DocManager module can load.\n- Fix WebUser login -- weblogin.processor.inc.php.\n- Fix makeUrl() -- no longer needs to add base_url.\n- Fix upgrade install script to insert new config settings properly.\n- Few tweaks to modX::_initSession function (was setting session_name twice).\n- Changed all line-endings to unix-style \\n on all files.\n- Removed assets/cache/* which is replaced by core/cache/*.\n- Updated version data format to be compatible with PHP's version_compare() function.\n- Resolved problems setting primary keys values and improperly identifying new objects when using xPDOObject::fromArray().\n- Several adjustments to xPDO::load(), xPDO::getCollection() and several xPDOObject methods based on changes to xPDOObject::fromArray().\n- Added stripslashes() to modRequest::_sanitize() when working with magic_quotes_gpc enabled.\n- Fix to MakeTable::prepareOrderByLink() to handle FURLs properly.\n- Reduce exposure of critical database credentials in xPDO::load() when errors are reported/logged.\n- Fixed error in xPDOObject::save(); updates to objects with compound primary keys were failing.\n- Added proper escapes to deprecated modX::getFullTableName() to fix issues when dashes (-) or other reserved (My)SQL characters appear in a database name.\n- Merged with trunk (0.9.5 final) at revision 2106.\n- Removed session_keepalive code.\n- Merged with trunk (0.9.5) at revision 2066.\n- Merged with trunk (0.9.5) at revision 2063.\n- Schema updates based on column size changes in 0.9.5.\n- Added missing modX::getSettings() method.\n- Various bug fixes.\n- Merged with trunk (0.9.5) at revision 1945.\n- [bug fix] Fixed a modParser bug when CDATA wrappers were encountered.\n- Add missing webAlert function to new modX class.\n- Modify categories save process to get the insert id using $modx->lastInsertId().\n- Fix to setup.sql; changed ENGINE= to TYPE= when creating new context table to avoid problems with MySQL versions before 4.1.\n- Fixed invalid reference to mergeDocumentMETATags in modResponse class.\n- [New feature] Allow custom error handler classes.\n- [New feature] Fine-grained configuration options for caching pages, database results, or disabling the cache altogether (see system settings starting with `cache.`). Turn the different caching options on/off or set a default time-to-live for those items being cached.\n- [New feature] Database result-set and xPDO object caching, with support for memcache, native-JSON object caching for high-performance AJAX requests.\n- [New feature] Configurable session management with default implementation configured for modSessionHandler, an xPDO-based implementation that stores sessions in a database, and allows a great deal of configurability, by site and/or context.\n- [New feature] Contexts allows a site to be organized into sub-sites, subdomains, etc, and override any system settings by context. The default contexts are 'web' and 'mgr' to support the legacy ideas of front-end and back-end session contexts.\n- Introducing the new MODx core built on top of xPDO; this will incrementally replace the entire existing codebase, but can co-exist until 1.0 release and provides about 90 to 95% legacy compatibility for existing tags and add-ons." ]
[ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [4, 121, 29], "buggy_code_start_loc": [4, 55, 27], "filenames": ["core/docs/changelog.txt", "core/model/modx/modmanagerrequest.class.php", "manager/templates/default/header.tpl"], "fixing_code_end_loc": [6, 123, 29], "fixing_code_start_loc": [5, 56, 27], "message": "Cross-site scripting (XSS) vulnerability in manager/templates/default/header.tpl in ModX Revolution before 2.2.11 allows remote attackers to inject arbitrary web script or HTML via the \"a\" parameter.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:modx:modx_revolution:*:*:*:*:*:*:*:*", "matchCriteriaId": "BF258698-982E-42B2-9AB6-049E5FD0017E", "versionEndExcluding": null, "versionEndIncluding": "2.2.10", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "66600BCA-D439-4743-8AE7-4E9433951F6F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "6544C9E0-CD92-407A-A17D-839CC84379CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "EF6D8ED9-01E2-429C-892C-1BDE207C0D34", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "89285DBF-9B65-4A8A-9ABC-1894C484A84E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "1E6ABC9F-775E-4D4C-91AB-35581F493EC5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "6A0B981D-AE93-4312-8AEC-99F157AAFA83", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.6:*:*:*:*:*:*:*", "matchCriteriaId": "73CA07B9-2DE2-4E6A-921D-89667AB54250", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.7:*:*:*:*:*:*:*", "matchCriteriaId": "223B2881-E108-45F5-AF97-6BF740B58420", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.8:*:*:*:*:*:*:*", "matchCriteriaId": "68D5B94B-B7FD-475E-BB9E-47871592959F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.0:*:*:*:*:*:*:*", "matchCriteriaId": "397FB64F-732C-41BC-BFAF-5D4742AD3E39", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.1:*:*:*:*:*:*:*", "matchCriteriaId": "7B762680-99DD-40A1-9D81-21E01A139BEB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.2:*:*:*:*:*:*:*", "matchCriteriaId": "3C9A56B2-5985-4CE3-B206-C657ED992280", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.3:*:*:*:*:*:*:*", "matchCriteriaId": "DDA3C9FA-A54C-4752-B2E0-986B6808423B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.4:*:*:*:*:*:*:*", "matchCriteriaId": "72BAE1E7-E1E7-45EB-AB4E-5E0DEAD84630", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.5:*:*:*:*:*:*:*", "matchCriteriaId": "539CA3F9-8AA5-44A3-917C-BCD94953B3E3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "3C4F2E50-2861-47B1-B4F8-DB3C7F4EDFAB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "357A9A52-0915-4865-B2B7-619A776BF8DD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "686065C6-CA40-4ACC-9927-AB2FD2679362", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.3:*:*:*:*:*:*:*", "matchCriteriaId": "B1B7FAA3-22E0-4464-BDCD-F77AB16FF76B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.4:*:*:*:*:*:*:*", "matchCriteriaId": "7140446F-DAAD-40EC-997E-1A9A140AC39C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.5:*:*:*:*:*:*:*", "matchCriteriaId": "D352065C-12CF-48E0-BD97-2C20178828A0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.6:*:*:*:*:*:*:*", "matchCriteriaId": "319FCE68-F2B0-4F3C-8772-C453F0B9B303", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.7:*:*:*:*:*:*:*", "matchCriteriaId": "00978BE1-0642-4A88-B2E6-B0ABD7E0E3E7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.8:*:*:*:*:*:*:*", "matchCriteriaId": "E94115D1-663A-4282-ABC0-5EE0DB2450C0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.9:*:*:*:*:*:*:*", "matchCriteriaId": "1D83A52A-A9E4-417C-AEFA-006D60518ECA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site scripting (XSS) vulnerability in manager/templates/default/header.tpl in ModX Revolution before 2.2.11 allows remote attackers to inject arbitrary web script or HTML via the \"a\" parameter."}, {"lang": "es", "value": "Vulnerabilidad de XSS en manager/templates/default/header.tpl en ModX Revolution en versiones anteriores a 2.2.11 permite a atacantes remotos inyectar secuencias de comandos web o HTML arbitrarios a trav\u00e9s del par\u00e1metro \"a\"."}], "evaluatorComment": null, "id": "CVE-2014-2080", "lastModified": "2015-07-30T14:52:44.890", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-03-01T00:01:09.590", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "http://modx.com/blog/2014/01/21/revolution-2.2.11%E2%80%94security-fixes-and-prevent-change-loss"}, {"source": "cve@mitre.org", "tags": null, "url": "http://seclists.org/oss-sec/2014/q1/431"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/65755"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Patch"], "url": "https://github.com/modxcms/revolution/commit/77463eb6a8090f474b04fdc1b72225cb93c558ea"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/modxcms/revolution/commit/77463eb6a8090f474b04fdc1b72225cb93c558ea"}, "type": "CWE-79"}
325
Determine whether the {function_name} code is vulnerable or not.
[ "This file shows the changes in recent releases of MODX. The most current release is usually the\ndevelopment release, and is only shown to give an idea of what's currently in the pipeline.\n", "- Prevent XSS on actionVar in header.tpl", "- Fix caching of manager menus", "MODX Revolution 2.2.10-pl (October 7, 2013)\n====================================\n- Increase modTransportPackage version columns range to smallint\n- [#10211] Fix parser state bug triggered by media sources\n- Fix loading modResource derivatives in class_key dropdown\n- [#9973] Prevent extended user classes being set to modUser\n- Upgrade xPDO to 2.2.9-pl\n- [#10182] Improve sanitization of processor_err_nf response", "MODX Revolution 2.2.9-pl (August 28, 2013)\n====================================\n- Avoid critical error when resource tree not initialized\n- Avoid suppressed warnings with ob_get_level()\n- Upgrade xPDO to 2.2.8-pl\n- [#10043] Fix class-loading LFI in registerLogging\n- [#6937] Fix Persistent/Reflected XSS in User Messaging\n- Set default error_handler_types to error_reporting()\n- Upgrade to ExtJS 3.4.1.1 and add ExtJS debug support\n- [#9976] Fix cross-context symlink caching\n- [#10093] Add create/update methods to S3 Media Sources\n- [#9902] Added error window when package download fails\n- [#10070] fix potential SQL injection vulnerability in modImport\n- [#9843] Added lang_topics field to create and update action window\n- [#10094] Defaults overwriting properties in ResourceCreateProcessor\n- [#10007] Fix parser logic when processing elements via API\n- [#10087] Avoid stat warnings with missing static sources\n- [#9809] Remove empty ULs in topmenu\n- [#7569] Add bottom border to collapsed panels\n- [#146] Also fire field change event on change event\n- Fix contextsAffected in resource/sort processor\n- [#9815] Improved manager redraw on browser resize\n- Fix clearcache timing issue with MODx.Console\n- Prevent accumulation of MODx.Console onMessage callbacks\n- Prevent session write errors from phpthumb cache\n- [#9964] Fix Import HTML to use context of parent\n- [#9916] Add TABLE to TRUNCATE command in flushSessions (SQLSRV)\n- [#9527] Fix password reset by user email\n- Fix login processor to use absolute url redirects for mgr\n- [#9826] Fix errant creation of Policy Templates", "MODX Revolution 2.2.8-pl (June 4, 2013)\n====================================\n- Prevent empty HTTP_MODAUTH from succeeding\n- [#9450] Prevent non-existent Context initialization\n- [#9896] Improve performance of modTemplateVar::getRenderDirectories()\n- [#9859] Prevent conditional output filter recursion\n- [#6138] Handle offline errors in RSS feeds\n- Refresh file tree after removing file\n- [#9946] Do not cache modResource::$_isForward\n- Force browser to root on Media Source change\n- Refresh file tree after root upload\n- Fix remove file from root if no folder selected\n- [#8877] Fix inline grid datefield icon\n- [#6945] Fix datefield icon in grid toolbars\n- [#9825] Revert width increase of file and image TVs\n- [#9901] Fix empty resourceMap in sqlsrv\n- [#9912] Fix length of modResource.uri index\n- [#9846] Fix incorrect parameter order passed to findResource\n- [#9814] Fix empty cross-context links using link tags", "MODX Revolution 2.2.7-pl (April 9, 2013)\n====================================\n- [#9634] Fix notices in system/settings/update processor\n- [#9768] Fix array merge in xPDOObject::getMany()\n- [#9773] Fix classKey errors viewing manager actions\n- [#9774] Prevent resource/unpublish on site_start\n- [#8312] Allow sorting users by blocked status\n- [#1] Allow Element duplication when editing\n- [#9237] Return object from ContextSetting create/update\n- [#8327] Don't close context menu on click\n- [#8980] Fix lexicon when updating user password\n- [#9258] List languages and topics alphabetically\n- [#9152] Use default_context for New Resource toolbar actions\n- [#8138] Fix Combo Settings not saving from update dialog\n- [#9571] Fix template/update always refreshing cache\n- [#9093] Make collapsed tree panel tab more visible\n- [#8859] Add button to refresh error log\n- [#9772] Fix deprecated value for CURLOPT_SSL_VERIFYHOST\n- [#9728] Fix empty create Dashboard Widget tab\n- [#9734] Fix save button state on Content Types grid\n- Fix resizing of error log textarea\n- [#9287] Enable save button when switching templates\n- [#9132] Refresh cache when enabling/disabling plugin\n- [#9690] Fix various issues with server_offset_time\n- [#9738] Prevent working context overriding user settings\n- Fix error getting MediaSource table classes on cached Resources\n- [#9368][#9437] Fix modProcessorResponse->isError()\n- [#9681] Allow country/getlist processor to work more than once\n- Fix Auto-Tag TV value sorting\n- Make caching the aliasMap optional to reduce memory usage\n- [#9672] Fix invalid ini_get call in modDbRegister\n- [#8489] Add compound index to modTemplateVarResource\n- [#9592] Iterate all inherited parent FC rules\n- Replace location redirects with MODx.loadPage proxy\n- Add MODx.beforeLoadPage event to modExt components\n- [#9143] Fix destructors in modExt components\n- Allow loading of modExt files asynchronously\n- [#9359] Report errors about unpublishing site_start to user\n- [#9197] Load RTE for SymLinks in manager\n- [#9364] Allow Unicode chars via modX::sanitizeString()\n- [#9631] Fix image preview with special chars in filename\n- [#9608] Remove connections data from MODx.config\n- Fix invalid ini boolean evaluation in config_check processor\n- Allow modX::getParser() to get an extended modParser instance\n- [#9524] Fix invalid context assignment in modX::switchContext()\n- [#9517] modPackageGetAttributeProcessor returning wrong PACKAGE_ACTION\n- [#9451] Add modx-combo-source as settings type\n- [#5515] MODx.Browser UX improvements\n- Increase width of file and image TVs\n- [#9282] Fix Minify errors when manager on different subdomain\n- Various Manager UI Fixes\n- [#6150] Fix issues with auto_publish when encountering invalid data\n- [#8936] Fix modTemplateVarRender::_loadLexiconTopics()\n- [#9257] Fix workspace/lexicon/getlist strict notice in PHP 5.4+\n- [#9339] Use Resource context_key in update processor when not specified\n- [#9212] Fix SQL syntax error in modTemplateVar->findPolicy()\n- [#9239] Make sure class_key is passed when switching templates\n- [#8101] Add support for httpOnly session cookies in PHP 5.2+\n- [#8420] Provide multi-node support to flock-independent file locking\n- [#8420] Remove LOCK_EX from flock-independent file locking method", "MODX Revolution 2.2.6-pl (December 3, 2012)\n====================================\n- [#9178] Use PHP time for valid check in modDbRegisterMessage::getValidMessages()\n- [#9165] Fix modError::hasError false positives when loaded via getService\n- [#9029] Remove modRequest->loadErrorHandler dependency in runProcessor\n- [#9156] Fix reload data for rendering multi-value TV types properly\n- [#7916] Fix Area functionality in Element Properties and Property Sets\n- [#9097] Fix leftbar tree toolbar resizing issues\n- Image optimization applied across distribution\n- [#9006] Fix ImageMagick which convert issue (PHP 5.3.2+)\n- [#9069] Remove math output filter\n- [#9080] Fix modX::stripTags() bug allowing script execution vulnerability\n- [#9007] Prevent MODx.Browser closing window when manager loaded in a new tab\n- [#8928] Error saving Resource with access-restricted TemplateVars\n- [#8978] Fix issue where change template was not fired due to onsave check overriding listener\n- [#9026] Prevent new Content Types from having binary checked", "MODX Revolution 2.2.5-pl (October 2, 2012)\n====================================\n- [#8753] Fix variable name in security/user/removemultiple processor\n- [#7654] Fix Update processor for ResourceGroup-restricted TVs\n- [#8196] Enable save button when combo selections are made\n- [#8186] Apply FC rules to Resources when changing Template\n- [#8790] Add ability to hide changed password in Update Profile\n- [#7551] Ensure static element path is not existing directory\n- [#7631] Fix duplicate beforeSave() in modObjectCreateProcessor::process()\n- [#8754] Change elementType to objectType in various processors\n- [#4430] Return 404 error if static resource target is invalid\n- [#8767] Fix MODx.panel.Resource to inherit config.url\n- [#8545] Add ability to localize ExtJS pre-loading message\n- [#8089] Fix ability to disable drag/drop in Resource tree\n- [#7661] Prevent changing template from unsetting Empty Cache\n- [#8620] Enable type-ahead on User and Country combos\n- [#8529] Prevent empty multi-value TVs from saving as '||'\n- [#8018] Fix file creation/editing on non-default Media Source\n- [#8556] Ensure regClient functions inject only once\n- CSS Style fixes for IE 9 (8, 7)\n- [#8560] Fix Context Admin ACL automation and use Context Policy\n- [#8432] Package Browser tree not reloading on Provider change\n- [#8482] RTE Output Option for TVs does not render on frontend\n- Add Quick Create/Update File feature in Files tab\n- [#6522] Retain page in Package Manager after install/upgrade\n- [#7630] Save modUserGroupMember rank upon creation\n- [#8420] Provide flock-independent file locking to avoid cache corruption\n- [#7498] Fix Media Source error reporting for file uploads\n- [#8299] Clear action_map (and menus) in system/action create/update processors\n- [#8168] Fix JS error when compress_js=Off and compress_js_groups=On\n- [#8341] Allow Resource data pages to be extended by CRCs\n- [#6695] Close sessions before min scripts terminate\n- [#6918] Fix importing access policy items always being checked\n- [#8329] Fix syncsite checkbox being unchecked by default on resource/create\n- [#8296] Fix function passed by reference in ellipsis output filter\n- Allow numeric value in modWebLink to redirect to Resource by id\n- [#7763] Fix additional Media Source path issues with static elements\n- [#8208] Fix modDbRegister->read() with include_keys option\n- Fix PropertySet switching from Element create/update controllers\n- [#7392] Get correct modMediaSource derivative in modParser->getElement()", "MODX Revolution 2.2.4-pl (June 14, 2012)\n====================================\n- [#8105], [#8051] Fix modFileHandler::sanitizePath() infinite recursion", "MODX Revolution 2.2.3-pl (June 13, 2012)\n====================================\n- Add setting to be able to set default context for new Resources\n- Pass http_host in provider requests\n- [#7933] Add friendly_urls_strict to optionally enable non-canonical redirects\n- [#6428] Fix help tooltip for new namespace window\n- [#8054] Fix transport provider verify processor consistency\n- [#8051] Added extra sanitization for modFileHandler.sanitizePath\n- [#7925] Fix error editing Resources in multi-context sites\n- [#8052] Fix empty()/isset() on hydrated fields/related objects\n- [#7798] Avoid E_NOTICE in PHP 5.4 from array_diff_assoc in xPDO::loadClass()\n- [#7796] Fix issue with phpthumb calling non-static methods statically\n- [#7764] Compress and default to open Resource Group access wizard in window\n- [#7762] Fix issue with add/decr output filter not adding 0 if 0 is passed\n- [#7793] Fix issue with saving a new media source access on user group edit screen\n- [#7712] Fix Resource quick update showing 2 checkboxes", "MODX Revolution 2.2.2-pl (May 2, 2012)\n====================================\n- Preserve GET parameters for container_suffix redirects\n- Allow custom FURLs via URL rewriting again\n- [#7427] Fix request_method_strict with FURLs off\n- Add ability to extend manager session by relogging in without leaving manager screen\n- Add better handling for AJAX exceptions, displaying AJAX errors\n- [#7649] Prevent E_NOTICE when using ago filter within <1sec difference\n- [#7568] Add JSON to default content types\n- [#7549] Open new window for phpinfo in system info page\n- [#7531] Add manager setting for first day of week in datepicker\n- Flip page title on manager pages for easier readability in browser tabs\n- [#7543] Add extra sanity checks for ellipsis output filter\n- CLI upgrades not loading MODX config data\n- [#7652] Sessionless contexts allowing anonymous access to unpublished resources\n- [#7610] User.sudo field invalid for sqlsrv\n- [#7619] Fix issue with TV FC rules and template constraints\n- [#7613] Add ability to duplicate user\n- [#7590] Fix lazy loading errors in xPDO layer\n- [#7608] Prevent ttl=0 set on modDbRegister from expiring immediately\n- Add wizard for User Group creation to speed up ACL workflow\n- Add Context policy for proper managing of access to non-mgr Contexts\n- Add wizard for Resource Group creation to speed up ACL workflow", "MODX Revolution 2.2.1-pl (April 3, 2012)\n====================================\n- Override modAccess->getOne for Principal aggregate\n- Add GroupPrincpal/UserPrincipal aggregates to modAccess\n- [#7387] Add New Category button to Element tree toolbar\n- [#7518] Fix issue that prevented absolute URLs in media-source bound TVs\n- [#7521] Allow filtering of usergroup by request on users page\n- Add assets_path field to modNamespace\n- [#7447] Change default root node name of Files tab to \"Media\" to prevent confusion when a non-default source is selected\n- Drop no-longer used, deprecated modAction.parent field\n- [#7503] Change Duplicate Values text to Duplicate Resource Values to clear up intended behavior\n- [#7499] Fix DOM ID issues with Quick Update when multiple windows are loaded\n- [#7500] Make consistent positioning of published checkbox in quick update and normal edit page\n- [#7491] Prevent Media Source dropdown from showing in MODx.Browser when loaded from a TV\n- [#6894] Move Import button on Access Policy and Access Policy Template grids to top toolbar\n- [#7391] Fix UI error causing resource group checkboxes on TV edit page to not render correctly\n- [#7481] Fix issue with reloading resource when changing templates and the context alias cache\n- Add \"sudo\" user attribute, which bypasses access permissions for said user; upgrade to 2.2.1 makes Super Users in Administrator group sudo users\n- [#7445] Fix issues with TVs not respecting Resource Groups limiting access\n- [#7446] Added extra checks to protect against parse errors with :then and :else output filters\n- [#7455] Fallback to TV name if caption not found when displaying TV inputs\n- [#7456] Fix for minify not modified status in fastcgi environments\n- [#6931] Workaround for template changing issue on servers that have misconfigured date_timzeone setting\n- [#6687] Fix duplicated OK buttons in MODx.Console in certain situations\n- [#6501] Fix SuperBoxSelect selections spanning multiple rows\n- [#6496] Fix quick edit modal windows for elements on smaller screens.\n- [#6864] Fix rare issue where primary group is not set for user, and custom dashboard for their group does not propagate\n- [#7011] Prevent infinite recursion error in modElement::isStaticSourceMutable\n- [#7333] Prevent error when id is undefined in resource edit controller\n- [#7364] Add setting to set default sort field of MODx.Browser view\n- [#7363] Check for this.stateful in MODx.tree.Tree::_saveState\n- Add missing index to modSession.access\n- [#7357] Prevent viewing of Profile if user does not have change_profile permission\n- [#7322] Fix issue where certain regions were not able to be hid via FC; clarified FC set labels\n- [#7362] Fix issue with conflicting FC Sets when User belongs to more than one User Group with a Set\n- Update to xPDO 2.2.3-pl\n- Prevent fatal error if invalid class_key is passed to Resource edit/create page\n- [#7052] Prevent username/host/dbname from being set as a system setting placeholder\n- [#3860] Fix session issue with modUser joinGroup/leaveGroup methods\n- [#7315] Standardize default sorting for User Group access grids\n- Fixed ellipsis filter to not cut off html tags in property\n- [#7326] Fix inability to unset a TV's Input Option Values field\n- [#7306] Sanity check for reload data for resource groups when changing template of new resource\n- [#7279] Handle edge case where processor classes might already be loaded with CRCs causing issues with runProcessor\n- Add dashboard name to dashboard title\n- [#3818] Add UI/processing to set response code for weblinks\n- [#7061] Prevent Static Element access to the core/config/ directory\n- [#7088] Tweak column widths for settings grids\n- [#7102] Improve memory_limit checks to properly check for values that are not formatted to PHP standards\n- [#7191] Fix invalid api doc link in link_tag_scheme description\n- [#7194] Fix issue where save button did not enable when reordering groups on user edit screen\n- [#3818] Change modWebLink default responseCode to 301\n- [#6611] Fix issue where MODx.Browser did not sort files by name by default\n- [#7070] Do not overwrite user changes in default media sources during upgrade process\n- [#7066] Allow search locally in Package Management if cURL is not installed\n- [#7063] Fix issue with retreiving Element Media Source cache data\n- [#7036] Fix issue with multiple grid store loading when searching\n- Allow for non-PHP Dashboard File Widgets that are just HTML files\n- [#6711] Fix issue with using MODx.Browser with file nodes and clicking loading edit page\n- [#6936] Add sanity check for database tables getlist processor if user did not grant SHOW TABLES permissions for sql\n- [#6942] Add missing resource duplicate ACL permission description lexicon string\n- [#6970] Reload error log page after clearing too large error log file\n- [#6956] Fix wrong groupname for OnMediaSourceDuplicate plugin event\n- [#7013] Fix issue where modUser->getUserGroupNames was buggy with non-self users\n- [#6960] Fix rendering issue when tree_root_id is set\n- [#7031] Ensure setting from addr in modMail sets return-path as well\n- [#7010] Add in rootId config option for MODx.Browser mgr widget\n- [#6874] Fix issue where duplicating a TV did not copy Media Source relationships correctly\n- [#6582] Fix clear cache checkbox persistence in Resource page when reloading via Template change\n- Add modX::getInstance() factory method\n- Allow for MODX tags within Media Source properties\n- [#5410] Add lock_ttl to System Settings for controlling ttl for resource locks\n- [#6575] Ensure that downloads of packages work behind proxies if allow_url_fopen is on\n- [#4879] Add language selector to login page\n- [#6826] Add activate/deactivate to context menu for Plugins in tree\n- [#6509] Fix minify issue in windows environments due to doc root pathing\n- Fix CSS for active tabs in mgr in IE\n- Prevent ENTER key from firing save in textareas in various modals\n- [#6712] Fix issue with Resource Group tree being limited to 10 groups\n- Bypass modSystemSetting->clearCache() when OPT_SETUP is true\n- Allow display of custom messages from form processors\n- Fix issue with extra slashes in URIs\n- Add ability to reload permissions for all authenticated users\n- [#6651] Add properties field and API methods for modResource\n- [#6613] Ensure page redirects if removing Element via tree that is currently being edited\n- [#6608] Fix search text in package management when doing empty search\n- [#6633] Ensure change password fieldset checkbox toggles dirty status for user form\n- [#6567] Fix Suhosin check to disable compress_js setting\n- [#6587] Fix issue with combobox rendering in editable grids by providing combocolumn xtype for proper data rendering\n- [#6583] Fix duplicate upload_files values\n- Prevent editing and deleting of core standard Roles", "MODX Revolution 2.2.0-pl2 (January 4, 2012)\n====================================\n- [#6564] Fix issue where save button on New Resource does not work due to JS DOM error\n- [#6470] Fix issue where Media Sources could not be protected on new installs only", "MODX Revolution 2.2.0-pl (January 4, 2012)\n====================================\n- [#6559] Fix issue with save btn on resources not enabling after template change\n- Better handling of dynamic lexicon topic adding and deprecated manager controllers\n- [#5905] Refactor new package versions to run ACTION_UPGRADE\n- [#6120] Improve static element behavior with immutable sources\n- [#6551] Fix issue where ID instead of name of Template showed on resource combo\n- [#6509] Fix minify issue when DOCUMENT_ROOT is a symlink\n- [#6546] Reposition setting grid filter dropdowns to clarify behavior\n- [#4146] Fix issue where Content Types were always binary when created\n- [#6470] Fix issue where Media Sources could not be protected due to missing reference in principal_targets setting\n- [#6520] Fix issue with Quick Create Resource and default settings\n- [#6510] Fix minify issue with virtual dirs inside the document root\n- [#5229] Fix issue where changing parent did not reload Resource edit page\n- [#6513] Better handling for large error.log files in mgr\n- [#6519] Ensure JS config gets working context config\n- [#6507] Add missing Media Source plugin events\n- [#6505] Remove htmlentities on date output filter\n- Allow PDO driver options to be defined in MODX config\n- [#6383] Add index.php to minify paths in mgr templates", "MODX Revolution 2.2.0-rc-3 (December 22, 2011)\n====================================\n- [#6247] Fix additional minify issues with CMP controllers in MODX_ASSETS_PATH\n- [#6428] Fix improperly designated tooltip and UI for create namespace window\n- Fix various regression issues with rename/delete files/directories in the Files tree\n- Ensure hideFiles property works for the files tree\n- [#6383] Add index.php to minify paths\n- Prevent TVs tab from showing in Resources if the only TVs are of type \"hidden\"\n- [#6413] Fix missing date_timezone setting description\n- [#6297] Prevent invalid characters in property set names\n- [#5997] Fix issue where components dirs were being created in assets with non-standard assets directory paths\n- Fix issue where resource ID was not being passed to FC rule checks\n- [#6417] Fix issue with modResource class_key being incorrectly set\n- Adjust modResponse contentType loading to allow overriding in custom resource classes\n- Fix critical timezone issue introduced for [#6077]", "MODX Revolution 2.2.0-rc-2 (December 16, 2011)\n====================================\n- [#3033] Add method to reload Context data in same request\n- [#6372] Add explicit resource_duplicate permission for duplicating a resource\n- [#6364] Fix incorrect lexicon reference in package versions grid\n- [#6365] Add manager_login_url_alternate setting which allows for setting a custom manager login URL\n- [#6077] Override PHP default timezone via System/Context Settings\n- [#5709] Fix issue where drag/drop in left trees did not work when package management was open\n- [#6153] Prevent enter key from sending Message when typing in messages page\n- [#6349] Properties can now belong to areas, and are grouped in grid by area\n- [#6344] Fix various pathing issues when drag/dropping files into content\n- [#5941] Add anonymous Load Only ACL when creating contexts\n- [#6247] Fix minify issues outside of $_SERVER['DOCUMENT_ROOT']\n- Improve skipFiles attribute for file media sources to allow MODX tags and hiding directories\n- [#6336] Fix error when updating property via window in media source properties grid\n- Fix various issues with permissions and ACLs on Media Sources\n- [#6306] Fix issue with close button always prompting changes made when changes may not have been made\n- [#6317] Fix issue with combo editor rendering in grids\n- [#6307] Save button now properly resets to disabled after save\n- [#6313] Fix issue with renaming content field label on derivative resource types\n- [#6084] Fix upgrade from 2.0.x releases\n- Add OnManagerPageBeforeRender and OnManagerPageAfterRender events\n- [#6207] Prevent overwriting static element file content when changing a static source\n- [#6255] Escape html tags in readme, license and changelog files for downloaded Packages\n- [#6096] Fix more issues with Resource reloading after changing a template by making the Resource Access grid local\n- [#5418] Add ability to export/import Access Policies\n- Add ability to import/export Policy Templates, as well as a base export/import processor class\n- [#6242] Actions on regular Resources break with Custom Resource Class extended fields\n- [#6096] Fix issue where reload token in Resource create would not allow save after validation\n- [#6238] Fix rendering issue when opening multiple quick create resource windows at once\n- Fix various issues with TV input and output renders by properly objectifying them into base abstract classes\n- [#5763] Allow for 3rd-level deep category nesting\n- [#6215] Fix issues with derivative resources and non-standard manager themes\n- [#6237] Add ability to sort users by active status in mgr grid\n- [#6197] Refresh old and new context caches when moving Resource\n- Update to xPDO 2.2.1-pl\n- [#6080] Fix revert to default properties on Source Properties grid\n- [#6204] Fix issue where multiple languages could not be loaded per page in the lexicon\n- [#6196] Ensure that MODx.Browser view updates when changing a media source from dropdown in tree\n- [#6198] Fix issue with saving user groups on a new user that caused duplicate role saving\n- [#6159] Implement OnBeforeUserActivate, OnUserActivate, OnBeforeUserDeactivate, and OnUserDeactivate events\n- [#6063] Add extra settings and checks to allow for better handling of manager CSS/JS minification on servers that do not allow DOCUMENT_ROOT access\n- [#6147] Fix element processors not firing proper events and passing wrong variables to plugins.\n- [#6060] Fix issue where resources were getting class_key of modResource rather than modDocument\n- [#6030] Fix issue where alt attribute was duplicated on image output renders\n- [#6122] Clarify text for removing a dashboard widget from a dashboard\n- [#6124] Fix issue where element associations of various elements were not saved in respective create processors\n- [#6145] Allow sorting of plugin events by enabled flag\n- [#6065] Fix issue with missing paths in certain environments for new installs in setup\n- Fix provider select window width in Chrome/Windows\n- [#6081] Fix issue in modFileMediaSource that prevented source properties from being read in certain processors\n- [#5141] Remove dependency for navbar.tpl in manager templates\n- [#5760] Fix memberof filter if user is not logged in\n- [#6090] Fix issue with removing Content Types in 2.2-rc1\n- [#6088] Fix issue with :date output filter and umlauts\n- [#6093] Make for easier translations of Element context menu items\n- [#6099] Fix incorrect index name for modWorkspace", "MODX Revolution 2.2.0-rc-1 (November 17, 2011)\n====================================\n- [#6019] Configure log_level, log_target, and debug via Settings\n- [#4798] Resource create/edit: Template can be switched without saving\n- Update to xPDO 2.2.0-pl\n- [#6039] Fix issue where Resources could be improperly dropped into the right tree in the Resource Groups screen\n- [#5715] Fix issue with resetting of header in Element panels\n- [#6025] Fix issue with renaming checkbox fields via Form Customization\n- [#5697] Fix issue with allow_multiple_emails in user creation\n- [#121] Add option for Elements to pre-process default property/property set values\n- [#6017],[#2774] Add more Permissions to Administrator policy for managing security functions\n- [#5064] Fix issue where access_permissions Permission was required for creating new users\n- Improve Package Management UI\n- Add modManagerController::addLexiconTopic for easier adding of lexicon topics dynamically within mgr controllers and dashboard widgets\n- [#6009] Add ability to hide left-hand trees when rendering a Dashboard\n- [#6007] Stop upgrade from overwriting session_cookie_path system setting\n- [#5998] Add \"Create File\" option for stream-based media sources\n- [#4794] Add custom Permissions for restricting creation of core derivative Resource Types\n- [#4958] Add Resource ID to node of Resource in Resource Groups tree\n- [#5434] Change manager page title to use site_name as prefix instead of MODX\n- [#4875] Add ability to download file from Files tree\n- [#5997] Fix issue where in advanced installs with moved web path, assets directory is improperly created\n- [#5990] Fix issue where content types were not listable in Resource dropdowns\n- [#232] Enable option to render target URL for WebLinks\n- [#5963] Fix issue with Static Elements and their Source being None\n- [#5936] Fix issue where Quick Update Resource was too high on smaller screens\n- Fix issue with phpThumb and zoom crop\n- [#5983] Fix adding/updating a provider window duplicating \"username\" field.[#5948] Ensure that menu item for Change Profile is added on build\n- [#5985] Fix updating a provider not showing username\n- [#5978] [ReUp] [#5978] Fix missing fields/tabs in actions XML causing issues with form customization on resource/create\n- [#5938] Optimize modResource->getTVValue() using parser source cache when available\n- [#5973] Prevent empty user groups being loaded for anonymous users\n- [#5962] Fix phptype in modContextResource.resource field definition\n- [#5050], [#5366], [#5781] Various xPDO Database Caching Fixes (xPDO 2.2.0-rc2)\n- [#4830] Prevent removal of Content Types that are in use\n- [#5293] Prevent drag/drop from Resource Group tree to Resource tree in Resource Group page\n- [#4433] Validate paths in setup for trailing slash\n- [#564], [#4506] Make Workspace path portable by allowing path setting replacements\n- [#5086] Fix issues with Package Management when open_basedir is in effect\n- [#4947] Adjust ensuring of admin access to context to only needed policies\n- [#5078] Have default resource field context settings, such as default_template, respected in Quick create\n- [#5909] Allow blank extensions in Add Content Type window\n- [#5931] Fix code that prevents easy renaming of assets directory with package management\n- [#5841] Properly color active state for tabs in mgr ui\n- [#3287] Fix issue with dob User field in editing panel in mgr\n- [#5060], [#5043] Fix issue with openTo and TVs for MODx.Browser\n- [#3396] Allow MODX_API_MODE in mgr context\n- [#4230] Add ODF and OOXML to default uploadable file types setting\n- [#5315] Use automatic_alias behavior when updating site_start regardless of setting\n- [#3535] Fix issue with tree_default_sort not being respected on the resource tree\n- [#5892] Add for default_media_source setting for specifying the default media source for a site\n- [#5896] Make console window always closable\n- [#5757] Allow text in grids to be selectable\n- [#5471] Add publishing options to Duplicate Resource window\n- [#5879] Ensure html tags are stripped on titles in the Resource edit view\n- [#5855] Ensure if no parents are specified, resourcelist input option works as expected\n- [#5852] Fix issue where input options are wiped on quick update TV\n- Add showNone option to source/getlist processor\n- [#5619] Enable modElements to store content in external files\n- [#5856] Implement ability for derivative Resource types to have their own translatable name\n- [#4726] Implement server-side state provider for modExt to fix size problems with cookies\n- [#5860] Fix FC SQL error when user is in no groups\n- [#5843] Add required asterisk to required Element fields\n- [#5723] Add Media Source tab to User Group Access screen\n- Change \"Cancel\" references to \"Close\" for clarity\n- [#4566] Fix online users manager dashboard widget grid\n- [#5809] Change \"Remove\" to \"Delete\" where appropriate to clarify language\n- Refactor processors to be class-based\n- [#90] 301 Redirect id method requests when request_method_strict is not enabled\n- [#90], [#5676] Improvements to strict routing with friendly_urls\n- [#5323] Add system events for moving Resources in and out of Resource Groups\n- [#4610] Add locale system setting for setting locale in MODX\n- Add HTML5 local caching as a toggleable option for manager ui\n- [#5788] Fix content not output to browser until after shutdown function\n- [#5777] Fix validation of TV names against Resource field names\n- Add ability to install and upgrade MODX from command line\n- [#5745] Ensure all core passwords are not transmitted through MODx.config JS array\n- [#4304] Add default_content_type Setting for setting the default Content Type for Resources\n- [#2735] Ensure menu permissions are checked for mgr action if action has menu associated\n- [#4606] Clarify connectors language in setup\n- [#5561] Add search toolbar to packages grid\n- [#5587] Fix issue with dashboard widgets and caching\n- [#5453] Add ability to disable forgot password on manager login screen\n- Add batch remove to Namespaces grid\n- [#5671] Add :toPlaceholder, :cssToHead, :htmlToHead, :htmlToBottom, :jsToHead, :jsToBottom output filters\n- Add delete user button to user editing page toolbar\n- [#5542] Add ability to drag/drop files and folders in the Files tab\n- [#5665] Remove console.log debug references in JS\n- Add Media Sources, which allow abstraction of file management in MODX\n- [#2737] Centralize logic for changing Context of modResource Children\n- [#5068] Move token check for new resources below error validation in processor to prevent bogus duplicate resource issue\n- [#4945] Remove weblink content maxlength restriction\n- [#5270] Enable container drag 'n drop in Extended Fields tree\n- [#4790] Add support for comment tag token, e.g. [[- comments here]]\n- [#5539] Add back in compress_css/js for allowing toggling of js/css compression in manager\n- [#5556] Enable connection pooling with master/slave support\n- [#5499] Ensure modFile create returns boolean\n- [#5501] Add sanity checks on FC rules renameTab and hideField\n- [#5505] Fix issue with dropdowns in Fx5\n- Enable modTag elements to accept property sets\n- Enable modElement->getPropertySet() to merge @propertyset in name with property set specified in setName parameter\n- Allow modParser->getElement() method to accept @propertySet in name parameter\n- Prevent modParser->parsePropertyString() from trimming all backticks at beginning and end of string\n- Improve parser efficiency by returning results of nested tags if elementOutput is null|false\n- [#5392] Fix bug where policy template descriptions were not translated\n- [#5377] Fix modParser->isProcessingTag() bug preventing filtering on placeholder tags\n- Pass content by reference to OnParseDocument event\n- Add message_key and json message_format option to system/registry/register/send processor\n- Allow raw messages to be returned from system/registry/register/read processor\n- Add include_keys option to modRegister implementations\n- [#5336] Prefix non-core actions in the MODx.action JS object with their namespace\n- Avoid setting description to null in element/propertyset/create processor\n- Improve modX->logManagerAction to avoid attempts to insert NULL values\n- Accept null options in modHashing->__construct()\n- [#4607], [#3463] Add rank field for contexts to allow custom sorting in tree, fix issues with context/resource dragging and dropping and ensure context name validation rules are consistent\n- Improve UI of User's groups to allow for assigning ranks to User Groups for a User\n- Add Custom Dashboards and Dashboard Widgets\n- [#4871] Fix Access Permissions not being copied when duplicating a context\n- [#4382] Forgot Manager Password now lookups using username to prevent issues when the 'allow_multiple_emails' system setting is enabled\n- Fix rendering of combo boxes in element properties\n- Add ability to select Primary User Group for User\n- [#4637] Fix RTE checkbox not saving correctly when using Quick Create Resource\n- [#5268] Add search toolbar for Resource tree\n- [#4080] Add Content Type and Content Disposition to Quick Create/Update Resource\n- [#5250] Add check for cURL in Package Management\n- [#5204] Add search by parent to mgr search page\n- Added much better handling for custom resource classes; deprecated custom_resource_classes setting\n- [#4601] Ensure children of protected Resources inherit by default their parent's Resource Groups in create UI\n- [#4016] Update description text in grid when adding/updating element properties without need for page reload\n- [#2860] Fix 'Sent On' date when viewing an expanded message\n- [#4984] Ensure tree highlighting of currently edited resource/element/file works consistently\n- [#2638] When updating an element's category, ensure old treenode is removed\n- [#5139] Fix issues with MODx.Browser and file/image TVs in other contexts\n- [#4958] Add IDs to Resource Groups in RG tree\n- Add ability to rename Resource Groups\n- [#5185] Improve core package already extracted validation for upgrades\n- Update xPDO and regenerate schema to get new maps of derivative classes\n- [#5195] Change TV value fields from TEXT to MEDIUMTEXT (mysql)\n- [#5141] Add ability to override specific controllers/templates in a custom manager theme w/ fallback to default\n- Add modResource::getControllerPath method for better abstraction of derivative resource types\n- Add show_in_tree and hide_children_in_tree fields to modResource for better support with custom Resource types\n- Abstract all manager controllers to classes to improve usability, testing and creation of controllers", "MODX Revolution 2.1.3-pl (July 21, 2011)\n====================================\n- [#5295] Fix parents input option for Resource List TV when 0 is specified\n- [#5190] Fix includeParent input option in Resource List TV\n- [#5222] Fix nested cacheable tags being skipped in non-cacheable tags\n- Fix delegateView recursion in Resource controllers on Windows\n- [#3966] Fix double slash issue in file paths when dragging into resource content from the Files tree\n- [#4565] Fix issue with Resource tree sorting\n- [#5026] Make directory tree in MODx.Browser instance launched from Files tab consistent with other instances of MODx.Browser\n- [#4960] Prevent method declaration error for modPHPMailer::reset()\n- [#3716] Ensure consistent handling of combo-boolean property values in the database\n- [#4586] Improve number detection for Radio and Checkbox TV values\n- [#5196] Unset uri_override when duplicating creates a duplicate uri", "MODX Revolution 2.1.2-pl (July 6, 2011)\n====================================\n- Fix issue with modUser::getSettings pulling a deprecated alias\n- Update to xPDO v2.1.5-pl\n- Implement DocBlox for documentation generation\n- [#5168] Fix element and tv permission queries for SQL Server\n- [#5146] Fix issue with Firefox and button widths\n- [#5164] Fix possible issue if a TV is stranded to a non-existent category\n- Update ExtJS to 3.4.0\n- Set a default session_gc_maxlifetime to avoid frequent logout issues\n- Refresh modExt trees when drag operations fail\n- [#4918] Limit save permission check to modified nodes in resource/sort processor\n- [#5065] Fix 404 error with cross-context symlinks when cacheable\n- [#5152] Fix nested non-cacheable tags from being cached in modResource->_content\n- [#5145] Update config check on dashboard to show correct core path if core is moved\n- [#5112] Add Settings for adjusting behavior of Context sorting in Resources tree\n- [#4341] Properly clarify text and function on Resource Tree context menu options for view/preview\n- [#5046] Fix issue where parent could not be changed for new resources via Form Customization\n- [#5112] Sort contexts by name ascending in the Resources tree\n- [#5102] Fix error removing older transport package versions\n- [#4940] Fix issue where CMPs that did not use ExtJS could not scroll\n- [#5097] Ensure browser toolbar button does not show when MODx.Browser is already open\n- [#4953] Improve modx.console.js to avoid message loss\n- [#4836] Make sure modFileRegister sorts messages before reading\n- [#5087] Fix issue where class_key was not respected when using Add Another in UI\n- [#260] Implement on-the-fly compression for css/js in manager\n- [#3464] Set xPDOTransport::ACTION_UPGRADE for already installed packages\n- [#4955] Package management actions refresh packages cache partition\n- [#5071] (SqlSrv) fix/refactor Plugin Events getList processor\n- [#2870] Change internalKey default value to NULL\n- [#5072] Add missing primary key index to modEvent\n- [#5005] Fix incorrect label on introtext field in weblink panel\n- Remove session_cookie_lifetime variable when logging out of context\n- Remove legacy SESSION variables and dependencies\n- [#4703] Remove user settings when logging out of a Context\n- [#2566] Improve tv output render url to take resource pagetitle when using resourcelist TV type\n- [#5020] Improve per page field on grids to handle ENTER key\n- [#5021] Improve modUser::joinGroup to check to see if user is already in group\n- [#5025] Fix issue where duplicate resource window did not show duplicate children option\n- [#5007] Only create Lexicon Entries for Settings if they are specified\n- [#5006] Fix issue with updating a policy template with no permissions\n- [#5001] Fix issue with modauth, wctx and RTE browser", "MODX Revolution 2.1.1-pl (June 1, 2011)\n====================================\n- Make modauth calculation independent of session_id\n- Ensure login/logout processors do not add Contexts with empty keys\n- [#3145] Ensure mail_smtp_pass and proxy_password System Settings use password xtype\n- [#4360] Show current context name on MODx.Browser window for reference\n- [#4881] Fix issue where modx-combo-language was missing from system setting editing screen\n- [#4896] Fix issue where New Category window is not cleared on each load\n- [#4934] Fix missing lexicon load call in package download processor\n- [#4927] Gray out disabled plugins in elements tree, italicize locked elements\n- [#4921] Ensure Category names are not ever capitalized when displayed as tabs\n- [#4865] Fix PDO error caused by missing charset for new MySQL installs on PHP 5.3.6+\n- Improve modSessionHandler and add Settings for advanced configuration\n- [#4750] Fix various issues with duplicating Resources, such as new name not prefixed and incorrect menuindex\n- [#4910] Fix bug where ResourceList TV type could not be marked as required\n- [#4915] Fix UI glitch when creating both an Access Policy and its Template on same page load\n- [#4916] Fix issue where cache clear checkbox was always being cleared on template save\n- [#4884] Remove PHP4 constructor on modRegister\n- Harden connector CSRF security by tying user session modauth to prevent hijacking of session if modauth is known\n- [#4863] Fix issue where template changing causes unintended alias\n- [#4854] Fix bug that caused update/rename file to be missing in Files tree context menu\n- [#4851] Improve safe_mode check in setup to check for non-boolean values\n- [#4856] Fix issue with MODx.Panel instances that have no textfields, causing scrollbar issues\n- Fix issue where MODX version was not being sent to provider during package update\n- [#4850] Fix issue with MODx.Window instances that have no textfields", "MODX Revolution 2.1.0-pl (May 24, 2011)\n====================================\n- [#4818] Fix SqlSrv query errors related to TVs\n- Add modX->$sourceCache data to cached Resources\n- Fix loading of cached Resource content and processed flag\n- Fix caching of empty policies for Resources\n- Fix modSessionHandler->write() cache flag if cache_db_session is not enabled\n- Update xPDO to v2.1.4-pl for cache_db bug fixes and improvements\n- [#4832] Fix issue with moving resource parent to root\n- [#4827] Make sure editing a file sends the working context along\n- Fix erroneous call to OnDocUnpublished event that should be OnDocUnPublished\n- [#4796] fix New Resource page heading during typing of page title\n- Add Usergroup filter to users grid\n- [#4785] Fix preview of files in left tree in non-standard contexts with absolute filemanager_ settings\n- [#4473] Add other common file types to upload_files system setting\n- [#4539] Fix issue with stretching of quick update chunk and small screen resolutions\n- Automatically focus cursor to first textfield on windows in mgr\n- [#4738] Fix issue with inconsistent results in resourcelist TV\n- [#4441] Fix FC issue when parent is constraint and trying to change default template\n- [#4764] Fix issue with timestamp display on manager log page\n- [#4680] Fix javascript error when typing Template name\n- [#4681] Fix path issue which was causing 404 errors in the manager, IE 7-9\n- [#4439] Add parentheses to list of disallowed password characters in installer\n- [#4669] Fix button target size to make it more responsive to most clicks\n- [#4625] Fix sizes of buttons and submit inputs in installer - IE 8 and 9\n- [#4617] Fix custom values not being shown on Context Installation page during Advanced Upgrade\n- [#4605] modX->switchContext() now checks load permission via Context ACLs\n- [#4595] Fix display of modified/accessed times on Edit File page\n- [#4594] Fix last login time displayed in Info block of Manager welcome page\n- [#4470] Fix frozen URI not displayed when editing resource\n- [#4572] Fix installer error log filenames (characters not allowed in Windows filenames)\n- [#4585] Fix database connection processors in advanced upgrade\n- Update xPDO to v2.1.3-pl\n- [#4567] Remove calls to xPDO->log() in xPDOCacheManager->writeFile()\n- [#4557] Minor fixes on Installer Options screen for Traditional package\n- [#4556] Fix js error on Welcome screen of Traditional package's installer\n- [#4076] Fix Edit/Quick Update context menu items in protected categories\n- Fix Context Access query broken in RC4 changes for #4502", "MODX Revolution 2.1.0-rc-4 (April 29, 2011)\n====================================\n- [#4543] Fix preview URLs when FURLs are turned Off\n- [#4537] Trigger refreshURIs when related settings are modified\n- Have modAccess*::loadAttributes() check access_*_enabled settings\n- [#4502] Enable custom targets in modUser->loadAttributes()\n- [#3692] Add policy checks for new_document_in_root and add_children to resource/sort processor\n- [#4526] Additional fixes for output filters on placeholders\n- [#4504] Ensure UserGroup ACLs are deleted along with UserGroups\n- [#4507] Fix usergroup description not being set when created\n- Change modResource->isDuplicateAlias() to return id of duplicate Resource\n- [#4495] Add duplicate URI check to resource/publish action\n- [#3857] Fix placeholder processing when output filters applied\n- [#4362] Fix path issues with Static Resources and base_urls of /\n- [#4074] Require list permission on Context for Resource searches\n- [#4439] Do not allow invalid characters in username / password\n- [#4485] Fix issue with scrolling on drag/drop Element Properties window in small resolutions\n- [#4352] Fix failedlogincount / user blocking logic in login processor\n- [#4373] Fix issue with htmltag TV output render and empty values\n- [#4374] Fix issue with updating files in the edit file page\n- [#4024] Fix issue with LocalProperty grids not rendering list type properties display values correctly\n- [#4400] Trim whitespace from Namespace paths when adding/updating them\n- [#4434] Fix issue with edit panel on contexts\n- [#4372] Fix View button not getting URI change after Save Resource (all Resource types)\n- [#4369] Ensure Save button is active after Template change on Weblink, Symlink, Static Resource\n- [#4471] Set Resource alias properly on update\n- [#4469] Guard against inadvertent creation of duplicate New Resources\n- Add options to configure cache file writing attempts when exclusive locks fail\n- [#4464] Prevent unnecessary TV queries on uncached Resources\n- [#4422] Fix problems updating Boolean settings (System, Context, User)\n- [#4453] Fix File Browser when paths contain \"n_\"\n- [#4447] Fix ACL grid in Edit Context view\n- [#4438] Fix error logging to custom log targets defined by array\n- [#4399] Fix IE8 javascript error on Resource and Element update pages", "MODX Revolution 2.1.0-rc-3 (April 11, 2011)\n====================================\n- Fix invalid merge retained in master branch from 2.1.0-rc-1\n- Fix modResource::save() to refresh uri if isfolder field is dirty.", "MODX Revolution 2.1.0-rc-2 (April 11, 2011)\n====================================\n- Refresh resource tree if resource's parent has changed\n- [#4327] Fix bug with auto-publishing\n- Fix positioning of right panel in mgr UI to make tree/nav static and isolated from scrolling of right panel\n- Make alias required field in resource/create processor when friendly_urls is on but automatic_alias is off\n- [#4280] Fix issue where transport package could not be removed if transport files were removed\n- [#4281] Utilize modX::sourceCache in modParser::processElement()\n- Fix issues with Namespace grid related to context menus and search\n- [#4257] Fix issue where context menus did not show in Contexts grid\n- [#4288] Fix issue with resource preview context menu\n- [#4279] Fix undefined collResources notice with empty Contexts\n- [#3119] Fix modResource->getAliasPath() to use id if set\n- Upgrade MagpieRSS to 0.72 to fix issues with atom feeds\n- [#3623] Fix TemplateVarTemplate foreign key definition in modTemplate\n- Replace specific references to MySQL with more general language\n- [#4185] Change modx logo in mgr to new logo\n- [#4217] Add rank field to modUserGroupMember table\n- [#4271] Highlight currently editing Resource on tree\n- Fix issue with image/file TV and uploading in MODx.Browser when using a custom basePath TV\n- [#4270] Fix issue where images could not be removed when using a custom basePath TV\n- Add User Group related events\n- [#4260] Change title tag in mgr UI to reflect current page\n- [#4256] Add caption field to Quick Create/Update TV\n- [#4261] Change keyboard save shortcut to CTRL+S\n- [#4262] Ensure that FC rules htmlencode their tab/field labels\n- [#4243] Ensure that files that are read-only do not show save button; fix file tree opening\n- [#4244] Add backwards compatibility for Element properties of list type with older indexes\n- [#4236] Fix bug in Template combo that hid category name\n- Improve compression of images in mgr to reduce load times and core transport zip size\n- [#4232] Fix Output Options being ignored in TVs in 2.1.0-rc1\n- Add options to allow ACL queries to be disabled for Contexts, Categories, and Resource Groups\n- [#3941] Fix issue where Resource TV values were not copied when duplicating a Context\n- [#4202] Fix issues with file/image TVs urls/paths when using modx path placeholders\n- Fix sorting/display bugs on UserGroup ACL grids, add grouping for better visibility\n- [#4175] Add modRequest->getClientIp() for better IP handling\n- [#4217] Add rank field to modUserGroup\n- Update version to 2.1.0-rc-2\n- [#4173] Fix issues with math-related output filters and floats\n- [#4205] Ensure old modxcms.com provider is removed after change to modx.com provider\n- [#4220] Fix modX::makeUrl() when friendly_urls not enabled\n- [#4207] Fix issues with checkboxes and Form Customization rules\n- [#4013] Fix modX::_log() to pass target to parent::_log() properly", "MODX Revolution 2.1.0-rc-1 (March 28, 2011)\n====================================", "- Fix issue with properties and i18n in Element properties and in drag/drop box\n- [#4146] Fix issue where new Content Types were always created as Binary\n- [#291] Add principal_targets setting to allow custom ACLs to be loaded by MODX Principals/Users\n- [#99] Allow SymLinks/modX->sendForward() to forward to Resources in external Contexts\n- [#4147] Changing ContentType extension in grid not refreshing URIs\n- [#3967] Fix issue with running user create/update processors more than once in a session\n- [#3542] Hide Template Variables tab on Resource create/update pages if no TVs are present\n- [#788] FC Rules for TVs now display distinctly for create or update\n- [#1118] Add more help for User fields in manager editing page\n- [#2578] Fix issues with manager log view page where sorting was off and grid was not sortable\n- Fix issue where user-created FC tabs were not removable from a Set\n- [#4096] Fix Package Management archive issue when using mapped Windows drives\n- [#3785] Add category filter and search box to TV grid on Template panel\n- [#65] Make locked Resources be read-only rather than unviewable\n- Improve Package Management to show changelog, more supports information in package browser\n- [#4120] Fix issue where TV sort order is reset on Quick Update\n- [#4115] Fix issue with modPhpThumb and filenames with + signs\n- [#2719] Fix reset behavior on autotag/tag TV inputs\n- [#3586] Adjust improper text on Content Types page\n- [#2652] Fix issue where Element could be drag/dropped onto another Element in tree\n- Add ability to select a blank value for ResourceList TV input type\n- [#54] Fix issues with phpThumb and DOCUMENT_ROOT by adding a custom phpthumb_document_root System Setting\n- [#4122] Fix order of execution of validation and plugin events for Element processors\n- [#4105] Add Spanish translation\n- Refactor duplicate alias checks into duplicate URI checks\n- Cleanup deprecated code in Resource templates\n- [#3765] Ensure entries editedon values are set when editing a Lexicon Entry\n- Update ExtJS to 3.3.1\n- [#4073] Add session_name, session_cookie_path, session_cookie_domain as System Settings with blank default values\n- [#4077] Add resource_quick_create and resource_quick_update Permissions to restrict access to Quick actions on Resource tree\n- [#4050] Add tree_show_resource_ids and tree_show_element_ids Permissions to show/hide IDs of Resources/Elements in tree panels\n- Add username field to modTransportProvider, and send it and UUID to providers during transmissions\n- [#3641] Add base URL for Help links in manager for easier management and customization of URLs\n- [#3552] Fix issue causing list-xtype properties to be swapped when using drag/drop into field functionality\n- [#4069] Ensure that you cannot delete the last User in the Administrator user group\n- Add fix for ie9 to get tree nodes to work properly\n- Prevent Category ACL queries on Elements if no entries for current context\n- [#2601] Improve text and drag/drop for weblink/symlink content fields\n- [#3636] Fix issue with empty values on options in list/dropdown/checkbox/radio TVs\n- [#4024] Fix issue with display value not always showing for list properties in element property grid\n- [#4056], [#4041] Add xtype password, template, user, usergroup, etc to available xtypes for System Settings\n- [#3350] Improvements to bugfix for PHP bug 53632\n- [#4054] Improve select binding to be able to use Resource fields via placeholders\n- [#142] Add modResource.setTVValue API method\n- [#4021] Add system setting to allow setting of a custom favicon for the manager\n- [#3589] Fix issue with Static Resource paths when using custom filemanager_path\n- [#4040] Fix issue where Users were always created as active in mgr UI\n- [#4043] Enable drag/drop of users and groups in User Group tree\n- [#4052] Fix issues with element property import and invalid characters causing freezing in UI\n- [#4042] Fix issue in phpThumb base class preventing far property from working\n- [#4049] Add resource_tree_node_tooltip for controlling field in Resource Tree tooltip\n- [#3511], [#2964], [#3601] Fix issues regarding form customization and Templates by removing ajax loading of TVs in Resource panels\n- Consolidate JS for derivative Resource panels to allow to inherit from main Resource panel\n- Add context param to modx.getParentIds\n- [#3754] Ensure Resources can not have their parent set as one of their descendants\n- Add context param to modX.getChildIds\n- [#3612] Improve CDATA filter to not add spaces at beginning or end\n- [#3764] Add delete to actionbar on Resource edit panel\n- [#3585] Add description field to modUserGroup\n- [#3020] Improve trees to expand node on click if no href target is set for tree node\n- [#4006] Show children count rather than IDs on categories in element tree to lessen id ambiguity\n- Fix issue where Quick Create was not respecting unchecked setting checkboxes\n- [#3673] Add \"Save and Close\" button to quick update windows\n- [#3970] Ensure extension is lowercased before checking for allowed status when uploading files\n- [#3920] Ensure modPHPMailer resets replyTo and custom header fields\n- Add UI for managing Resource uri and uri_override fields\n- Remove all deprecated methods and variables scheduled for removal in next minor release\n- Change modxcms.com references to modx.com\n- [#3898] Prevent any non-integer being set in ?a= in mgr interface\n- [#3926] Ensure security/user/create processor can take in a class_key parameter to set class_key for SSO\n- Improve user processors event handling to allow for better SSO integration that can stop save/remove/update\n- Refactor password reset not to send password hash as activation key\n- [#325] Allow configurable user password hashing with PBKDF2 default implementation\n- [#3111] Fix bug causing unnecessary writes to Resource cache files\n- Update xPDO to v2.1.1-pl2\n- Add modResource.uri_override to allow a uri to be manually set and locked per Resource\n- [#3111] Add modResource.uri field to allow context maps to be regenerated in a single query\n- [#3859] Remove redundant check for php bug\n- [#3858] Fix javascript errors from FC hideField rule\n- [#2812] Add link_tag_scheme to define default scheme for makeUrl() call in modLinkTag\n- [#3111] Remove resourceListing, documentListing, and documentMap from context cache\n- [#3111] Cache refactoring with proper file locking, partitioning, and multiple format support\n- [#3111] Update xPDO to release 2.1.0-pl for cache improvements\n- [#3740] Add proxy support to modTransportPackage.class.php\n- [#3693] Fix reversed content-disposition logic on static resources\n- [#3427] Fix issue where User Settings were not respected with filemanager_path/url\n- [#3702] Ensure file/image TVs can have files drag/dropped onto them\n- [#3465] Add sanity check for non-object to log call in modAccessibleObject::_loadInstance\n- [#3615] Fix issue with modx->user->getResourceGroups, set resource groups in \"modx.user.{$id}.resourceGroups\" session key\n- [#3568] Fix double error->failure reference in resource/create processor\n- [#3425] MODx.Browser now loads directory of TV's current value on load\n- [#3481], [#3571], [#3304], [#3569] Fix issue with filemanager_path in non-web contexts\n- [#3009] Add ability to assign TVs to specific directories and base paths, limit file extensions shown\n- [#2679] Add Input Options to TVs, allowing TV inputs to be customized and tweaked", "MODX Revolution 2.0.7-pl (January 14, 2011)\n====================================\n- [#3472] Fix issue due to tree impr that prevented element saving success response\n- Improve loading of mgr pages by preventing trees from rendering until activated\n- [#3205] FC fixes: Ensure Resource Content field can have values set/renamed, that rules on create respect template, and that default values on create are set\n- [#3165] Fix issue where resource/updatefromgrid processor was missing published value if user does not have publish permission\n- [#2] Fix issue in user extended fields where subkeys in 2 separate containers DOM IDs conflict and prevent editing\n- [#3422], [#3374], [#3197] Fix issue with filemanager_url and Image/File TVs and their relative end result URLs\n- [#3201], [#177] Add modResource.leaveGroup, modTemplate.hasTemplateVar, modTemplateVar.hasTemplate\n- [#3350] Fix for PHP bug: http://www.exploringbinary.com/php-hangs-on-numeric-value-2-2250738585072011e-308/\n- [#3326] Fix issue where TV radio/cb options with value of 0 couldnt be selected\n- [#3329] Fix edit and cancel buttons on view resource page\n- [#3329] Clarify Preview link on Resource action toolbar to be more correct \"View\"\n- [#3347] Fix issue where renaming a file broke the browsing of directory tree\n- Fix issue where FC tvDefault rules, regardless of active state, are always run\n- Introduce pdo_sqlsrv support\n- Add database_dsn to config\n- Update xPDO to release 2.1.0-pl", "MODX Revolution 2.0.6-pl2 (January 6, 2011)\n====================================\n- [#3350] Fix for PHP bug: http://bugs.php.net/bug.php?id=53632\n- [#3347] Fix issue where renaming a file broke the browsing of directory tree\n- Fix issue where FC tvDefault rules, regardless of active state, are always run", "MODX Revolution 2.0.6-pl (December 20, 2010)\n====================================\n- [#3143] Fix lexicon grid search to respond to enter key\n- [#3144] Fix issue with reset password and @ being stripped\n- [#3142] Ensure whitespace is stripped from tags in tag/autotag TV types\n- [#3118] Ensure defaults are set in resource/create processor if values are not sent\n- [#3105] Improve memory_limit check in setup to accept integer values from PHP instances\n- [#3106] Add sanity check to resource create/update processors to disallow invalid Resource Group ID references\n- [#3038] Fix problems with filemanager_path settings and absolute URLs in image TV values\n- [#3039] Add symlink_merge_fields setting to disable modSymLink merge behavior\n- [#3103] Alter modSession data field to store more than 64Kb\n- [#3091] Add missing specific dom ID to profile change password panel\n- [#3096] Fix issue with exporting default properties not in a set from an element\n- [#3099] Fix FC rules to respect class_key constraints\n- [#3097] Fix extension_packages to support modx path placeholders, as well as new serviceClass and serviceName parameters\n- [#3085] Ensure Files tree only refreshes active node when creating/updating a file/dir\n- Improve the Permission dropdown and add window in AP Template page\n- [#3083] Fix Form Customization issue when Resource has a blank Template\n- [#3082] Fix Form Customization issue where cacheable and ID fields not able to be hidden/altered\n- [#3034] Fix error creating Resources in Contexts other than web\n- Fix issue with incorrect active permission total in Access Policy grid\n- [#3023] Fix issue where topmenu did not respect manager_language\n- [#3080] Fix missing placeholder in error message when attempting to create a duplicate Element\n- Add new header image to match new site\n- [#3078] Fix issue with htmltag TV widget properties when using = in its value\n- [#3079] Ensure GPC vars are not sent into $scriptProperties array in $modx->runProcessor\n- [#2983] Add sanity check to prevent plugins from firing if disabled (redundancy)\n- [#3057] Fix issue where parent change causes fail to save in UI\n- [#3076] Fix bug where manager returnUrl was not working due to [#2918] fix\n- [#3059] Ensure createdby is set on resource creation\n- [#3041] Fix missing lexicon entry in resource processors\n- [#3043] Fix invalid 200 response header on sendError()", "MODX Revolution 2.0.5-pl (December 8th, 2010)\n====================================\n- Change remove() to removePackage() in modTransportPackage\n- Fix issue with package setup-options attribute not loading forms\n- [#2932] Fix redirect issue after setup and on manager login page caused by [#2918]\n- [#2931] Fix issue where FC rules weren't applying if no UserGroup was set in a Profile\n- Ensure non-Resource FC rules are removed on upgrade\n- [#2918] Address XSS vuln in manager login that allows JS injection\n- Fix issue where // is stripped from filemanager_url http address\n- [#2902] Fix issue where Administrator policy ACLs in non-Administrator groups couldnt be edited\n- [#2915] Ensure UserGroups restriction is enforced in FC Profiles\n- Fix bug when editing FC profiles from a grid, issue where UserGroup wasn't respected\n- Ensure radio TV values still can select if default value is 0\n- [#2869] Fix issue with parent display text in Resource panel\n- [#2892] Fix problem creating folders on filesystem from file manager and browser\n- [#22] Allow SymLinks metadata to override target Resource metadata\n- Cache Resource ACL Policies with the Resource\n- [#2888] Fix problem with elementCache in modX::sendForward()\n- [#2610] Allow Elements to be created under a Category when a Category Policy is in effect\n- [#2869] Standardize initial parent combo value text on Resource edit page\n- [#2736] Colon character \":\" added to default FURL Alias Character Restriction Pattern\n- [#2889] Ensure that a new Resource gets an alias generated if auto_alias is On\n- [#2837] Ensure element properties import escapes <> and provide better error checking\n- [#2886] Ensure SimpleXML and XMLWriter extensions are installed when using FC Set import/export\n- [#2882] Add hidemenu_default setting for setting default hide from menus on Resources\n- Fix issue with derivative Resource types and FC rules\n- [#2858] Extra sanity checks to ensure md5 pw is never sent across get/getlist processors for Users, even if user has access level\n- [#6] Fix issue with RTL text in nodes in Resource tree\n- [#2873] Fix relativity of image urls in drag/drop and TVs when using various filemanager_path/url settings\n- [#2878] Ensure resource panel is marked dirty when drag/dropping into TV\n- [#2828] Fix issue with incorrect content field name for FC rules\n- [#2863] Fix order of execution issues with FC rules and default values\n- [#2874] Enhance User blockedafter/blockeduntil fields to accept time as well as date values\n- [#2529] Fix automatic publish/unpublish\n- Adjust FC rule ranks to properly account for prior FC rules that may affect FC constraints\n- Update xPDO to 2.0.0-pl release\n- [#2661] Fix Template getList processor to respect authority\n- [#313] Fix header error with binary modStaticResource downloads\n- [#206] Fix session bug with opcode caching systems like APC, WinCache, eAccelerator\n- [#2846] Add tag syntax to description hover text for resource fields\n- [#2849] Add ability to drag/drop onto TV fields\n- [#2848] Fix issue with file edit and base paths\n- [#2802] Ensure Category tab is hidden when all TVs are hidden in that Category\n- [#2779] Added Content Editor policy to default list of policies\n- [#2819] Fix bug in FC rules where parent constraint was not traversing up tree to inherit parents\n- [#2744] Fix bug with empty template and TV values\n- [#2841] Fix bug with File Edit page and modFileHandler reference\n- [#2839] Fix bug with failed login count not being updated\n- Add ability to view permissions inherited when viewing an ACL row in a grid\n- [#2834] Fix issue where constraint class was not set on new FC rules\n- [#2819] Fix issue with FC rules and execution order due to setting default templates, constraints\n- [#2830] Permit ability to change FC Set Template when editing a FC Set\n- [#2827] Fix issues related to FC upgrade with Rules with comma-separated names, differing constraints, and template setting\n- Fix issue related to #2625 with deferred tabpanel rendering that caused unpublishing when using Quick Update/Create\n- [#2825] Append idx to each item DOM id when using HTML tag tv output widget\n- [#2823] Add missing lexicon entry for TV output type\n- [#2817] Reorder System top menu for easier navigation\n- [#2820] Add DOM id to Profile page tabs\n- [#2814] Add longtitle, description, template to Quick Update/Create\n- [#2789] Add check to make sure safe_mode is off in setup\n- [#2565] Improve Quick Create/Update Resource to move settings into tab rather than fieldset\n- [#2807] Add tree_default_sort System Setting for configuring the default sort setting for the Resource tree\n- [#2803] Fix css issue with portal blocks on manager dashboard in Fx\n- Add new Form Customization UI, including Form Customization Profiles and Sets; much easier editing of FC rules\n- Fix issue with modInstallSmarty constructor due to Smarty upgrade\n- [#2799] Remove ext3 debug files to save space\n- [#2801] Fix bug with checkbox tvs without specified value options\n- Upgrade Smarty to 3.0.4\n- [#2782] Add changelog to Package View page\n- [#2782] Add ability to view changelog when installing a package via the \"changelog\" package attribute (similar to readme)\n- [#2770] Ensure email TV input type validates email\n- [#2776] Fix issue where context settings grid was not filterable\n- [#2790] Ensure \"number\" TV types restrict input to numbers only\n- [#2730] Fix rendering issue with policy template/group grids\n- [#2794] Allow TV URL output render to handle values that are straight Resource IDs\n- [#2741] Fix bug where Resource Group associations were not copied when duplicating a Resource\n- [#2746] Fix bug where email was sent in registration email rather than username\n- [#2733] Fix bug where Template Var associations were not copied when duplicating a Template\n- [#2742] Fix deprecated evtid reference in plugin duplicate processor\n- Fix various bugs with context settings and wctx param\n- Fix bug where modX::getDocumentChildrenTVars ignores docsort parameter\n- [#2743] Connectors using wrong permissions with processors\n- [#2758] Add modProcessorResponse class to better handle processor responses and error messages\n- [#2758] Add $modx->runProcessor($action,$scriptProperties,$options) to better handle processor execution; deprecated $modx->executeProcessor\n- [#84] Make distribution name available in manager\n- [#2666] Prevent sendRedirect() from preserving request parameters unless specified\n- [#2721] Fixed issue with per page items in MODx.grid.Grid that was incorrectly handling int value\n- [#2691] Fixed issue with duplicate aliases when duplicating a Resource\n- [#2506] Flag properties as dirty when importing from a file on properties grid\n- [#2592] Prevent cache files from being allowed in upload_files setting\n- Improved areas dropdown filter to include number of settings that have that area\n- [#2694] Fixed positioning and scrollbar issue in Fx with success status message on save\n- Added setting clear_cache_refresh_trees that allows you to toggle whether the trees refresh on site cache clear; defaults to false\n- [#2709] Fixed bug where Object-Template policies were unavailable to certain grids\n- [#2597] Fixed bug where Context Setting xtype and area are reset on grid save\n- Upgraded extension_packages setting to JSON for more options with packages and easier editing in Extras scripts\n- Fixed bugs relating to using filemanager_path in a separate context, as well as other bugs with context-specific settings in mgr\n- [#2496] Fixed bug that prevented icon from resetting when dragging Resources into a new parent\n- [#713] Prevent children resources from being prefixed with \"Duplicate of\" when duplicating a resource unless explicitly told to do so\n- [#2581] Fixed bug with resourcelist TV input type to handle resources from multiple contexts\n- [#2518] Added delay to allow FC rules to load before RTEs load to allow RTE TVs to be moved\n- [#2611] Added workaround for ExtJS bug with checkboxes/radios and an inputValue of string 0 that would prevent toggling\n- [#2512] Have remove setup/ dir checked by default if not using Git version of MODx\n- [#2699] Fixed loading issues with help panel on slow connections\n- [#2701] Fixed issue where description did not show until refresh when adding a new Permission to an Access Policy Template\n- [#2695] Postfixed Template to names of Access Policy Templates for clarity\n- [#2700] Fixed bug with Access Policy Template editor that reset values on save\n- [#2690] Renamed Administrator Access Policy Template Group to Admin\n- [#2563] Fixed chmod action on directories from File Tree\n- [#2693] Properly sort country indicies to properly display in dropdowns\n- [#2562] Added confirm dialog and success response for emptying recycle bin\n- [#2634] Ensured context key is changed when changing parent of a Resource via Edit Resource page if context is different for new parent\n- [#2631] Fixed issue when drag/dropping categories onto other categories in Element tree\n- [#2659] Fixed issue where action buttons were overlapping tabs on edit pages\n- [#2668] Fixed issue with FC rules and labels on checkbox/radio fields\n- [#2582] Fixed bug with orm tree preventing attributes on the root node\n- Fix bug in phpthumb allowing remote src parameters regardless of settings\n- [#2555] Expose additional phpthumb options in System Settings\n- [#2503] \"Preview\" inaccurately described viewing current page/site. Changed to \"View\".\n- Fixed help message strings to correct URLs\n- Fixed missing options array call in modRestClient, isArray call in modRestCurlClient\n- [#2545] Added setting resource_tree_node_name to allow users to specify the field used for the node text on the Resource Tree\n- [#2639] Prevent user from specifying a FC rule with Action of none\n- [#2641] Fixed issue where template was reset incorrectly when canceled on template change\n- Fixed issue where Permissions were being duplicated on setup due to relational db issue\n- [#2646] Prevent removal/editing of default Administrator policy ACLs to prevent users from accidentally removing access to web context\n- Added modAccessPolicyTemplate and modAccessPolicyTemplateGroup for easier managing and editing of Access Policies, including a UI for managing Access Policy Templates\n- [#2483] Auto-generate alias when duplicating a Resource\n- [#2645] Set Resources unpublished when duplicating\n- Update to xPDO v2.0.0-rc3\n- [#2501] Fixed menu not being loaded on immediately-added policies without page refresh, added bulk actions to policy grid\n- [#2505] Save Property Set now shows feedback and success message\n- [#2507] Export properties now prefixes filename with property set name\n- [#2624] Improved Users grid to allow batch editing from right-click context menu\n- [#2609] Remove filter commands and modifiers from scriptProperties passed to modElement/modTag instances\n- [#2500] Improved CSS on welcome page for Fx users\n- [#2532] Improved Resource tree icons to better shown when a Resource has children as opposed to when it is marked as a container\n- [#2602] Improved language on Users access permissions grid to clarify action\n- [#2614] Expand comment field on modUserProfile to handle more than 255 characters\n- [#2613] Ensured User Groups in mgr are sorted alphanumerically\n- [#2599] Fixed issue where Add Element to Property Set window form values were not cleared on second loading\n- [#2596] Fixed issue where User Groups could not be removed\n- [#2542] Fixed hardcoded language lexicon load reference in policy/get processor\n- [#2573] Fixed issue with backslash in TV output render property values\n- [#2594] Fixed issue where special characters were being stripped from phone numbers in user profile\n- Fixed issue with file tree that prevented image thumbnails from showing\n- [#2525] Fixed filemanager_path issues by added filemanager_path_relative setting, and then calculating from that\n- [#2589] Fixed issue with port 80 feeds in magpie RSS feed parser\n- [#2544] Fixed issue with updatefromgrid processor with User Settings\n- [#2560] Fixed issue with resourcelist TV not persisting set value\n- [#2586] Add rank field to FC rules allowing organizing of order of execution\n- Update core schemas and regenerate maps for new xPDO index elements\n- [#69] Allow Transport Vehicles to abort installation when validation fails\n- Update xPDO version to 2.0.0-rc2 (official release)\n- [#2552] Fix scope issues when passing nested arrays in Chunk properties", "MODX Revolution 2.0.4-pl2 (October 15, 2010)\n====================================\n- [#2502] Fix fatal error with Resources protected by Resource Groups\n- Fixed issue with resourcelist TV", "MODX Revolution 2.0.4-pl (October 14, 2010)\n====================================\n- Fixed issue where redirect was not working after creating new derivative resource\n- [#2485] Fixed issue where placeholder was in duplicated Access Policy\n- [#2492] Fixed reference in menu to bugs.modx.com\n- [#2486] Removed hardcoded language reference in lexicon load in access permissions getList processor\n- [#126] Ensured clearing of cache when deleting a Template Variable\n- Fixed issue where cancel button did not work on Resources after save\n- Fixed issue with URL TV Output Render and empty input values\n- Fixed issues with checkboxes/radios in TVs and widths when hidden\n- Fixed various issues with thumbnails in MODx.Browser and return paths in separate contexts\n- Added toggle setting for drag/drop in Resource and Element trees\n- [#MODX-2346] Allow login/logout processors to handle multiple contexts\n- [#MODX-2405] Fixed issue with border on portal panels in mgr home screen\n- Fixed issue with TV output render that stripped whitespace in delimiter\n- Fixed hanging save issue that occurred when HTML was in pagetitle/longtitle in a Resource\n- Fixed issue where TV values were being erased when a TV was hidden via Form Customization\n- Updated reference to help in Form Customization page\n- Fixed trivial issues with widths in richtext tvs\n- [#MODX-2415] Added fix to prevent adding of orm tree attributes with the same key on the same level\n- Added resourcelist TV input type for easier listing of resources in a tv input\n- Updated ExtJS to 3.3.0\n- [#MODX-2378] Fixed issue where action toolbar was on left in IE7\n- [#MODX-2408] Fixed issue where sorting was not available for description field on search page\n- Fixed issue where modx->resource was not available to TV input option values or default values in mgr\n- [#MODX-2410] Fixed issue with urlencoded context key on context edit page\n- [#MODX-2407] Fixed issue where user settings were not respected in connectors in mgr\n- [#MODX-2279] Fix bad AJAX response if database does not exist or can't be created during setup\n- [#MODX-2404] Fixed issue with auto_menuindex and multiple contexts\n- [#MODX-2354] Fixed issue with image TV loading incorrect URL in thumbnail preview on initial load\n- [#MODX-2357] Properly addressed issue where FC hideTab rule was causing hidden tabs to show if they were active at load\n- Refactor modAccessibleObject to centralize load policy check in _loadInstance()\n- Update xPDO for several critical bug fixes\n- [#MODX-2402] In Package Browser, Most Popular/Recently Added package names are now links to auto-search in grid\n- [#MODX-2397] Added filtering and search to FC rule grid\n- [#MODX-2401] Adjusted JS version postfix code to not adjust .php (or non-js) files used as script src targets\n- Improved context menus on FC rule grid to allow for batch actions on selected items\n- Added `for_parent` field to FC rules, to allow for more fine-grained control of rule applications\n- [#MODX-2385] Fixed issue when Context ACL is using no policy that prevented grid loading\n- [#MODX-2380] Fixed issue with upgrades and rb_base_dir, rb_base_url and filemanager_path\n- [#MODX-2246] Added topmenu_show_descriptions system setting to be able to toggle the top menus description text\n- [#MODX-2375] Improved class key field in Resource panel to a dropdown, added modClassMap for easier querying of resource/element types\n- [#MODX-2391] Fixed issues with FC rules not being respected on resource/create with default values for new Resource\n- [#MODX-2382] Fixed dynamic width of fields in windows across ui\n- [#MODX-2383] Fix inability to update rank of TV's in template editor\n- [#MODX-2379] Fixed issue where permission checks were swapped in Resource context menu with regards to delete/undelete\n- [#MODX-2384] Fixed issue where treepanel still showed if all trees were hidden via permissions\n- [#MODX-2389] Fixed issue where setup options, license and readme displays were not cleared after installation of package\n- Fixed issue where loading mask shows up and never disappears on extended Resource types\n- [#MODX-2388] Fixed issue with save button and user settings\n- [#MODX-2387] Fixed issue with user settings not able to be added via mgr ui\n- Fixed bug that would reset provider for updated packages\n- Fixed issue with paging toolbar pageSize being interpreted as string rather than int\n- Fixed issue where parent id constraint was ignored for default template on new Resources\n- Added sanitization to REQUEST_URI for login controller\n- Updated version to 2.0.4-pl", "MODX Revolution 2.0.3-pl (September 30, 2010)\n====================================\n- Fixed error in modResource::cleanAlias when context var is not available\n- [#MODX-2376] Fixed issues with updating settings on the context page\n- Fixed security issue with login screen and resource TV controller that allowed html injection\n- Fixed issue where clear cache checkbox isn't checked on Element pages\n- [#MODX-2370] Fixed various bugs with plugin event association on plugin page\n- [#MODX-1823] Improved the System Info panel by extracting data from phpinfo()\n- [#MODX-2362] Added missing OnResourceTVFormPrerender event\n- [#MODX-2374] Fixed issue where children nodes were not being moved with parent into new context\n- [#MODX-2373] Fixed imageTV issue where thumbnail was not cleared on data clearing\n- [#MODX-364] Fixed regClient* methods in cacheable Snippets on cacheable Resources\n- [#MODX-2370] Fixed issue with saving property sets on plugin events\n- [#MODX-2369] Fixed issue with modLinkTag and output filters where the filter commands were included in the URL\n- [#MODX-2350] Ensure that new Contexts always have Admin and Resource policy for Admin user group assigned to them\n- [#MODX-2352] Ensure that Context Settings appropriately override System Settings in core-level parsing where a Context is existent (example: site_unavailable_page)\n- [#MODX-2356] Ensure that OnResourceDelete and OnResourceUndelete events in update processors fire at correct times, after save()\n- [#MODX-2361] Ensure that a user in the Administrator group *always* has access to a Context when it is restricted in another user group\n- [#MODX-2357] Fixed bug that occurs when hiding a tab with FC rule that is the default active tab\n- [#MODX-2358] Fixed rare bug occurring with treestate in Chrome due to undefined variables in path\n- Fixed various issues with package management and the add new package button\n- Fixed bug where ?v=203pl is being added to content with .js in it, due to earlier commit to prevent js caching\n- Fixed issues with ellipsis/limit filters and special chars\n- [#MODX-2353] Fixed bugs with checkbox/radio TVs and complex values with HTML/quotes in them\n- Fixed some bugs with deleting a file in MODx.Browser in the actual view pane\n- [#MODX-2354] Fixed issue with imageTV and incorrect preview url reference\n- Fixed ellipsis output filter to use &#8230; instead of ...\n- [#MODX-2327] Fixed bugs with Form Customization not being respected\n- [#MODX-2349] Fixed bug with Form Customization and fieldDefault rule with template field\n- Added code to prevent caching of JS after upgrades by postfixing version to JS URLs\n- [#MODX-2342] Fixed issue where xhtml_urls setting wasnt included in build\n- [#MODX-2345] Fixed issue with templates and categories in mgr not persisting\n- [#MODX-2341] Fixed issue with redirect statement on login page in certain environments\n- [#MODX-2343] File upload now respects upload_* extension restrictions\n- [#MODX-2344] Respect context-specific filemanager_path in upload/remove actions on directory tree in mgr", "MODX Revolution 2.0.2-pl (September 17, 2010)\n====================================\n- Fixed issue where Add New Package would not work when selecting a provider manually\n- [#MODX-2339] Fixed issue with caching menus in mgr and multiple languages\n- [#MODX-2340] Fixed issue with initial resource values reverting after a save\n- [#XPDO-72] Fix invalid call to $this->manager->getPhpType()", "MODX Revolution 2.0.1-pl (September 16, 2010)\n====================================\n- [#MODX-2317] Add responseCode parameter to modX::sendRedirect() method\n- Fixed issue with @DIRECTORY binding not postfixing base path with / before value\n- Many styling enhancements, fixes for [#MODX-2264], [#MODX-2193], [#MODX-1885], [#MODX-1847]\n- Fixed issue with lexicon translations for permissions dropdown in mgr\n- Enhanced system settings grid to autosave without refresh, which allows for tabbing between settings via keyboard to set values\n- [#MODX-2325] Updated placeholders in setup lexicons for french/german languages\n- Added an editable dropdown for Permissions tab when editing an Access Policy for easier addition of Permissions\n- Fixed issue where default template was overriding empty template resources\n- [#MODX-2325] Updated Czech translation\n- [#MODX-2329] Login page now auto-focuses on username textfield\n- Add missing modCategoryClosure to create_tables script in setup\n- [#MODX-2280] Fixed bugs with IE and package management\n- Prevent issue where a User Group can select itself as a parent\n- Allow typeahead on user field when adding a User to a User Group\n- Optimized Resource Group tree in mgr UI\n- Fixed issue where > 20 records were not showing in ACL lists in User Group edit panel\n- [#MODX-2206] Prevent issue where renaming a menu's lexicon key orphans child menus\n- Fixed rendering bugs in file edit panel, as well as optimized its loading and streamlined RTE integration on the panel\n- [#MODX-2202] Removed deprecated modAction objects to prevent confusion\n- [#MODX-2325] Updated Swedish translation\n- Prevent bug that causes modal to overlap welcome screen\n- Allow non-empty responses to OnBeforeTVFormSave to prevent save\n- [#MODX-2201] Ensure MODX_PROCESSORS_PATH is upgraded correctly on upgrades where the core is moved\n- [#MODX-2323] Allow non-empty responses to OnBeforeDocFormSave to prevent save\n- [#MODX-2309] Ensure upload files button always uses the active node as the path, or if it is a file, its parent directory\n- [#MODX-2295] Ensure menuindex can be overridden in resource creation if auto_menuindex is set to true\n- Fixes to resource panels to adjust widths, loading of values properly\n- [#MODX-2318] Fixes to TVs in Resource pages to make order sorting work correctly\n- Abstracted setup database methods to driver-specific structures to accomodate for various future db drivers\n- [#MODX-2241] Added archive_with setting so users with improper ZipArchive compiles can switch back to PCLZip\n- Updated xPDO to include sqlite drivers\n- [#MODX-2308] Added UUID to all modx installs for usage in extras, custom providers, stats tracking, etc\n- [#MODX-2303] Fixed issue where resource editing pages were not respecting context settings\n- [#MODX-2302] Fixed issue with loading of input option values in TV related to optimizations in 2.0.1\n- [#MODX-2297] Fixed output filters limit/ellipsis when dealing with special character cases\n- [#MODX-2290] Added image preview when hovering over images in file tree\n- Added extra sanity checks in Package Management in case transport zips are not extracted\n- Make package grid update available Yes clickable to update\n- Cleaned up and better abstracted modRestClient and modRestCurlClient code\n- Fixed bug in setup during upgrade-advanced where DB information was not being checked correctly\n- Lots of improvements to handling and caching of thumbnails in manager\n- Fixed bug where reset filter on settings grid was not resetting to core namespace\n- [#MODX-2178] Added missing settings and lexicon values for those settings to build/lexicons\n- [#MODX-2179] Lexicons in Setup now use placeholders rather than sprintf for better i18n support\n- Added phpthumb_imagemagick_path for users that need to change the imagemagick path for different environments\n- [#MODX-2288] Dont duplicate TV Resource values when duplicating a TV unless explicitly told to\n- [#MODX-2217] Persist sort order of Resource tree\n- [#MODX-2291] Prevent editing of binary files to prevent zeroing out of file when saving\n- [#MODX-2185] Resource tree expand all toolbar button now expands all levels deep\n- [#MODX-2260] Added ability to rename ORM container nodes on extended fields\n- [#MODX-2285] Added ability to dynamically set number of results for any grid in manager, as well as a default number via default_per_page system setting\n- [#MODX-2284] Fixed bug in modX::getChildIds\n- Adjusted the way resources/elements load data in mgr edit/create pages to vastly speed up load times\n- [#MODX-2282] Fixed deprecated help menu URLs\n- Trees now properly handle state, allowing multiple state paths to be set\n- [#MODX-2163] Give area combobox in System Settings a bit more breathing room\n- [#MODX-2259] Fixed issue with empty value fields in extended/remote fields via ORM widget\n- [#MODX-2249] Fixed issue with misleading comment in modTemplateVar::getValue\n- [#MODX-2270] Added option to sort by pulishedon in the resource tree\n- [#MODX-2278] Removed non-used files and added space to empty files\n- [#MODX-2250] Fixed bug where Checkbox TVs with default value dont allow all checkboxes unchecked\n- [#MODX-2274] Introduced filemanager_url setting to handle URLs when filemanager_path is outside the webroot\n- [#MODX-2251] Fixed issue where @bindings in TVs were running during input, preventing setting values\n- Fixed bug with modContext::getOption and default values\n- [#MODX-2184] Fixed issues with MODx.rte.Browser and context-specifics\n- Fixed issue with filemanager_path in Windows\n- Fixed a possible issue in base file perms in modFileHandler\n- Fixed some random typos in system settings data and lexicon translations\n- Fixed bug where userinfo filter was outputting wrong content when user was empty\n- [#MODX-2263] Fixed IE issue with dropdowns as TVs\n- [#MODX-2183] Autotag values are now alphabetically sorted\n- [#MODX-2240] Site - Preview now dynamically previews current editing context\n- Fixed invalid login issue that prevented OnUserNotFound from firing on mgr login screen\n- [#MODX-2238] Fixed bugs regarding parent constraint and default template\n- [#MODX-2234] Fixed issue when drag/dropping a Resource into the parent field\n- [#MODX-2226] Fixed bugs with date output filter not behaving as expected\n- [#MODX-2184] Fixed issue where context was not respected in MODx.Browser instances, fixed bugs when specifying paths outside MODX_BASE_PATH\n- [#MODX-2236] Added sanity check to modTemplateVar::getRenderDirectories with custom dirs\n- Added modResource::joinGroup\n- Added helper JS function MODx.hideTV to modext\n- [#MODX-2233] Fixed issue where qtip was not showing on Elements in a Category\n- [#MODX-2203] Fixed issue where root of file tree was not accessible after navigating away\n- [#MODX-2192], [#MODX-2232] Fixed issues with settings and their translations, names in the Settings grids\n- Adjustments and optimizations to menus/actions processors and js\n- [#MODX-2231] Fixed issue where saving translated properties would overwrite key with translation\n- [#MODX-2220] Fixed bug where save_user was needed to change profile\n- [#MODX-2213] Always include english lexicon when loading a lexicon to act as a backup translation\n- [#MODX-2210] Added strip for xss in manager a variable\n- [#MODX-2205] Fixed issue with saving resources with resource fields having html and unescaped content\n- [#MODX-2198] Fixed directory checks on context web path for advanced distribution\n- [#MODX-2194] Fixed issue with modLexicon::fetch not working if a prefix is set\n- Removed SVN commit log from top header now that we're in Git\n- Adjusted version to 2.0.1-rc1", "MODX Revolution 2.0.0-pl (LastChangedRevision: 7216, LastChangedDate: 2010-07-21 09:10:12 -0500 (Thu, 21 Jul 2010))\n====================================\n- [#MODX-2159] Fixed bug where richtext_default was being ignored in Quick Create\n- [#MODX-2174] Fixed bug where manager_language was being ignored in Connectors, check for ctx init\n- [#MODX-1715] Added reference to setting keymap_save to allow for overriding of save shortcut key\n- [#MODX-2008] Updated Russian and Japanese translations\n- [#MODX-2008] Added in Thai translation\n- Fixed typo in filters english lexicon\n- [#MODX-2008] Added in French translation, updated German translation\n- [#MODX-2173] Fixed issue with IE and package installation wizard\n- Fixed setup directory checks for advanced builds\n- Fixed incorrect welcome URL in build\n- [#MODX-2008] Added in Czech translation\n- Configured phpdoc.ini file for SDK build\n- Fixed bug in file tree where URL was absolute rather than relative when being drag/dropped\n- Added OnFileEditFormPrerender event to allow plugins to fire on file editing form\n- [#MODX-2172] Fixed bug where tooltips for stay buttons were behind window\n- Sanity checks to tv render directories\n- Removed deprecated CSS icon reference\n- [#MODX-2169] Fixed bug with TV default values, inheriting and non-linear TV inputs\n- [#MODX-2170] Fixed error where element names cannot have less than 3 characters\n- [#MODX-2169] Properly handled @INHERIT binding in TV inputs\n- [#MODX-2165] Changed 'Remove Package Version' context menu item behavior to allow to show on non-installed versions to allow rollbacks from downloaded but not installed updates\n- [#MODX-2164] Fixed issue that might cause random, non-affecting error during package updates\n- [#MODX-2008] Added in Japanese translation\n- [#MODX-2163] Default settings grid to show only core namespace settings to reduce confusion\n- Added autotag TV input widget that grabs tags from a list of the tags so far for all content values for that TV\n- [#MODX-2161] Added sanity check for incorrect or invalid filemanager_path values in file tree\n- Added missing deleted checkbox on resource panels\n- [#MODX-2167] Fixed issue where duplicate button was creating incorrect duplicate name\n- [#MODX-2162] Fixed issues with set to default in TV values, reliance on processedValue\n- [#MODX-2168] Fixed new user panel issue with missing JS reference\n- [#MODX-2160] Fixed bug where config check was running checkPolicy on resources that caused inadvertent missing unavail/error page message\n- Some query optimizations in processors\n- [#MODX-2159] Ensure richtext_default setting is respected\n- Fixed bug where context settings create modal wasnt resetting values\n- Added missing tabpanel IDs for various tabpanels across mgr ui\n- Fixed bug that was strtolower'ing any strings in tabNew FC rule\n- Added grid renderer to FC grid\n- Tweaks to general UX, other slight cosmetic fixes\n- [#MODX-2156] Fixed unitialized variable in modTemplateVar::renderOutput/renderInput\n- [#MODX-2152] Fixed issue where local package dialog wasnt showing after clicking modxcms.com package browser\n- [#MODX-2154] Fixed issue where publish_document access permission was being ignored in resource processors\n- [#MODX-2149] Fixed issue where Package Management's modal would only once if hidden\n- Fixed issues with stay button on resources\n- [#MODX-2008] Added Swedish translation\n- [#MODX-2148] Fixed image TV thumbnail sizing\n- [#MODX-2145] Fixed 'New' context menu text to be easier to translate\n- Slight tweaks to CSS for MODx.Browser file thumbs\n- [#MODX-2147] Added phpThumb settings for controlling thumbnail output in manager, defaulted zoomcrop to off and force aspect ratio to on, center\n- Fixed erroneous change template message\n- [#MODX-2143] Fixed filemanager_path implementation so that thumbnails and relative URLs in browsing work with absolute and relative paths as setting\n- Removed powered-by text in request headers in AJAX calls\n- [#MODX-2143] Fixed issue where if filemanager_path was set differently that URL insertion on TVs or drag/drop was incorrect\n- Added urlencode/urldecode to filters\n- [#MODX-2132] Remove friendly_url_prefix reference that was causing PHP warnings without breaking makeUrl()\n- [#MODX-2142] Fixed issue where translations in settings, properties and permissions were not being translated or falling back to english\n- [#MODX-2132] Reverting commit in r7125 due to side issue caused by fix in it\n- Hardened security on some file download actions in mgr such as console output, phpinfo, properties export\n- Adjusted setup expiry to 15 minutes\n- [#MODX-2139] Added message to display if setup has to restart due to timeout\n- [#MODX-2140] Fixed welcome page to point to static page rather than atlassian stack\n- Update Help URLs to new base url for docs\n- Some UI tweaks to lexicon grid, added reset() JS method to MODx.Window for shorter code\n- Added in create entry to lexicon management\n- Ensure $modx is available in custom TV renders\n- [#MODX-2137] Fixed bug in image TV output render\n- [#MODX-2138] Fixed textarea bug in system settings\n- Allow MODx tags in TV descriptions in input renders, but prevent HTML tags\n- Fixed bug where output render type was being ignored\n- Ensure tv data isnt sent back in resource update processor, to prevent escaping problems with richtext tvs\n- [#MODX-2109] Fixed setup to have upgrade mode not go to editing database/contexts, only advanced upgrade goes there\n- Fix object caching bug in modAccessibleObject::_loadCollectionInstance()\n- Update xPDO 2.0 to revision 429\n- Ensure extended fields can be added to users with none pre-existing\n- [#MODX-2131] Fixed other issues with TV values and rendering\n- Added ctrl+alt+p key shortcut when updating a Resource to preview it\n- Prevent illegal drops of actions to menus, menus to actions, in trees on Actions page\n- Slight fixes, tweaks to plugin events grid\n- [#MODX-2130] Fixed typos and missing references in mb-based output filters\n- [#MODX-2131] Fixed various issues with TV rendering, values, and in multiple contexts\n- [#MODX-1404] Make MySQL client version check a warning only for older versions\n- [#MODX-1404] Remove MySQL client version check for 5.0.51\n- [#MODX-2024] Fix use of %s strftime modifier in modSessionHandler::write()\n- [#MODX-2132] Remove friendly_url_prefix reference that was causing PHP warnings\n- [#MODX-2107] Fix errors with friendly alias slug generation with certain multi-byte characters\n- [#MODX-2114] Fix Error Caching Resource log message when site unavailable or other transient Resources are constructed\n- [#MODX-2129] Added missing Resource events\n- Fixes to Messages page/grid\n- Added optimize database button on database tables grid\n- Fixed reference bug in resource/update processor\n- Improvements to Users grid to dim inactive users\n- Fixed a few bugs with MODx.Browser and file tree\n- [#MODX-2127] Added message to Package Management if cURL or Sockets is not installed that prompts user to do so\n- Added ability to send warning/error messages to all MODx.* grids/trees\n- [#MODX-2128] Fixed MODx.Browser in RTE mode\n- Added modManagerRequest::addLangTopic,setLangTopics,getLangTopics assistance methods\n- [#MODX-2125] Various fixes for manager log page\n- [#MODX-2023] Added sanity checks for settings caches in setup, ensure settings caches are removed post-setup\n- [#MODX-2064] Ensure Action combos in System Actions page are reloaded when an action is updated/created/removed\n- Fixed invalid validation rule on element classes\n- [#MODX-2091] Ensure duplicate maintains published status\n- [#MODX-2123] Added workaround for IE with Quick Update Resource window\n- Modified validation on modChunk, modPlugin, modSnippet, and modTemplateVar to allow spaces within a name\n- [#MODX-2052] Fixed bug with loading multiple MODx.Browser instances in non-file management circumstances\n- Updated duplicate processors to check validation, return more informative messages, sanity checks\n- Removed duplicate days keys in lexicon\n- Fixed issues when TV render directories are overridden\n- [#MODX-2115] Fixed issue with phpthumb reference and capitalization, and when base_url is /\n- [#MODX-2113] Fixed CTRL+SHIFT+H shortcut for hiding left nav\n- Fixed bug in ORM tree relating to adding root nodes when subnode was selected\n- Added ability to add/remove attributes and containers to UI ORM trees, specifically in User extended and remote data\n- Added UI for editing extended User Profile data\n- [#MODX-2116] Fixed bug in depth search in modX::sanitize\n- [#MODX-1150] Changing class_key for a Resource now reloads the page to change editing area\n- [#MODX-2077] Config check screen in welcome panel now is same width as other panels\n- [#MODX-1648] Lexicon Management now loads by default the current manager_language\n- [#MODX-1743] Package update now shows status alert when package is already up to date, rather than an error\n- [#MODX-2119] Fixed bug in IE where onunload was firing regardless, preventing moving off page seamlessly\n- [#MODX-2112] Fixed bug where admin password reset was not working\n- [#MODX-2111] Fixed bug where language settings were not set after running setup in another language\n- [#MODX-2110] Fixed bug where resource fields were not being updated on update, causing publishedon errors\n- Adjusted version for pl development", "MODX Revolution 2.0.0-rc-3 (LastChangedRevision: 7083, LastChangedDate: 2010-07-07 12:20:55 -0500 (Wed, 07 Jul 2010))\n====================================\n- Updated German translation\n- Fixed bug with new installs and base template name\n- Fixed UI issue with Namespace path being unwantingly translated\n- Upped timeout on setup settings cache to 10 minutes; was far too short\n- [#MODX-2040] Fixed bug with setProperties and merge argument\n- Slight tweaks to phpthumb default config\n- Added sanity check when using multiple TV render directories\n- [#MODX-2100] Fixed content type creation for binary type bug, bug in build with regards to content types\n- Added flag to setup to fix proceeding error after install\n- Fixed setup to return setup process to very beginning when settings timeout, avoiding various errors about classes not being found\n- Added modx-tv-checkbox class to resource TV checkboxes for easier DOM manip\n- Added showCheckbox setting for resource TVs display to allow for extensibility and TV targeting\n- Added phpThumb specific settings\n- Added OnResourceTVFormRender event for affecting TV displays on resources\n- [#MODX-2104] Auto-detect correct value and set use_multibyte on new installs\n- [#MODX-2104] Added 'use_multibyte' setting that allows for use of mb_* functions for multibyte characters; fixes bug with MB chars in output filters\n- [#MODX-2019] Added default Element policy\n- Fixed issue with Ext.form.BasicForm and prior commit, adjust else/if condition\n- Added headers check to all Ajax requests to connectors to require unique site ID header to harden security\n- Added modx-content-above and modx-content-below divs for RTE usage\n- [#MODX-2008] Updated Russian translation\n- Enabled RTEs to be used on TV default value field\n- Added which_element_editor setting, which allows for usage of multiple RTEs for Elements vs Resources\n- Fixed bug with custom_resource_classes setting implementation on blank values\n- [#MODX-2094] Enabled Packages to be able to have their Provider changed\n- [#MODX-1809] Added manager_time_format to allow changing of time formats in mgr widgets\n- Added extra var to pass revo version in transport provider requests; helps with download metrics and version checking\n- Optimized package grid by moving menus to JS\n- Fixed issue where manager_language setting was being ignored in mgr connectors\n- Enhance security on language string loader\n- [#MODX-1834] Adjusted color on Yes/No on packages grid to more reflect intent\n- Readjust JS firing timing for Elements to prevent RTE timing errors in faster browsers\n- [#MODX-2090] Added auto_check_pkg_updates_cache_expire setting, which caches package update checks in Package Management to speed up grid load times\n- Ensure Resource pages using RTEs always have save btn enabled\n- Fixes to RTE loading in Element panes, other issues regarding timing of plugin firing\n- Fixed bug with area listings in combo in system settings\n- [#MODX-1961] Fixed bug with octal perms when creating directories in the admin\n- [#MODX-1527] Fixed bugs in admin confirm password field on install\n- Fixed Package Management in IE8\n- Styling improvements\n- Fixed IE issue on navbar, few other tweaks to package management for IE\n- [#MODX-2032] Fixed topic varchar length issue with UTF-8 installs\n- [#MODX-1612] Added Create Menu context menu on root node for menus tree\n- [#MODX-2020] Ensure error when creating duplicate context ACLs shows\n- Tweaks to Package Management browser JS to allow for more consistent rendering\n- [#MODX-2051] Stripped tags from TV description field on input rendering\n- Added 'custom_resource_classes' setting, which allows you to specify custom resource types for the resource tree\n- Tweaked FC tvMove rule to be more consistent with values of other TV FC rules\n- Allow blank names (not keys) in Settings create/update windows; tweaks to query in package management grid\n- [#MODX-1737] Container resources can now have names specified on duplicate\n- [#MODX-2074] Fixed bug where property descriptions were not i18n-able\n- [#MODX-2062] Date TV type now can store time; updated datetime ExtJS xtype to latest version\n- [#MODX-2046] Added 'collapse' toggle to left trees, shortened username on top right to allow for small resolutions\n- [#MODX-2067] Fixed bug with cleanAlias and a non-existent lexicon string\n- [#MODX-2086] Fixed a few bugs in package management styling\n- Tweaks to context menu styling\n- [#MODX-2078] Context menus now show under cursor\n- [#MODX-2083] Fixed bug where setting editedon was returning invalid date\n- [#MODX-2061] Fixed erroneous lexicon entry for cache_handler setting description\n- [#MODX-2085] Fixed issue with namespace path not being translated on get\n- Added ability to activate/deactivate FC rules from context menu\n- fieldVisible, fieldLabel, tvVisible, tvMove Form Customization rules now support multiple fields via comma-sep list\n- Added functionality to Form Customization to add new Tabs and move TVs to other tabs\n- Applied CSS gradient styling to grids, tabs\n- [#MODX-2056] Fixed CSS for topmenu, restyled to add contrast and enhanced\n- Cleaned up TV display panel, removed TV reload button, extended fields all the way across\n- [#MODX-1832] moved \"Set to Default\" to a fade-in icon\n- Prepared code for oncoming feature to move TVs into other tabs\n- Removed credits from about pane, consolidated tabs\n- Fixed permissions checks on resource tree context menu when policies are limited\n- Added prefix filtering to modLexicon::fetch\n- Added modTemplateVar::getDisplayParams for easier fetching of display_params for a TV\n- Fixed bug with custom TV render paths\n- Added phpThumb to core, added connector for secure access, integrated into MODx.Browser\n- Ensure categories in TV panel are sorted alphanumerically\n- Added stripString, cdata, replace, fuzzydate and ago output filters\n- [#MODX-2045] Added ExtJS, Smarty, PHPMailer, MagpieRSS version into System info\n- [#MODX-2057] Fixed bugs with action/menu trees\n- Fixed bug with is_writable check in setup; was checking core/config rather than just core/config/config.inc.php\n- [#MODX-2042] Fixed extra beginning slash for image/file TVs\n- Add validation to processors for Chunks, Plugins, Snippets, and Template Variables\n- [#MODX-1998] Disallow reserved Template Variable names (i.e. Resource field names)\n- [#MODX-2033] Fix bug with unchecking Template Variable access when editing a Template\n- Have modX::switchContext() update placeholders from config on successful switch\n- [#MODX-1774] Remove redundant setting of placeholders from modX::$config in modRequest::handleRequest()\n- [#MODX-2031] Fix modX::stripTags() and modX::sanitize() to properly strip nested element tags\n- [#MODX-2027] Added icon to file tree to show MODx Browser, for a different view on file management\n- [#MODX-1924] Made more precise the cursor pointer change on buttons in mgr\n- [#MODX-1904] Fixed bug with phx placeholders in modTranslate095 class\n- [#MODX-1535] Fixed bug with transparent background for grid-based comboboxes\n- [#MODX-1904] Fixed bug with phx placeholders in modParser095 class\n- [#MODX-1936] Lexicons now fallback to English if no translation is found for specified language\n- [#MODX-1781] Fixed z-index issue with top nav and window masks\n- [#MODX-217] Added create element type icons for Element tree\n- [#MODX-217] Added directory create icon to file tree toolbar, changed upload files button to icon\n- [#MODX-2022] Fixed bug regarding php file permissions and writable checks\n- Fixed bugs related to loading of RTEs for TVs in derivative resource classes\n- Enhanced image TV to show preview of image, adjusted to display below\n- [#MODX-2015] Added sanity check to prevent users from dragging Resources to a non-existent context\n- [#MODX-2013] Fixed bug where hiding fields with Form Customization would disable them from being sent\n- Fixed bugs with System Settings grid due to erroneous merge in UI styling\n- [#MODX-2012] Made Form Customization grid sortable\n- [#MODX-2011] Fixed MODx.grid.Grid::getSelectedAsList to work in Fx,IE\n- Added more sophisticated check for writable directories in setup to ensure compatibility across environments\n- Fixed bug where manager_language setting was ignored\n- [#MODX-2007] Redirect to requested mgr page when logging in\n- Adjusted version for RC-3 development", "MODX Revolution 2.0.0-rc-2 (LastChangedRevision: 6924, LastChangedDate: 2010-05-27 15:56:51 -0500 (Thu, 27 May 2010))\n====================================\n- Fixed copy-prepared-css command in build.xml to prepare for rc-2 release\n- Adjusted welcome screen URL to go to a non-release specific confluence page\n- [#MODX-2000] Fixed FC rule to apply to template fields by overriding in controller\n- [#MODX-2000] Add ability to specify a template in REQUEST or alter via plugin in resource/create controller\n- [#MODX-2004] Allow settings to be duplicated when duplicating a context\n- Added missing OnUserBeforeRemove event\n- [#MODX-1797] Fix bug with publishedby field getting updated unintentionally\n- [#MODX-1919], [#XPDO-52] Update xPDO to revision 425 for fix to xPDOManager::createObjectContainer()\n- [#MODX-1918], [#MODX-1919] Improve error reporting in database setup steps\n- Made default click behavior for Files in file tree be to edit\n- [#MODX-1995] Fixed issues regarding sending password via email with new users\n- [#MODX-1549] Preserve file tree state\n- [#MODX-1810] Gender now saves correctly in user panel\n- [#MODX-1635] Redirect to Users grid after creating a new user\n- Fixed bug with import properties\n- [#MODX-1971] Allow ./- in Context key names, but not as first character\n- [#MODX-1997] Added ability to duplicate and set inactive/active Form Customization Rules, batch actions to Rule grid\n- Cleaned up profile editing page\n- Cleaned up style for headers on welcome page\n- Reworked System Info page, cleaned up styling, display, info\n- Added batch actions to Users grid\n- Fixed bugs with removing directories in file tree\n- [#MODX-1996] Fixed missing create/update settings windows\n- Allow for separate paths on derivative resource types based on a [classkey]_delegate_path setting that points to their controllers, added checks to prevent path mapping\n- Prevent deferred render on left nav trees, to prevent loading errors for js hooks\n- Fixed bugs with MODx.grid.encodeModified/encode, plugin event saving\n- Added loadCreateMenus JS event to modx-resource-tree modext widget\n- Refactored js lang loading to allow for dynamic modification of strings\n- [#MODX-1993] Moved config.inc.tpl to core/docs to prevent confusion\n- Added description below TV rows in Resource edit\n- [#MODX-1853] Fixed issue where reload button was above MODx.Browser in TV pane\n- Switched Quick Create/Update Resource description field to more-used introtext field\n- [#MODX-1992] Fixed error in modSnippet preventing multiple executions per request\n- [#MODX-1983] Clarified package uninstall option message\n- [#MODX-1982] Fixed broken cancel button on Package View page\n- [#MODX-1989] Fixed incorrect var reference in getfiles processor\n- Added extra pagination to dropdowns in mgr that might have large #s of records to add usability for large sites\n- Fixed all Elements including Template Variables to properly respect modAccessCategory ACLs.\n- Allow base-level Element Category ACL assignments\n- Fixed some issues with Settings grid and lexicons, key not being displayed, etc\n- [#MODX-1940] Resized lexicon grid toolbar to fit better in smaller resolutions;\n- [#MODX-1950] Adjusted permissions to allow proper listing of Elements; checks 'list' policy on Element now rather than view_[element]\n- [#MODX-1975] Added warning messages for PHP 5.2.0 and 5.1.6 versions in setup asking that users upgrade to 5.3.0+; will still allow installs, however, if the user has those versions\n- [#MODX-1967] Added warning to setup for people who are using PHP 5.3.0+ and dont have date.timezone set\n- Added proper permission checks to Elements/Categories across processors/controllers\n- Added UX for managing Element Category access for User Groups\n- Add modAccessCategory to allow context-specific security policies on modCategory as well as any modElement via the related modCategory; includes policy inheritance to sub-categories\n- Add modCategoryClosure table class to allow for easy recursive queries on modCategory\n- Fixed bug caused by JS/CSS optimizations that would break left nav when too many resources were loaded\n- Fixed bug where access contexts for admin user were being duplicated on upgrades\n- Added extra options to attaching with modPhpMailer; fixed bug in phpmailer that caused E_DEPRECATED errors\n- [#MODX-1912] Added manager logging to file/directory actions\n- [#MODX-1912] Added file/directory specific permissions to allow more fine-grained security on using the file manager\n- [#MODX-1972] Added OnTVInputRenderList, OnTVOutputRenderList, and OnTVOutputRenderPropertiesList System Events to allow you to return a path to specify where to look for custom TV files\n- Allow separate caching directories for smarty when using different manager themes\n- [#MODX-1951] Ensure smarty cache is cleared on site cache clearing and settings\n- Ensure admin ACLs are set on new installs\n- Added check to modResource::stripAlias to make sure modX object is a modX instance\n- Added basic template and default home resource to new installs\n- Added load-only and load,list and view policies to build, adjusted setup to handle admin/resource policies with different IDs\n- Moved setup's global new/upgrade install scripts to separate files\n- MODExt adjustments; main layout now in central viewport so can handle browser resizing, refactored settings grid editing code, IE/FF/Chrome fixes\n- [#MODX-1970] Add scheme property to Link Tags to allow canonical, https, or any URL generation scheme from modX::makeUrl()\n- Fixed bug where core namespace was not in build\n- Update xPDO to revision 424 for fixes related to PDOException reporting\n- Ensure packages are unpacked after downloading\n- Fixed bug with removing a plugin\n- Added System Setting, 'cache_noncore_lexicon_topics', which can be used to disable caching on noncore lexicon topics, which is useful for 3PC development.\n- Deprecated modPackageBuilder::buildLexicon\n- Completely refactored the Lexicon system to now do file-based Lexicon Entries only. DB entries are only for overrides. This allows for proper overriding of\ncore lexicon entries, caches faster, and allows for much easier 3PC development.\n- [#MODX-1783] Fixed unnecessary scrollbar bug by removing unnecessary margin on body/html tags\n- Slight spacing tweaks to main layout to make layout feel more open\n- [#MODX-1806] Improvements to messages section\n- [#MODX-1913] Fixed incorrect wording on setup complete page\n- Tweaked launching of layout panel to add consistency across browsers\n- [#MODX-1835] Fixed error on Windows platforms when an extension_packages path contains a colon (:)\n- Added ORM editing formpanel object for editing v/p editing pairs, used now on modUser remote data form\n- Added panel for viewing remote data on a user\n- Added 'lexicon' field to modAccessPolicy to enable translations of descriptions of Permissions\n- Added extended field to modUserProfile to handle a majority of basic extended user profile storage/retrieval needs\n- Added 'lexicon' field to Element properties to enable automatic translating of property descriptions and option names\n- Fixed parent/context_key reference issue when creating resource from context tree node\n- Tweaks to index.css for default mgr theme to correct styling issues in webkit browsers due to ExtJS upgrade\n- Fixed deprecated references to removed images in default mgr template css that was causing 404s\n- [#MODX-1911] Allow for drag/drop reorganizing of categories in the Element tree\n- [#MODX-1892] Various fixes to TV-Template relationship grids\n- [#MODX-1895] Added sanity check for windows systems with file names in file browser\n- [#MODX-1908] Corrected logic flaw in modManagerResponse that prevented smarty templatePath from being set for CMPs\n- Optimized loading for System Settings grid\n- Updated ExtJS to 3.2.1\n- Add remote_key and remote_data to modUser\n- [#MODX-1898] Fix static calls to modX::fromJSON() and modX::toJSON() instance methods (xPDO updated to revision 421)\n- Pushed File tree nodes' context menus to JS layer, added Upload Files button to tree toolbar\n- Pushed Element tree nodes' context menus to JS layer, similar to Resource Tree optimizations\n- [#MODX-1897] Fix Date TemplateVar web output render error in PHP 5.3 due to use of ereg()\n- Fixed bug with Quick Update caused by new resource tree js changes\n- [#MODX-1848] Allowed parent selector to select contexts as the parent in Resource page\n- Pushed Resource tree nodes' context menus to the JS layer, massively decreasing the size of the JSON tree sent in the getNodes processor, vast speeding up tree functionality\n- Made publish/unpublish/delete/undelete actions on the tree only change the class of the node, rather than refreshing the node, speeding up workflow\n- Pushed modX::getService to xPDO layer\n- [#MODX-1873] Ensure setup redirects use full URL in header\n- [#MODX-1887] Adjust default widths for main layout to render panels more consistently\n- Optimized modX::getChunk() and modX::runSnippet() by caching instances within a request to modX::$sourceCache\n- Modified modX::setDebug(true) to set error_reporting(-1)\n- Optimized modLexicon::loadCache\n- [#MODX-1824] Fixed bug where duplicate wasnt fully duping resources\n- Moved Resource's duplicate method into the model, via modResource::duplicate\n- [#MODX-1868] tree_root_id now accepts a comma-delimited list of Resource IDs to restrict by. Works across contexts as well.\n- [#MODX-1871] Fixed bug with delimiter TV output render\n- Dropped unnecessary ID field on modEvent table and made `name` column PK\n- Refactored modX::invokeEvent and modX::getEventMap to take advantage of new plugin event changes\n- Adjusted the modPluginEvent model to reference the event name rather than id\n- Added new model-based System Events to work more effectively in any context\n- Removed deprecated system events\n- Added tree_root_id setting that allows you to specify the start parent ID of the left Resource tree\n- Fixed bug where User Settings could not be removed\n- Enabled ability to set absolute path and placeholders for filemanager_path and rb_base_dir\n- [#MODX-1791] modPackageBuilder::createPackage now forces lowercase package name to be more compatible across environments\n- Sanity checks to prevent user from accidentally removing admin/resource access policies\n- [#MODX-1860] Fixed bug where new password was being hidden too fast when changing user password\n- Added proxy support to modRestCurlClient for Package Management\n- Added a couple refactorings to modRestSockClient to prevent possible errors\n- Consolidated user group create system events into one event, OnUserGroupCreate\n- Fixed some various plugin event calls\n- Fixed Plugin Event code to restrict groupname to a UI filter only, not in event caching; adjusted UI grid to support groupname in display\n- Refactored file handling processors to use modFileHandler class with modFile and modDirectory derivative classes to abstract file system processing to abstract for multiple environments\n- [#MODX-1789] Added extra checks in Package Management to make sure that the correct directories are created before using it. Will now prevent usage of PM if those directories do not exist or are not writable.\n- [#MODX-1789] Added code to attempt to create core/components and assets/components after install. If fails, displays a notice to user to manually create them themselves to allow Package Management to work properly.\n- [#MODX-1839] Fixed grammatical error in forgot login link on login page\n- [#MODX-1846] Fixed invalid markup for username in top right\n- [#MODX-1854] Fixed invalid references to cultureKey that broke cultureKey setting effectiveness\n- [#MODX-1785] Fixed invalid password variable reference in invoke notfound event in login processor\n- [#MODX-1784] Fixed invalid event call on user update, as well as added event invoking into updatefromgrid processor\n- [#MODX-1836] Set default context_key in modResource objects to 'web'\n- Fixed bug with system info page and active users that would cause error in error log\n- [#MODX-1788] File tree now respects filemanager_path setting. Also cleaned up file browsing processors.\n- Upgraded ExtJS to version 3.2\n- Updated version to 2.0.0-rc-2 for svn development and issue tracking\n- [#MODX-1778] Fixed error that shows up if E_NOTICE set to true in setup/ index due to servers not posting a HTTPS server global", "MODX Revolution 2.0.0-rc-1 (LastChangedRevision: 6614, LastChangedDate: 2010-03-22 16:41:04 -0500 (Mon, 22 Mar 2010))\n====================================\n- Prepared for rc1 release\n- Fixed CSS compression copying in build.xml\n- Fixed regClient*() functions to work again on cacheable scripts\n- Move element source and include cache files outside of context cache directories since they should be cleared only when elements are updated\n- Remove eval() from modScript and re-enable remote debugging of modScript instances by caching function as include in addition to source cache\n- [#MODX-1759] Ensure manager log fires on top menu deletion\n- [#MODX-1772] Ensure array of IDs is passed to OnBeforeEmptyTrash and OnEmptyTrash plugin events\n- Added a welcome screen to show on first login to manager\n- [#MODX-1738] Fixed issue with default value on radio TVs\n- [#MODX-1741] Fixing inconsistent widths for radio options by making them list vertically rather than horizontally\n- [#MODX-1769] Lexicon grid search now searches name and value\n- [#MODX-877] Updated confusing text on TV access permissions tab\n- [#MODX-1766] Fixed PHP_SAPI issue to properly work by setting a default value on setup to provide a default http_host value to properly populate the site_url\n- Fixed bug in setup that didn't catch processors_path in prior configs\n- [#MODX-1759] Fixed bugs with manager log not storing correct PK values, or displaying missing keys in grid\n- [#MODX-1766] Fixed config.inc.tpl to work with non-httpd SAPI's\n- Added title/info for the Reports->System Info->Database page. This is return fixed the CSS styling issue as well.\n- Fixed CSS Styling on Recent Documents. 5px padding was removed.\n- Fixed bugs with modMail class and default attributes that prevented attributes from persisting after a reset()\n- Removing deprecated RTE handler code\n- [#MODX-1762] Increased file uploader window size for translations\n- Dont render unnecessary tabs in Resource TV panel if no TVs assigned to Template for that Resource\n- Sort Template Variables on the Template editing page by name\n- Ensure Element Properties that have HTML in them show markup instead of rendering the html in editing mode in mgr ui\n- [#MODX-1669] Redid File Uploader in Directory tree to be more cross-browser compatible\n- Cleaned up and enhanced login CSS\n- Standardizing and adding class constants to modRest* classes\n- Updated copyright data in lexicon entries\n- Fixes to build.xml, css compression command\n- Updated copyright dates\n- [#MODX-1750] Lots of procedural and reference fixes to Lexicon grid UI\n- Cleaned up presentation of modAction records in mgr\n- Added a fix to tree refreshParentNode; enhanced modUserGroup::getUsersIn()\n- Added saving mask to Element Property grid to fire when saving the property set\n- Removed deprecated file reference in login template\n- Added System Settings to toggle news/security feeds in welcome panel\n- Added System Setting to toggle on automatic checking of package updates in Package Management\n- [#MODX-1751] Fixed erroneous reference in friendly alias setting description\n- [#MODX-1752] Fixed bug where topmenu items without children didnt show even if they had an action\n- Some css tweaks to login page\n- Updated to xPDO 2.0.0 r419 to fix xPDOVehicle bug\n- Fixed bug with Download Output button in MODx.Console\n- Ensure forgot login activation email is HTML\n- Added Forgot Login link and form to manager, sends an activation email to specified email if user forgot login/password\n- Fixed SQL sorting algorithm for package versions, added helper methods for comparing package versions\n- Added $resource to properties passed to OnDocFormDelete in resource/delete processor\n- Updated to xPDO 2.0.0 r417 ([#XPDO-40] Fixed getCount to work when passing a criteria with a class alias set)\n- Enhanced striptags output filter to take a parameter of allowed tags\n- Make sure $paths and $options are passed to OnCacheUpdate\n- Added compression/concat references to login and browser tpls\n- Fixed build.local.xml and build.xml scripts\n- Added compress_css system setting for compressed CSS for releases, moved over modx-theme.css to templates css/ dir. Don't use compress_css without first running _build/build.local.xml Ant task.\n- Cleaned up leftover PHP4 function definitions, unescaped SQL code, added proper accessor methods for private vars, other old code\n- Fixed bug with modLexiconLanguage::clearCache\n- [#MODX-1738] Fixed issue with FC TV rules not working as expected on Resource Update\n- Fixed bug where plugin event properties were getting merged if more than one plugin was associated with the event\n- Added loading mask to editing panels to prevent accidental editing before data is loaded\n- Added sanity check for OnRichTextBrowserInit event processing\n- Added fix for RTE loading in Resource panel, should fix most RTE saving bugs\n- Added collapsibility to Document panel\n- Added 'concat_js' system setting that will concat all the common JS files into one single file\n- Adjusted lang.js.php to properly use ETag header to cache lang js\n- Added css rule to prevent hidden iframes from being shown\n- Fixed bug where Resource Groups were not editable on Create Resource\n- Added sanity check for packages with missing provider\n- Added \"Updates Available\" column to packages grid, auto-checks provider for updates\n- [#MODX-1732] Added duplicate language ability to language grid\n- [#MODX-1741] Fixed possible bug with radio/cb tv labels\n- [#MODX-1593] Fixed bug where User could not be added with no role in User Groups tree\n- [#MODX-1735] Properly URL encode link tags while still preserving = and &amp; in query string\n- [#MODX-1736] Fixed bug with assigning TVs to Resource Groups\n- [#MODX-1740] Added workaround for SQL code to properly hide TVs with FC rules\n- [#MODX-1738] Fixed bug with radiogroups and set TV default FC rule\n- Fixed some header issues, _FILES content type handling\n- [#MODX-1733] Fixed bug that was stripping tags from connector processing\n- Ensured that Static Resource filename change fires dirty status\n- Made sure Set to Default fires dirty status for Resource panel\n- Fixed possible width stretching bug in TV panel in Resource edit view\n- [#MODX-1543] Added \"Rename Category\" to category nodes in element subnodes in Element Tree\n- [#MODX-933] Can now drag/drop Elements into Categories in the Element Tree to assign them to Categories\n- [#MODX-1729] Fixed incorrect filter name to be more appropriate to function\n- [#MODX-1727] Added missing Empty Cache checkbox to derivative resource panels\n- [#MODX-1724] Fixed bug with output renders in TV panel not triggering panel dirty status\n- [#MODX-1730] Fixed bug with $scriptProperties and login processor\n- Some cleanups to MODExt flow and ID referencing\n- Changed all GPC references in processors to $scriptProperties, which is loaded at entrance points to processors with GPC vars, pushing input handling to the connector\n- [#MODX-1711] Fixed bug with strip output filter\n- Added ellipsis output filter\n- Fixed various event callings across JS implementation to properly modularize modext components\n- Added events to user's groups grid to ensure dirty firing\n- Added MODx.FormPanel::markDirty\n- Added in CSS tweaks to accommodate Opera 10.5\n- Fixed bug with users grid if access permissions tab is removed\n- Fixed deprecated method definitions in modConnector classes\n- Fixed text in language settings to more accurately reflect function\n- Added area filter to Settings grid\n- [#MODX-1721] Disabled unnecessary paging on System Events table\n- [#MODX-1726] Added sanity check to ensure TV input type is properly set\n- Fixed bug with action buttons and continue stay method\n- Added UI for managing website field in modUserProfile\n- Added website field to modUserProfile\n- Removed unnecessary and problematic editor dropdown in chunk editing screen\n- Sped up drag/drop of reordering in tree by now only framing moved nodes instead of refreshing\n- Added modRequest::getParameters() method for retrieving various GPC variables or arrays of variables; automatically strips MODx GET parameters as necessary\n- modRequest::__construct() now creates references to all GPC variables in modRequest::$parameters\n- Modified modX::makeUrl()/modContext::makeUrl() to accept query string parameters as an array or string\n- Added modX::toQueryString() static method to turn associative array into a valid query string\n- [#MODX-1709] Fixed issue with encoding of action button parameter\n- [#MODX-1554] Prevented uploading of files to files themselves in directory tree\n- [#MODX-1700] Fixed issue with text referencing setting in lexicon entry\n- Ensure tags in a Static Resource content are parsed before trying to load the source path\n- Fixed static/weblink update js\n- Removed unnecessary and redundant table prefix check later on in setup\n- Fixed css/js properties in TV tab to let RTEs auto-determine the height of their TD fields\n- Fixed missing permissions reference on resource controllers\n- Added OnHandleRequest to modManagerRequest::handleRequest\n- Properly hides UI elements for Resource buttons/pages if user doesnt have permissions\n- Refactored modResource::cleanAlias() to allow various options, including built-in and custom transliteration capabilities\n- [#MODX-717] Foreign characters (UTF8 data) needlessly removed from alias\n- Hide top menu items if there are no submenus and if the topmenu is not clickable\n- [#MODX-1690] Fixed text for confirmation dialog when removing an Element to include name and type of Element\n- [#MODX-1707] Added mail_charset and mail_encoding system settings to control charset and encoding in emails\n- [#MODX-1706] Ensure that text and qtip fields in Resource/Element trees have any tags stripped\n- [#MODX-1699] Fixed bug in Quick Edit TV where it would erase the caption and replace it with the name\n- [#MODX-1704] Fixed erroneous if statement in clear button hiding in error log panel\n- [#MODX-1675] Added fix for windows paths on Edit File panel\n- [#MODX-1681] Added checks for issue with importing lexicon in Webkit-based browsers\n- Cleanups to TV input widths\n- Removing core RTE; too much work, may take back up in a later version\n- [#MODX-1697] Added ability to edit images and links in RTE\n- Added more robust MODx.rte.Selection API\n- Added missing changes to modActions needed to load lexicon entries for RTE\n- [#MODX-1662] Fixed mismatch in menus widget field label\n- [#MODX-1687] Fixed bugs in template package browser due to changes in modx.view.js\n- Made resource panel be a fileUpload-able panel for plugins\n- [#MODX-1357] Added richtext_default system setting\n- [#MODX-1685] Added MODxEditor, a core Ext-based RTE to be the default RTE for Revolution\n- [#MODX-1674] Stabilized MODx.Browser to work with core RTE\n- - Added missing registry.db.modDbRegister* classes to setup\n- [#MODX-1642] Logging out doesn't unlock resources: added modUser::removeLocks() and modified modUser::endSession() to call this method\n- Added OnInitCulture event to core transport data.\n- [#MODX-1672] Refactor collation/connection processors in setup to be more stable\n- Updated xPDO to r414 for improvements in xPDOManager\n- modInstall::writeConfig() uses new_file_permissions if specified or umask() settings by default\n- Removed superfluous calls to xPDO/modX::setDebug() and xPDO/modX::setLogLevel() in modInstall\n- modInstall::getConnection() now uses utf8_general_ci for charset/collation by default\n- [#MODX-1691] Set Quick Create/Update windows to use anchor property rather than width to adjust for resizing\n- Added 'cultureKey' setting to enable easier language translation in contexts/fe/components\n- Fixes to styling for MODx.Browser window\n- Added 'relativeUrl' parameter to MODx.Browser file data\n- [#MODX-1674] Fixes and stabilization to MODx.Browser, specifically when used by RTEs\n- Changing default editor from TinyMCE to blank value\n- Fixed bug in setup where inplace setting was being forced to 1\n- Cleaned up most processors, fixed wrong permission references, standardized code\n- Fixed welcome panel to only show panels with permission to see\n- Fixed error log view page to restrict viewing and clearing by permission\n- Added descriptive information to Roles grid\n- Lots of permissions fixes, other bugfixes and sanity checks to Element processors/controllers\n- Added propertyset permissions\n- Cleanups to Resource controllers, processors, optimizing of security permission checks\n- Fixed various bugs with search page\n- Fixed bug with adding policies that prevented partial regexp matches in name\n- Fixed bugs when adding new policies or permissions that showed prior added perm/policy in form\n- Properly secured and refactored recently edited resources grid\n- [#MODX-1670] Adjusted permissions to allow restricted user to edit profile\n- [#MODX-1667] Removed unnecessary opacity CSS rule in menus\n- Fixed bug where page wasnt reloading on login in certain situations\n- Make rightlogin div longer to support longer translations\n- [#MODX-1653] Fixed issues with related objects, removal of aggregates, and other packaging bugs. Introduced xPDOTransport::UNINSTALL_OBJECT, which defaults to true. When off, it will prevent an object from being uninstalled.\n- Updated xPDO to r413\n- [#MODX-761] Fixed language issue in setup, now sets it correctly and loads proper lexicon for login screen\n- Ensure console window appears above other windows\n- [#MODX-1663] Added MODx.msg.status, which shows a fading status message on a successful save. This also solves the issue of user feedback.\n- Removed unnecessary field from recently-edited-resource grid on welcome screen\n- [#MODX-1660], [#MODX-1037] Revamped login screen to HTML/CSS, basic form processing to allow browsers to save password in their password management systems\n- Revamped UI in new setup options, cleared up text, simplified presented options\n- [#MODX-18] Allow editing of MODX_CONFIG_KEY in setup welcome view\n- [#MODX-18] Prompt user for MODX_CORE_PATH if not found at beginning of setup\n- [#MODX-760], [#MODX-1080], [#MODX-1528] Added setup option to set new_file_permissions and new_folder_permissions in welcome view\n- [#MODX-760], [#MODX-1528] Removed new_file_permissions and new_folder_permissions system settings from setup\n- [#MODX-760], [#MODX-1528] Updated xPDO 2.0 to revision 407: new file and folder permissions determined from umask()\n- [#MODX-878] Stay buttons now action-specific, done through Ext state rather than PHP\n- Redo logic order of modPackageBuilder::buildLexicon to ensure languages are packaged in before topics\n- [#MODX-1647] Added width specification to force width of screen to prevent scrolling off of RTE TVs\n- Cleaned up tvTitle Form Customization rule by moving code from JS to PHP\n- Fixed z-index issue for windows due to IE fix\n- [#MODX-732] Added z-index force to topmenu for IE, fixed rightlogin div on topbar for IE\n- [#MODX-1641] Optimized and cleaned code dealing with Form Customization TV visibility and default values\n- [#MODX-1658] Fixed bug where placing a menu item in a submenu would place it in top level\n- [#MODX-1624] Enabled changing of text field in menu items\n- [#MODX-1656], [#MODX-1654] Fixed CSS gap in install summary in setup\n- [#MODX-1655] Fixed hardcoded lexicon strings in setup\n- [#MODX-1621] Remove unnecessary context menu items from items in Resource Group Resources tree\n- [#MODX-1627] Fixed incorrect menu in resource group tree resources when newly dragged\n- [#MODX-1599] Added manager_date_format system setting for customizing date formats for the manager\n- [#MODX-1651] Increasing width of setup navbar buttons to accommodate translations\n- [#MODX-1649] Fixed bug where Quick Create didn't respect default_template setting\n- [#MODX-1650] Fixed bug with language specification in setup to properly set cookie for Windows machines, and set initial language properly\n- [#MODX-1626] Fixed bug where top menus could not have actions\n- [#MODX-1494] Fixed issue where some settings dont have descriptions, and cleaned up deprecated settings\n- [#MODX-1645] Fixed incorrect lexicon key for setting_site_start_err\n- [#MODX-1646] Fixed issue where download buttons were staying grayed out if there was an error message\n- [#MODX-1644] Added SMTP mail settings to default system settings to allow global SMTP usage for all modMail functions\n- [#MODX-1606] Fixed bug in modRestCurlClient class due to encoded ampersand\n- [#MODX-197] Refactored Action Buttons JS, added 'actionNew', 'actionContinue', and 'actionClose' events to MODx.FormPanel objects, ensured parent/context_key is persisted through add another resources\n- Added a couple sanity checks to modRestCurlClient\n- Added JS to disable install button when clicked in setup to prevent double-clicks\n- controllers/resources/create: Refactored template inheritance to occur before any delegate controller is called.\n- processors/resources/create: Moved OnBeforeDocFormSave event invocation until after POST vars are applied to $resource object.\n- processors/resources/create: Refactored common code to be executed before any delegate processor is called.\n- processors/resources/create: Refactored to respect add_children and new_document_in_root permissions.\n- Added various access_denied lexicons to the resource topic.\n- Added new_document_in_root permission to control access to creating Resources at the root level.\n- Updated to xPDO 2.0 revision 406.\n- [#MODX-1606] Added sanity checks and ID standardization to DOM nodes for Package Browser\n- Fixed possible bug with ta-toggle div in resource panel\n- [#MODX-1628] Fixed FC tvDefault rule by doing setting php-side\n- [#MODX-1636] Added ability to assign Role to User when adding them to a User Group from the User Groups tree\n- [#MODX-1634] Fixed bug with resource/resourcegroup/getlist processor that prevented showing of resource groups in new resource panels\n- [#MODX-1639] Fixed bug where resource panel JS didnt check for existence of possibly hidden access permissions grid\n- Fixed modUser::removeSessionContext() to call modUser::endSession() if no contexts are left\n- Fixed modUser::endSession() to destroy all SESSION data and the session cookie\n- Fixed bug in Plugin -> System Events tab caused by invalid function call in getlist processor\n- Fixed problems with various deprecated functions to increase compatibility with Evo and avoid performance issues:\n * modX::getDocuments() and modX::getDocument()\n * modX::getAllChildren()\n * modX::getActiveChildren()\n * modX::getDocumentChildren()\n * modX::getDocumentChildrenTVars()\n * modX::getParent()\n * modX::getPageInfo()\n * modX::getUserInfo()\n- Fixed modX::__construct() declaration to indicate it properly as a public method; added phpdoc comments.\n- Fixed modX::sanitize() declaration to indicate it properly as a static method.\n- Updated to xPDO 2.0 revision 405\n- [#MODX-1614] Fixed issue with cached pages going to unauthorized_page instead of error_page when user does not have load permission\n- [#MODX-411] Set system setting: emailsender to the admin email address during install\n- [#MODX-1556] Show class and id for deleted resources or elements in Manager Action Log\n- [#MODX-1552] Create New element Here shows for root elements but not those in categories\n- [#MODX-1625] Fixed bugs with menu tree preventing creating child nodes of new items, restyled menu and action icons\n- Added preventative to make sure packages are only downloaded once when in Package Browser\n- [#MODX-1623] Fixed package installation error: attempting to preserve files fails with error message\n- Updated to xPDO 2.0 revision 404\n- Setup upgrades no longer preserve existing data/files on install\n- Fixed issue with setup trying to write connector files regardless if files are already in place\n- Updated to xPDO 2.0 revision 403\n- Fixed bug where plugin properties were not being injected into the plugin event call\n- [#MODX-1617] Fixed bug with tvDefaultValue Form Customization Rule\n- [#MODX-1619] Added sanity check for modActionDom constraint check\n- [#MODX-1620] Fixed missing or incorrect lexicon entries across ui\n- [#MODX-1612] Fixed bug where Create Menu button was not working\n- [#MODX-1616] Renamed \"field\" to \"name\" in Form Customization rule windows\n- Removed any non-essential JS from the top menu items\n- Added additional check and error logging for processor_path option in modX::executeProcessor().\n- Added missing view_sysinfo permission to default Administrator policy\n- [#MODX-1595] Fixed bug regarding hiding top menu items with permissions\n- [#MODX-1596] Fixed bug related to creating a new top menu item\n- Fixed issues related to usergroup panels and anonymous usergroup editing\n- Fixed bug in template viewer for package browser that wasnt paginating right\n- Added modRestServer for generic REST request handling\n- Enable remote sorting and sorting by ID on Users grid\n- Fixed and enhanced search field on Users grid\n- Fixed bug with duplicating a context where only the first level would duplicate\n- Updated to xPDO 2.0 revision 396\n- Fixed bug where package version info wasnt being computed on download/scanlocal\n- Added check for locked status on resources, now shows locked status in tree, as well as who is editing\n- [#MODX-1592] Fixed bug with usergroup create by moving it to a window\n- [#MODX-1590] Fixed missing processors for ACL grids\n- [#MODX-1526] Added permissions resource_tree, element_tree, file_tree that restrict rendering/viewing of the left-side trees. Must be applied to access policies.\n- [#MODX-625] Adjusted text in config.inc.php writable warning message\n- [#MODX-1586] Fixed toolbar rendering bug in user settings due to hidden div, now using hideMode: offsets\n- Added search for user box in usergroup users grid\n- Changed User Group users grid to a non-local grid, now supports pagination and proper validation\n- Enhanced UI for editing User Group Context/ResourceGroup ACLs\n- [#MODX-1525] Added permissions field to modMenu to define policy permissions required to see Top Menu items\n- Fixed bug in Packages grid to properly show provider name\n- Added modRestResponse class, improved error handling for REST-based package management\n- Added verification for Providers, now check to make sure they can connect before being added or updated\n- Added Package View page to Package Management, allowing you to view more info about a package, view prior installed versions, and remove older package versions\n- Fixed typo in setup script for PM changes\n- Added version_major, version_minor, version_patch, release, and release_index fields to modTransportPackage tables to assist sorting and organization\n- Fixed bug in transport schema\n- [#MODX-1571] Fixed xtype in automatic_alias setting\n- [#MODX-1572] Fixed deprecated error in PHPMailer service\n- [#MODX-1512] Fixed bug with MODx.tree.Tree::refreshNode that caused a strange duplicate node error\n- Updated xPDO to revision 392 to get new nested condition features\n- [#MODX-1515] Fixed date picker CSS\n- [#MODX-923] Added file path to config.inc.php configcheck message on welcome page\n- [#MODX-1579] Added code to prevent invalid characters from being used in admin username/password in setup\n- [#MODX-1575] Fixed bug with Resource Group getList processor\n- Updated to xPDO 2.0 revision 389\n- Added validation to modContext.key field; must be a valid PHP identifier without underscore characters\n- Modified modError::checkValidation() to call modError::addField() for each validation message\n- [#MODX-1562] Cleaned up Site Schedule grid to properly load baseParams during refresh and adjust pagination\n- Cleaned up processor code, plugin invoking, access permission checks in processors\n- [#MODX-1562] Fixed bug in Site Schedule data\n- Fixed OnDocUnpublished and OnDocPublished calls in processors to pass modResource reference\n- [#MODX-1564] Fixed bug causing combo values to get overridden if they were set before the combo store loaded\n- Move element and resource prerender plugin events to after js registering to allow for proper event execution order\n- [#MODX-986] Added \"Duplicate Context\" to Resource tree, as well as \"Remove Context\"\n- Fixed bug with default provider on package management UI\n- [#MODX-1540] Fixed last login display in Welcome page\n- [#MODX-1567] Enabled sorting in Reports -> System Info -> Recently Edited Documents\n- [#MODX-1522] Restricted user editing to just the save_user permission\n- Added a \"reload\" button to the error log\n- Fixed Active Resources on Reports - System Info\n- Fixed database version query in Reports - System Info\n- [#MODX-1560] Added a button to truncate manager log\n- Added new browsing view for Templates in Package Management; thumbnail-based browsing.\n- [#MODX-1534] Revamped file edit page to match other page structures\n- [#MODX-1542] Added missing undelete permission to basic Resource policy\n- [#MODX-1539] Added view_user permission to solve dropdown combo users bug that needed \"edit_user\"; view is more applicable there\n- [#MODX-1553] Show current permissions in chmod window\n- [#MODX-1539] Fixed a few bugs with the manager log page\n- [#MODX-1530] Fixed permission reference in resource create/data\n- [#MODX-1532] Fixed bug in permissions reference when trying to remove element from property set\n- Fixed bug with login page and new controllers location\n- Enhanced provider home page to allow links for newest/most downloaded packages\n- Added sorting to Access Policy grid, cleaned up getList processors across site\n- Fixed Manager Log page to properly display content, log the right class key, and now display the name of the object edited\n- Enhanced Property Sets page to now allow you to edit specific implementations of Property Sets per element, as well as the default set\n- Added \"disabled\" checkbox to Quick Update Plugin\n- Fixed bug in modManagerResponse dealing with CMPs and templating paths\n- Moved controllers/* files to controllers/default/ to allow for custom manager templating\n- Fixed bugs with Property Sets not showing correctly in dropdowns\n- Updated xPDO to revision 385 to fix cache_db functionality broken by PHP 5 only changes\n- [#MODX-1514] Added css for pointer cursor to top menus\n- [#MODX-1513] Added check for SimpleXML to installer\n- Add sanity check to make sure languages arent erased on package uninstall\n- Removed confirm dialog for remove action on Access Permissions grid\n- Fixed panel layout for Access Policies, User Group editing\n- Fixed E_STRICT warning on modX::getCacheManager() [method signature did not match xPDO::getCacheManager()]", "MODX Revolution 2.0.0-beta-5 (LastChangedRevision: 6224, LastChangedDate: 2009-12-15 10:03:36 -0700 (Tue, 15 Dec 2009))\n====================================\n- Fixed bug where Set to Default on Resource TV panel was hidden unless you clicked Reload\n- Fixed some bugs with Property Sets editing\n- Fixed bug where download wasnt working for package management due to missing provider\n- Fixed bug where quick create Static Resource wasnt loading MODx.Browser\n- [#MODX-1496] Fixed issue with scrolling context menus not working on local grids\n- Fixed styling in welcome panel\n- Shrinking top menu a bit to fit in smaller window resolutions\n- Fixed invalid method reference in modInstallTest derivative classes\n- Fixed styling and JS in TV pane\n- Fixed error with charset reference in setup/\n- Clear Search in Package Browser when clicking on a Tag\n- Added Search bar to Package Browser, now can search entire repository\n- Fixed height of Package Browser to not go too far down screen\n- Fixed modRestSockClient to properly strip HTTP headers and return only XML\n- Added modStaticResource methods: getSourceFile() and getSourceFileSize()\n- Fixed bug in setup/ script with new transport package fields\n- Fixed modCacheManager to not cache reg* calls that will cause breakage on similar calls to reg* method\n- Added 'package_name' and 'metadata' fields to modTransportPackage for future development\n- Fixed styling commits; also fixed bug on Package Management when not selecting default provider\n- Added help buttons to Resource pages\n- Moved TV categories in Resource edit page to tabpanel, also cleaned up button styling\n- Fixed table styling. This is temporary until all tables are ported to ext grids. This affects welcome pane, system info, and online users.\n- Fixed bug where package browser would close on ESC key\n- [#MODX-1489] Allow spaces in Category names\n- [#MODX-1497] Fixed username not being sent in new user email\n- Fixed NOT NULL error in modManagerLog\n- Revamped Package Management UI, changed Provider hooks to REST-based, massively improved downloading UI\n- Fixed styling on the search page.\n- Fixed styling on the actions page.\n- Fixed styling on the manager logs page.\n- Fixed triggerfields in windows in Safari\n- Changed the text-size and and top margin of the Main Navbar Submenu span for more readability.\n- [#MODX-1426] Added connect check to assist with mysql_get_server_info in setup\n- Few style changes: Changed Button style text color to black - Previously it appeared that buttons were disabled. Changed Text color inside of combo boxes to black - As before it looked like the element was disabled.\n- Modified the date fields to show a drop-down box rather than the date image. Changed the text-size and spacing of the Main Navbar to 12px.\n- Fixed styling of the welcome panels.\n- Fixed some issues with OnDocFormSave, plus standardized how to render fields/html to update forms\n- Fixed bug with default values, @ bindings and other things on checkbox/radio TVs\n- Prevent tree from expanding too much on quick create, cleaned up js\n- Assigned user id/username to [[+modx.user.id]] and [[+modx.user.username]] for easier access\n- Cleaned up last PHP4 remnants to PHP5-only\n- [#MODX-1483] Fixed bug with TV saving in resource create processors\n- Recompiled MODx.Console to use Ext.Direct, now should be a bit more stable. To end a MODx.Console session, pass 'COMPLETED' to the registry.\n- Resizing the left tree now properly resizes content in the right panel and is stateful\n- Added resizability to leftbar tree\n- Removed no-longer-necessary js file references in resource controllers\n- Consolidated filetree css/js into main css/js files\n- Fixed logic error that caused removing setup directory to fail\n- Combined some common JS files, cleaned up login page css, other optimizations\n- Consolidated filetree extension CSS, removed unnecessary filetree files\n- Consolidated CSS files in templates/default/css to one single file to reduce load times from @imports\n- Added rowactions to package grid\n- Improved code in @DIRECTORY binding to be more efficient and take advantage of DirectoryIterator\n- [#MODX-1478] Fixed @SELECT binding\n- [#MODX-1474] Fixed bug with multiple list-boxes\n- [#MODX-1476] Fixed bug with TV default values with non-inherit tvs, also bug with radios/checkboxes and set to default\n- [#MODX-1479] Fixed bug with duplicate DOM ids in User Group tree\n- [#MODX-1480] Fixed bug with wrong permission reference in property set remove processor\n- Added emptyText to local and property grids\n- [#MODX-1477] Added emptyText config param with default 'No data to display' message to empty MODx grids\n- documentObject was not getting set from cached Resources.\n- Added inline help that loads official MODx documentation in a window\n- [#MODX-900] Fixed erroneous text on site_status setting description\n- Added (Inherited Value) flag to TVs that are inheriting their value\n- Added category titles to TV editing panel\n- [#MODX-1354], [#MODX-1475] Fixed @INHERIT and other bindings in TV inputs\n- Fixed bugs with dirty status not firing for certain TV input types\n- Fixed CSS for login page\n- Fixed issue where default connection charset was not persisting in setup for upgrades\n- CSS tweak to get windows working properly\n- Major styling updates (thanks lossendae!)\n- [#MODX-1473] Fixed bug with modUser and modUserProfile PK's getting mixed, causing errors if PKs for each object were different\n- Added city field to user UI\n- Optimizations to Resource panel\n- [#MODX-1466] Made \"back\" from Access Policy edit redirect to Access Controls page, made Access Controls tabs stateful\n- [#MODX-1471] Added scrollOffset: 0 to grids to hide empty space on right side\n- [#MODX-1469] Fixed dir handling in setup\n- [#MODX-1388] Updated documentation for modX.getTree and modX.getChildIds\n- [#MODX-1318] Prevent ordering of elements in dragdrop since order defaults to alphanumeric\n- Made charset in setup/ a dropdown of available charsets\n- Fixed collation grabbing for setup/\n- [#MODX-1090] Added 'Rename File' window to directory tree\n- Vast improvements to setup, including removing of mootools, using ExtCore now, simplified UI workflow to remove unnecessary AJAX calls, added in database creation checking, collation specification, etc\n- Fixed bug with modPackageBuilder that would ignore the specified path for a Namespace\n- [#MODX-1207] Changed modSession.id column to varchar(40) to support session.hash_function=1 with session.hash_bytes_per_char=4.\n- Simplified and optimized session handling, removing older PHP workarounds and adjusting preset system settings.\n- Make sure non-static Resources with binary content types get processed and output.\n- [#MODX-1450] Added paging to Template combobox to allow for large numbers of templates\n- [#MODX-1443] Tree sorting now works for modMenus\n- Removed deprecated system settings from build\n- [#MODX-1448] Fixed issue with container checkbox not persisting\n- [#MODX-1426] Fixed issue with MySQL checks on non-standard\n- [#MODX-1437] Fixed duplicate policy\n- Fixed some issues with Form Customization\n- Added 'address' field to modUserProfile\n- Added ability to edit the (anonymous) user group from the user group editing panels\n- Fixed typo in usergroup get processor\n- [#MODX-1018] Fixed bug with having to click the Clear Filter button in a settings grid twice\n- [#MODX-1380] Fixed bug with expanding node when quick creating a resource in it\n- [#MODX-1326] Fixed the access denied logout form, added styling\n- [#MODX-1423] Fixed error with duplicating a template\n- [#MODX-1409], [#MODX-919] Fixed issue where tag symbols were being stripped in Elements and breaking filtering and nested tag functionality\n- [#MODX-1347] Fixed user validation for username missing error\n- Extrapolated RTE logic to make it generic\n- Added OnRichTextBrowserInit to allow for 3rd Party RTEs to hook into MODx.Browser\n- Added system setting \"allow_multiple_users_per_email\" to allow users to have a single email shared across users. Defaults to true.\n- [#MODX-972] Fixed bug when property description was changed, grid wasnt updating\n- [#MODX-1390] Fixed docs for $modx->sendUnauthorizedPage();\n- [#MODX-895] Fixed possible rendering issue with error log scroll bar\n- Optimized setup pre-install checks, now checks both mysql client and server versions\n- [#MODX-1404] Fixed mysql version checks to only show a warning if the client/server is incorrectly setup to where PHP cannot determine the versions.\n- Package Management now restricts downloading/updating Extras to their supported MODx versions (ie, you can't download packages that support only beta-3 if you have beta-4 or beta-2)\n- [#MODX-1310] Fixed expand/collapse toolbar items in trees\n- [#MODX-1361] Make sure cache (including Smarty files) is cleared after install\n- [#MODX-1372],[#MODX-1376] Marked deprecated functions as so in phpdoc comments\n- [#MODX-1378] Fixed bug with adding a None role to a user group in the User -> Access Permissions tab\n- [#MODX-1375] Fixed documentation for modX.getRequest\n- [#MODX-1374] Fixed documentation for modX.getRegisteredClientScripts\n- [#MODX-1370] Fixed quick create to set modResource type to modDocument properly\n- [#MODX-1373] getLoginUserName and getLoginUserId now return boolean false if no user is logged in\n- [#MODX-1369] Fixed validation errors and possible loophole in error processing for user processor flow\n- Fixed column alignment with radio/checkbox TV inputs\n- [#MODX-1350] Fixed issue where reset to default wasnt working with radio TV inputs\n- [#MODX-1360] Fixed issue where publishedon was being reset in quick update\n- Sanity fixes to misc processors\n- Added access modifiers to methods in modElement\n- Moved name character sanity checks for Elements to element class.\n- Cleaned up element processors, added missing permission checks, filled out plugin event calls\n- [#MODX-1355] Fixed erroneous label for quick create resource on Contexts\n- [#MODX-1352] Remove stay-buttons from user update screen\n- [#MODX-1349] onDirty now fires on triggerfield-based TVs\n- Cleanups to getList processors, bugfixes for grids\n- [#MODX-1317] Fixed erroneous label for quick create resource; should be Document\n- [#MODX-1316] Added menu title to quick create/update resource\n- Fixed issues with User grid\n- [#MODX-1325] Fixed console's download to file functionality\n- [#MODX-1327], [#MODX-1340] Fixed issue with generation of new password\n- Fixed locking\n- Lots of PHP5-only optimizations", "MODX Revolution 2.0.0-beta-4 (LastChangedRevision: 5880, LastChangedDate: 2009-10-19 09:04:47 -0500 (Mon, 19 Oct 2009))\n====================================\n- If memory limit is lower than 24M, force to 128M if possible\n- Fixing setup text for memory limit checks.\n- [#MODX-1080] Make sure traditional distribution doesnt need base directory writability\n- Added modInstallTestSvn class for handling SVN-specific setup tests\n- Fix to setup contexts controller to read existing paths on upgrade.\n- setup/ memory_limit checks now only need to be 24M for setup/ to run.\n- Updated to xPDO 1.0 revision 363 to fix \"Error saving changes to parent object fk field action\" messages being logged during install.\n- Fixed issues with category remove dialog and lexicon topic grid\n- [#MODX-1294] Fixed possible obscure problem when using Preview after changing the alias in a Resource\n- [#MODX-1278] Fixed issues with checkbox TVs and default values, fixed the 'set to default' button for complex inputs\n- [#MODX-1280] Fixed issues with the user create processor\n- Added OnBeforeUserActivate, OnUserActivate events\n- Added 'active' boolean field to modUser. Defaults to 1.\n- Added OnCreateUser, OnDeleteUser, OnUpdateUser events\n- [#MODX-1170] Fixed issues with Export Topic\n- [#MODX-912] Fixed isinrole/ismember output filter\n- [#MODX-677] Made capitalization consistent on Resource edit/create screen\n- [#MODX-1251] Fixed issue with server offset displaying incorrectly\n- [#MODX-896] Fixed issue with server_offset setting description\n- [#MODX-928] Fixed issue where parent resource wasnt refreshing properly\n- [#MODX-777] Made consistent the checkDirty behaviour of save buttons across manager\n- [#MODX-938] Added check to build to check if core+core.transport.zip were removed before build starts.\n- [#MODX-629] Added missing automatic_alias setting to build\n- [#MODX-790] Fixed issue where couldnt browse back to root directory with MODx.Browser\n- [#MODX-902] Fixed empty warning message for removing category\n- Fixed bug with removing categories\n- Fixed issue where couldn't drag a resource onto a resource with no children\n- [#MODX-1130] Fixed issue with parent triggerfield; also redid how tree hrefs load so that clicking on a node in the tree to load url can be disabled\n- [#MODX-1133] Fixed issues with hotkey behavior\n- [#MODX-1230] Fixed issue where drag Resource to symlink/weblink content field would add tags as well\n- [#MODX-1273] Added OnLoadWebPageCache event invocation to modRequest->getResource().\n- [#MODX-1273] Fixed events in User update/create form\n- Enabled compression of manager JS scripts by changing the Setting \"compress_js\" to true.\n- Upgraded ExtJS to ExtJS 3.0.2\n- [#MODX-1270] OnManagerCreateGroup and OnWebCreateGroup events now fire\n- [#MODX-1237] Fixed warning in modParser with regards to uninitialized variable\n- [#MODX-979] Added password_generated_length (the length of the auto-generated password) and password_min_length (the minimum length for a password)\n- Cleaned up usergroup processors\n- Added sanity checks to usergroup processors\n- Prevent possible issue on usergroup update that would wipe related objects\n- Prevent possible issue that would allow user to remove Administrator group\n- Removed some legacy todo statements\n- Moved Element category reset on modCategory object remove to modCategory class\n- Cleaned up modResourceGroup, modTemplate helper methods\n- Added modUser::joinGroup(group,(optional)role) and modUser::leaveGroup(group) for easier development\n- Optimized getrecentlyeditedresources processor\n- Make sure config.js.php outputs proper headers\n- Commented out Content-Length headers on lang.js.php, for some reason was slowing down servers\n- [#MODX-1256] Fixed issue with Resource tree not being visible in Resource Groups page\n- Fixed issues with Import HTML/Resources pages; properly convert to MODExt\n- [#MODX-1202] Fixed issue where Element name was missing in Duplicate window\n- [#MODX-1233] Fixed bug where categories could only be renamed once before needing to reload page\n- [#MODX-1248] Fix bug that could wipe TV values if tab wasnt loaded\n- [#MODX-1241] Fixed Preview button on update panels\n- Prettying up of TV fields\n- Now display SVN revision number with version in top left of mgr header\n- Fixed issues with TVs setting values incorrectly\n- Added \"Set to Default\" button on TVs that will reset the TV's value to it's default value. TV Resource values can now be set to blank as a valid value.\n- [#MODX-924] Fixed errors in various system setting descriptions\n- [#MODX-935] Tooltips in Resource tree now do not show if no description or longtitle is set\n- [#MODX-1120] Now shows TV names in tag form below the caption in the TV editing panel in Resource editing\n- Fixes to plugin event calls in controllers\n- Fixes to filetree to enable in Ext3\n- [#MODX-1112] Fixed issue where checkboxes in grids werent firing dirty statuses\n- [#MODX-1229] Fixed issue where default hidemenu setting in Create Static Resource was setting incorrectly to true\n- Added some extra variables for RTE firing; also made sure MODx.loadRTE fires on new resource creation. Fixes [#TINYMCE-9], [#TINYMCE-8]\n- [#MODX-523] Fixed copy issue in console by providing \"Download to File\" link\n- [#MODX-649] Fixed issue where comboboxes were not loading proper displayValue when first rendered\n- Added category combobox to quick update/create windows\n- [#MODX-1019] Added missing site_unavailable_page System Setting.\n- [#MODX-1226] Removed modResource->checkChildren() method; isfolder should not be set based on presence/absence of children.\n- [#MODX-1213] Fixed issues with WebLink creation and loading\n- [#MODX-1178] Fixed issue where checkbox TVs were unable to be set to false; properly rendered values into a hidden field\n- [#MODX-1204] Implemented $matchAll for modUser::isMember, that allows exclusive and inclusive group membership checks\n- [#MODX-1203] Now preserves state of open tabs in left bar\n- Added \"Form Customization\" page, which emulates Evolution ManagerManager functionality and integrates it into the core\n- Revamped modMenu DB structure to allow for more proper dynamic menus; 3PCs will need to now refer to the Components menu as 'components', as the \"id\" field has been dropped and \"text\" is now the PK\n- Fixed DOM issue with Profile page\n- Improved core transport build script, lowered build times\n- Fixed issue where hiding the alias field would cause it to be erased\n- [#MODX-1169] Fixed issue where unchecking Container on a Resource that had children would hide them from the tree\n- [#MODX-1125] Fixed issue where Properties were being lost on new Elements\n- Fixed some dirty field problems in Element/Resource forms\n- [#MODX-1167] Improved isFolder checkbox tooltip\n- [#MODX-929] Changed default click functionality in Tree menu to edit Resources, unless does not have permission to, will then go to View\n- Fixed navbar structure on main menu to properly handle infinitely deep nested menus. Needs help from a CSS guru on the CSS end.\n- [#MODX-1161] Fixed bug with height argument on modX::getParentIds\n- Documentation updates to modResource class\n- [#MODX-1189] Fixed issue with TV values not setting properly with modTemplateVar->setValue\n- Added modResource->getTVValue, which gets the value of a specified TV for the Resource\n- [#MODX-1177] Adjusted Lexicon Management text to properly represent functionality\n- Added more metadata to Lexicon Topic exports\n- [#MODX-1191] Fixed issue where Namespace combo was conflicting with other DOM IDs in Lexicon Management\n- Changed Accordion to Tabs in left menu\n- In all Resource panels, Moved Page Settings back to right side, moved Template to top, moved Published to top right\n- [#MODX-1173] Added modResource->hasChildren() function. Returns # of children for the Resource.\n- [#MODX-689] Fixed error when using @SELECT binding with Template Variable Input Option values.\n- Fixed issues with modMenu creation/editing\n- [#MODX-1132] Various fixes to the user editing page\n- [#MODX-1123] Fixed bug where properties were not saving on new elements\n- [#MODX-683] Changed title for 1st tab on Resource edit screen\n- [#MODX-1118] Tweaked MODx.combo.ComboBox and other store references to possibly fix local store bug\n- Fixed issue with Sort By dropdown in the Resource Tree\n- Fixed issues with User Group update page\n- Added modAccessPermission class to properly handle access policy permissions\n- Adjusted UI to handle model change\n- Added logic in setup install to clear sessions table after install to prevent access permission changing problems (and is a good general practice anyway); users will have to re-login after setup/ is run.\n- Cleaned up access policy grid\n- Default sort roles by authority\n- Removed no-longer needed Security pages; now done in Access Control and User Group edit screens\n- Started cleanup of Security system; changed 'Authority' listing on User Group page to a more correct \"Minimum Role\".\n- Added some IDs to resource edit page\n- [#MODX-1124] Took Templates off the list of attachable elements in Tools | Property Sets", "MODX Revolution 2.0.0-beta-3 (LastChangedRevision: 5593, LastChangedDate: 2009-07-30 11:14:17 -0500 (Thu, 30 Jul 2009))\n====================================\n- Fixed issue with scrollbars and height in tree context menus\n- [#MODX-963] Fixed issue with scrollbars and height in grid context menus\n- Fixed possible error in lang.js.php\n- [#MODX-982] Added param stringLiterals to directory/getList processor\n- [#MODX-978] Updated PHPMailer to 2.0.4\n- [#MODX-960] Fixed DOM issue with User Group creation/editing screen\n- Added ability to drag/drop files in file tree into fields\n- Fixed issue with file tree hiding files\n- [#MODX-960] Fixed erroneous header in Manage User Groups and Roles\n- [#MODX-965] Removed Disabled field from Package grid since it currently is unapplicable\n- [#MODX-964] Fixed issue with toolbar buttons in package download tree by removing unneeded buttons, fixing refresh button\n- [#MODX-966] Changed Package Management grid to be easier to read, removed unnecessary information\n- [#MODX-962] Fixed issues with User panel screen\n- Replace deprecated split() call in magpierss class with explode().", "MODX Revolution 2.0.0-beta-2 (LastChangedRevision: 5416, LastChangedDate: 2009-07-16 13:15:41 -0600 (Thu, 16 Jul 2009))\n====================================\n- [#MODX-1029] Fixed incorrect URL references in browser controller template\n- Updated version info for beta2 release\n- [#MODX-942] Made sure all get-based processors use REQUEST, not POST\n- [#MODX-937] Added 'Download Extras' button to package grid which loads modxcms.com provider\n- login processor does not return site_url in response by default.\n- modResponse->outputContent() allows programmatic options to configure max_parser_iterations.\n- Updated xPDO to revision 341: package uninstall preserves and restores file resolver data\n- Changed key shortcuts to always require ctrl+shift to prevent browser collisions\n- Added in field for description key in modMenu windows\n- [#MODX-931] Added isequal, isequalto, and notequalto as modifier aliases to default Output Filter\n- Fixed issues with pagination on settings grids\n- Fixed ENTER key issues on quick create/update windows\n- Added &language option to lexicon tags.\n- Added ability to load lexicon topics via tag: [[%key? &namespace=`mynamespace` &topic=`mytopic`]]\n- [#MODX-910] Fixed issues with gte/lte/gt/lt output filters\n- [#MODX-921] Added \"isempty\" as an alias of \"ifempty\" in output filters\n- [#MODX-920] Fixed wordwrap output filter\n- [#MODX-914] Added isnotempty and hide output filters\n- [#MODX-913] Added isloggedin and isnotloggedin to output filters\n- Upgraded ExtJS from 2.2 to 3.0\n- [#MODX-925] Fixed issue where name couldnt be changed on duplicate resource window with resources with children\n- [#MODX-911] Fixed dragability issue when assigning resources to resource groups\n- [#MODX-901] System Settings grid search now searches descriptions\n- Added 'afterLayout', 'loadKeyMap', and 'loadAccordion' events to MODx.Layout\n- Fixed bugs with File TV input renders\n- [#MODX-887] Properly standardized POST/REQUEST access methods for element processors\n- Fixed issues with user emails being sent in plaintext with no linebreaks; now HTML-based for the time being\n- Package Download tree now disables already downloaded packages.\n- [#MODX-885] Fixed missing break statement in cat output filter\n- [#MODX-844] Fixed ucfirst output filter, added ucwords output filter\n- [#MODX-869] Added missing descriptions for certain menu items\n- [#MODX-868] Fixed bug on settings grid where filter box was not firing on enter key\n- Fixed bug where hidemenu was not persisting in Quick Update Resource\n- Fixed bug with tree mask rendering before panel is rendered\n- [#MODX-747] Fixed issues with access grids update windows\n- [#MODX-803] Fixed DOM issues with TV mgr input property renders\n- [#MODX-805] Fixed attribute issues with TV web output renders\n- [#MODX-859] Changed login page loader box to say 'Loading...' instead of 'Saving...'\n- [#MODX-860] Fixed z-index issues across manager\n- Added a custom loadMask to MODx.tree.Tree objects to display when they're loading but not affect page focus\n- Added a custom loadMask to the Package Management download tree to display while loading the remote provider payload\n- Added in icon for package files\n- Added fsockopen as a fallback for transport package if allow_url_fopen or cURL is not enabled\n- [#MODX-856] Added cURL method of grabbing transport packages when allow_url_fopen is set to false\n- Fixed bug in property update where list grid was not hiding if list xtype was previously selected but not now\n- Fixed import properties where it was not properly handling descriptions\n- Fixed bug where ExtJS couldnt handle text/json header responses with fileUpload set to true in form panels\n- Fixed some DOM issues with Package Management\n- [#MODX-833] Temporary fix for modManagerLog message showing up in console\n- [#MODX-853] Changed source caption of view resource data\n- [#MODX-809] Adjusted formatting of View Resource data fields\n- Fixed bugs with Resource data page not loading fully, glitching tree\n- [#MODX-772] Fixed bug where plugin events were not showing enabled if filtered by name\n- Fixed user system event calls to pass proper arguments\n- Fixed bug where you could only load 1 Quick window at a time\n- Fixed bug with duplicate resource\n- [#MODX-845] If no setup options are specified, package installation will automatically proceed\n- Added parameter to the getNodes processor for resources/elements called 'stringLiterals' which, when true, does not encode the JS literals\n- Layout can now be toggled between tabs (default) and portal panels via the setting 'manager_use_tabs'\n- Nuked the Loading Box in MODExt\n- Changed clearCache key shortcut to CTRL+U (CTRL+SHIFT+U for PC users)\n- Fixed issue where folder resources couldnt be drag/dropped\n- Added some key-events: CTRL+H for hiding accordion, CTRL+U for clearing cache, CTRL+N for Quick Create Resource (PC users will need to add SHIFT to all those calls)\n- Fixed portal issues with Safari\n- Added a few events to MODx. JS object, cleaned up code\n- Added sanity checks to context/category create/update processors\n- [#MODX-766] Added check to prevent settings starting with numbers\n- Added ability to update plugin events and dynamically manage plugins associated with them by right-clicking on them in the Plugin Event grid\n- Added 'beforeSubmit' listener to MODx.Window\n- Adjusted TreeDrop code to allow for RTEs to utilize drag/drop features\n- [#MODX-827] Fixed typo in resource container help string\n- Added prevention fix to prevent dragging of non-elements/resources into content panes\n- [#MODX-770] Fixed bug with creating Symlink\n- Fixed issues with creating and editing a static resource\n- Fixed bug with treedrop that set boolean values to string representations; changed to 1/0\n- Fixed missing context menu item to remove new properties in a property set\n- Added functionality for Element Tag Builder to use descriptions of properties\n- [#MODX-817] Redid Clear Cache window to use MODx.Console\n- Lexiconized missing \"Copy to Clipboard\" string\n- Slight tweaks to MODx.Console to get messages to display final ending messages properly\n- Changed invokeEvent missing event warning to debug msg to prevent it from logging in every console output\n- [#MODX-818] Fixed issues with Quick Create where it didnt work in FF, missing lexicon strings\n- Added Visual Element tag builder when you drag/drop an element into a field\n- Resources/Elements can now be dragged from tree straight to Resource Content pane.\n- Removed Spotlight effect on dialogs; was unnecessary.\n- Fixed bug in Namespace creation window that was preventing namespace from creating\n- Added refreshes to comboboxes in Lexicon Management to refresh combos on Namespace/Topic creation to keep panels up-to-date\n- Fixed Safari issue with Element tree displaying funky on certain pages\n- Fixed issue in Safari where combobox trigger was on left side\n- Only set lexicon entries for context/user settings if they dont exist as system settings\n- Fixed issue with Actions panel causing accordion DOM to bug\n- Fixed issue with Quick Update not persisting class_key\n- Fixed some issues with persistent settings for Quick Update Resource\n- Fixed issue with Quick Update Resource content field being too long\n- Fixed invalid lexicon entry reference for quick create resource\n- Added Quick Create/Update Resource\n- Preview context menu option now is \"smart\" and builds FURLs and separate context references\n- Fixed invalid topic reference issue with modLexiconEntry::clearCache()\n- Fixed headers for connector responses\n- Added Quick Create/Update for all Element types\n- Fixed bugs with category setting in Element processors\n- Added Clear Cache checkbox option to all Element type forms\n- Fixed bug with Category dropdown\n- Fixed tv input properties forms from double-rendering\n- [#MODX-804] TV fields now fire resource change event\n- Fixed bug in Safari with TV fields being uneditable if panel is dragged\n- [#MODX-745] Added 'cancel' button to go back to policy page when updating a policy\n- [#MODX-573] Removed no-longer-applicable 'role' column from users grid, fixed capitalization issues in processors\n- [#MODX-762] Added in missing lexicon entries to hardcoded strings\n- Added modx.localization.js for i18n translations\n- Added indexes on modLexiconEntry table\n- Properly formatted lexicon strings still using sprintf\n- Fixed bug where created was not set on transport package creation\n- Made sure package grid paginates correctly if number of packages installed exceeds 20\n- Fixed Last Modified On on Lexicon grid\n- Optimized action, menu, language, content-type, lexicon, namespace processors\n- [#MODX-765] Added fix to prevent creation of blank system settings\n- Fixed bug in Safari with TV widget properties rendering\n- Consolidated resource getNodes processor, added access policy checks\n- Added sanity check to toJSON function in modConnectorResponse\n- Properly refactor element tree to point to correct processor\n- Added delegate processors for different modes in element tree\n- Updated Context policy attributes for missing attributes\n- Fixed invalid category reference on chunk update processor\n- Added log error messages if save()/remove() fails on modElement derivatives\n- [#MODX-771] Fixed invalid lexicon string reference in element tree\n- Added WARN log message when executing a system event that doesn't exist\n- Filled out missing access policy checks in element processors\n- Fixed incorrect and missing permission check in snippet get/getList processors\n- Fixed invalid lexicon reference in template processors\n- Optimized templateTV getList processor to use only one query\n- Optimized plugin event getList processor to use only one query\n- [#MODX-194] Added sanity checks to element names\n- [#MODX-792] Added check to prevent user from creating blank context, other sanity checks\n- [#MODX-475] Prevented adding contexts with _ in name; will auto-strip\n- [#MODX-796] Fixed check for valid passwords in setup\n- Fixed problematic reference to $_lang\n- Fixed improper log message reference in lexicon's reloadFromBase processor\n- Additional access control defects and warning messages resolved for anonymous users.\n- Fixed access control defect which prevented multiple policies from being respected per principal.\n- Fixed issue with Policy Attributes not adding b/c id was not passed in\n- Added 'save' event fire to Element/Resource formpanels\n- Properly setup on*FormRender events for Element classes\n- Added MODx.onSaveEditor check, which will fire on form save, that allows 3rd Party Components to execute JS code on Element/Resource saves\n- Major refactoring to modx.actionbuttons, to render faster, as well as properly register events and button configs\n- Allowed OnRichTextEditorRegister to return a string as well as an array\n- Added MODx.releaseLock(id), which releases the lock on a Resource for a given ID\n- Added MODx.sleep(ms), which sleeps the UI for a given number of milliseconds (useful in async calls)", "MODX Revolution 2.0.0-beta-1 (LastChangedRevision: 5070 , LastChangedDate: 2009-05-28 16:20:08 -0500 (Thu, 28 May 2009))\n====================================\n- Fixed issue with cacheable toggle on derivative Resource pages\n- Fix error message when reading expired messages in modDBRegister.\n- Fixed issue with login page JS\n- Fixed issue with derivative Resource classes JS not loading Page Settings data into submit\n- Fixed issue with utilities JS not loading at right time\n- Updated build.xml to produce beta releases.\n- Quick fix to prevent blank attribute referencing\n- Fixed issue with package attributes and skipping blank options\n- [#MODX-723] Fixed issue where preview pane was picking up CSS from preview\n- Updated xPDO to revision 333.\n- Fix issues with Page settings defaulting to 1 on resource creation\n- Adjusted order of JS utils loading to make for easier min-concat loading\n- Cleanups to JS to prepare for beta-1\n- Lexicon updates\n- Updating outdated copyright notices in source code headers.\n- Fixed hardcoded version number in setup.\n- Added request_controller system setting to indicate the front-controller file (default=index.php).\n- Fixed array_merge warnings in modLexicon.\n- Added back support for anonymous user access control.\n- Added support for returnUrl parameter to be sent to login processor to allow unauthorized responses to return to the original requested page directly (NOTE: this overrides manager_login_startup and login_startup parameters, but does not work with POST requests: these will simply return to the URL with only GET parameters).\n- Export lexicon now prompts for download of exported file\n- Enhanced User Group update/create screen to now have grids that allow you to assign Resource Group / Context permissions to that user group. This will help clear up confusion with the access relationships.\n- Fixed scope issue in accordion.css that was causing odd behaviours with panels in the main content\n- Adjusted setup procedures to allow for more lexicon support for pre-load checks\n- Adjusted setup lexicon to allow for multiple topics; conformed upgrade scripts and other references to match\n- Consolidated similar code in setup, esp. with regards to fatal errors\n- Added smarter checks for xPDO failures in connectors\n- [#MODX-744] Fixed issue with invalid display of num cleared on cache claering\n- Fixed bugs with updating packages from a remote provider\n- Made sure package attr returns '' if false\n- Fixed manager log to show username, not user ID\n- Standardized derivative resource form panels to move page settings to left\n- Tweaked tree menu headers\n- Minor IE overrides for top navigation and accordion panel.\n- Added support for modLinkTag properties as url parameters, with context reserved to indicate a context to send to makeUrl().\n- Fixed error in modLinkTag when passed invalid data.\n- Added '@RESOURCE' binding alias so as to deprecate @DOCUMENT binding\n- Fixed default language setting for modLexicon\n- Fixed a couple issues with the page settings checkboxes for resources\n- Removed deprecated _tx_.gif\n- Removed home icon and replaced with tab\n- Adjusted CSS to align main content page vertically\n- Trees now have fun new icons representing their types (this includes the resource, element and file trees)\n- Cleaned up the default.inc.php lexicon topic to remove any no-longer-used entries\n- Fixing typo in subtract output modifier\n- Fixed improper reference in TV property renders for mgr context\n- Updated xPDO to revision 329.\n- Improvements to sendError() behavior.\n- Added lock stealing processor and updated remove_locks processor.\n- Added steal_lock:true policy attribute to default Resource policy to allow lock stealing permissions by ResourceGroup.\n- modTemplateVar: Fix getValue() on `value` field by storing and verifying the value requested is cached by the same resource.\n- modResource: Add resourceId value to getMany() on modTemplateVar to identify the resource caching a value on the modTemplateVar instance.\n- modX: Set logTarget based on XPDO_CLI_MODE; ECHO for CLI and HTML for non-CLI requests.\n- modX: Add sendError() function to provide customizable, named error pages on FATAL or other critical error situations.\n- modX: Refactored sendForward(), sendErrorPage(), sendUnauthorizedPage() functions to allow an array of options and better handle FATAL errors.\n- modCacheManager now Caches related modContentType data to prevent unnecessary database connection/query on fully cached pages.\n- Fixed problem with modStaticResource truncating the content to the size of the static file by setting the content length header on non-binary content types.\n- Fixed problem with modStaticResource non-binary content types rendering the path to the static file rather than the actual content of the file.\n- Calling modX->log(MODX_LOG_LEVEL_FATAL) or modX->messageQuit() now logs the error to file and then renders {MODX_CORE_PATH}errors/fatal.include.php.\n- Updated to r325 in xPDO: xPDO method changes to getOption() and _log().\n- Update 'setup-options' ability in transport packages to allow for script-based setup options that will properly handle upgrades to setup options default values\n- Updated to r323 in xPDO: Revise xPDOTransport::writeManifest to make 'setup-options' be able to be an executable script to allow for dynamic form ability\n- Updated snoopy class to version 1.2.4 (used by magpierss).\n- [#MODX-535] Removed automatic setting of isfolder based on presence or absence of children.\n- [#MODX-499] Site start Resources now return base_url from modContext->makeUrl() if no scheme is specified (i.e. when expecting relative links).\n- Improved error reporting on modX->makeUrl() to show original $id value being passed in on failures.\n- modLinkTag no longer returns empty values on first pass of parser, allowing delays until the value returns a valid value.\n- Implemented modResource editor locking (added modResource methods: getLock(), addLock($user), removeLock($user)).\n- Implemented modResource locking features in all appropriate processors.\n- modResource->checkChildren() now uses modX->getCount() to determine if children exist.\n- Added steal_locks attribute to Context access policy.\n- [#MODX-728] Made sure config check dialog is hidden if no warnings are present\n- Package Installations will now skip license agreements / readme panels if none are specified\n- Made sure More Info in download panel can scroll\n- Fixed issue with spacing in setup options panel of package install\n- modCacheManager->generateScript(): Fixed PHP notice in log message on error.\n- modInstall: Modify _modx() function to call setDebug with E_ALL & ~E_NOTICE instead of E_ALL & ~E_STRICT.\n- Optimized queries in element tree to eliminate subqueries or queries in loop, reducing to O(n) instead of O(n^2n)\n- Made clear cache results a bit smaller\n- Refresh trees after clear cache\n- [#MODX-609] Clear cache menu item now loads results in an alert dialog. No longer loads a separate page.\n- Fixed to template getlist processor\n- [#MODX-671] Fixed bug with resource group access permissions being checked when not assigned\n- [#MODX-699] Fixed to allow usage of login processor without lexicons\n- Added Import/Export to element properties grids, which allows for file-based transporting of properties.\n- Fixed issues with comboboxes dropping down a blue screen\n- [#XPDO-28] Fixed problem with multiple file resolvers on vehicles with similar basenames cause directory contents to merge unexpectedly.\n- fixed PHP notice for missing elementType variable\n- fixed subcategory elements missing from display (was counting elements in parent category rather then subcategory to determine if the subcategory should be displayed)\n- Fixed issue with default properties in TVs being locked\n- Fixed no onTVFormPrerender\n- Made sure clearDirty is fired on TV panels\n- Tweaked the css and updated copyright year.\n- Refactored all index.php gateways to support constructor options set as $options in the various config.core.php files.\n- modCacheManager/modCache: Introduced cache partitioning allowing various cache provider implementations to target specific MODx cache partitions and provide custom (system/context/user) settings for configuration options to each: cache_system_settings, cache_context_settings, cache_resource, cache_scripts, cache_lexicon_topics, cache_action_map\n- modAccessibleObject: Refactored object and collection loader logic to improve cache hit rates.\n- modRequest: Fixed warning for undefined variable $fromCache.\n- modSessionHandler: Refactored write() method to only update access time when the session data has changed or at specified intervals before the data is made available for GC.\n- modSessionHandler: Added support for cache_db_session, a new configuration setting to allow session data to be cached when cache_db is enabled.\n- modTemplateVar: Allow getValue() to use a `value` field for data if already populated for a specific resource.\n- Commented out missing image in welcome.tpl (temporary)\n- Added couple of bugfixes to modDBRegister to prevent duplicate payloads and update existing messages.\n- Fixed bug where QuickUpdateChunk was persisting values\n- Added fix to prevent DOM id problems\n- Added clearCache checkbox to chunk editing to allow toggleable cache clearing\n- Optimized chunk processors\n- Added 'Quick Update Chunk' and 'Quick Create Chunk' options to Elements tree, which allows you to quickly edit or create chunks via a window straight from the Element tree on any page\n- [#MODX-718] Fixed bug where elements without a category wouldn't show\n- [#MODX-697] Fixed problem with deprecated role topic still in action build scripts\n- [#MODX-705] Removed random numbers causing Radio TVs to render improperly\n- Fixed bug that caused policy data to be erased when creating/saving/removing policy data\n- [#MODX-711] Fixed Update Context screen to properly pass correct PK\n- modDbRegister: fixed bug with expired messages not being removed if remove_read => false\n- modDbRegister: allowed messages to be updated/overwritten\n- Fixed modCacheManager::prepare() - was returning false on already-prepared contexts\n- Added support for nested categories for elements; categories can now have subcategories\n- Fixed to treestate to properly set treestate ID so restore can work properly\n- Fixed call to onDocFormRender to make sure ID is passed on Resource update\n- Fixed to getFiles processor for MODx.Browser to properly store URL parameter with the base_url prefixed\n- [#MODX-712] Fixed errors creating context settings\n- modX: Fixed potential error when invokeEvent() is called and executes a plugin with property sets and pluginCache does not contain the object\n- modCacheManager: Fixed error when building the pluginCache with property sets\n- modCacheManager: Fixed typo in parentSql that was breaking use alias paths option.\n- modCacheManager->generateContext(): Added support for Resources to be generated in multiple contexts via modContextResource.\n- modParser: Removed errant log() statement in parseProperties().\n- modParser: Fixed problem in parsePropertyString() when passing `escaped` property values containing semi-colons (;).\n- Added in necessary reloading functions to ColumnTree\n- Fixed issue with column tree's context menu overriding the ID\n- modManagerResponse: Detect if controller responses are error arrays and render using error.tpl appropriately.\n- [#MODX-693] redirect bug - modResponse logic error\n- Moved core/config/version.inc.php to core/docs/version.inc.php\n- layout/tree/resource/getnodes.php: Additional optimization to reduce memory usage and improve performance when opening Resources containing a large number of children.\n- modConnectorResponse->toJSON() optimized to greatly reduce memory usage and improve performance with large result sets.\n- [#MODX-691] allow User Settings to be saved from prop. grid\n- Fixed bug with documentMap\n- Fixed issue with default tv render panel for resource page\n- [#MODX-690] Fixed a few events names registered in the system_eventsnames table during build/install\n- Added id's to element and category nodes for informational purposes (missed one spot).\n- Added id's to element and category nodes for informational purposes.\n- Updated drag and drop behavior to update context_key of all child Resources when dropping a container on a different context node.\n- Modified modTransportPackage.manifest field from MEDIUMTEXT to TEXT in order to handle large manifests.\n- Fixed aliasMap broken in recent cacheManager refactoring.\n- Added helper functions to MODx.tree.ColumnTree\n- Added DD events to ColumnTree\n- Added missing column tree CSS\n- Added UI for adding property sets to PluginEvents\n- Added cacheManager object checks to verify for PHP4 installs\n- modCacheManager->generateResource(): added validation of the modResource primary key before attempting to cache a record.\n- modUser: modified storage of session data to use the modUser primary key value to isolate values associated with a specific user; this will allow users to login as multiple users on the back-end and/or front-end without affecting the session data associated with a specific user.\n- modX->_initSession(): Enable session_gc_lifetime configuration setting to set session.gc_liftime ini setting regardless of what session handler is configured.\n- modPluginEvent: Added the ability of plugins to utilize Property Sets by allowing a plugin registered to a particular event to attach a Property Set and make it available during processing.\n- Fixed warning with loading of RTEs in resource page\n- [#MODX-674] Fixed content-dispo combobox bug\n- Removed allowBlank: false check on menuindex to allow for dynamic creation\n- Added in missing lexicon entries for prior menuindex commit\n- [#MODX-678] Added back in 'menuindex' field to resource panels\n- Added missing modX::__construct() options parameter.\n- Allow for extending of MODx.panel.ResourceTV by making reference to modx-resource-template field dynamic\n- Fixes for RTE loading\n- Fixed issue where smarty template path was not being reset if 3PC set path to something else\n- modX constructor now accepts a second parameter containing an array of options to be set in the config\n- Major refactoring of modCacheManager to provide more granular caching options\n- modCacheManager now accepts options, based on changes to xPDOCacheManager, and provides access via getOption()\n- generate*() methods now all return data as well as cache it to a specified cache_handler unless otherwise configured\n- modX->getCacheManager() no longer supports MODX_CACHE_DISABLED or config['cache_disabled']; the cacheManager is required, though you will still be able to effectively turn off all caching in the future via this setting (this will be worked back in)\n- manager/controllers/system/refresh_site.php changes to better target things to remove from the cache\n- Introducing modDbRegister and the modx.registry.db package, providing a database modRegister implementation.\n- Added new system settings for individual cache areas, i.e. cache_system_settings, cache_context_settings, cache_lexicon_topics, cache_scripts, etc.\n- modCacheManager: Various fixes and adjustments to latest refactoring, including clearCache improvements.\n- manager/controllers/system/refresh_site.php: Improvements to default clearCache call.\n- modCacheManager: converted generateActionMap() to support configurable cache implementations\n- Updated modAction->rebuildCache() and modManagerRequest->loadActionMap()\n- Additional tweaks to manager/controllers/system/refresh_site.php\n- Updated xPDO externals to revision 308\n- Removed unnecessary comments from the reg* functions\n- Moved all manager pages JS/CSS to inside HEAD tag using the reg* functions; this improves speed and validation of the manager\n- Fixed the way 3PCs handle their controller files. NOTE!!! This means that you no longer need a \"core/controllers\" file in your 3PC; just set the namespace path correctly, then set the controller in your modAction.\n- Added an ability for mgr pages to utilize regClientStartupScript and other reg* functions to make pages load faster and move JS/CSS to HEAD tag\n- modX->getEventMap() - Made sure prepare() creates a valid statement before calling execute()\n- Updated modStaticResource to set headers in getFileContent() for now, though this needs to be refactored for flexibility.\n- Fixed issue with saving TVs from create resource processor\n- [#MODX-637] Fixed issue with TVs not reloading on changing template in new resources\n- [#MODX-663] Fixed various issues with modAction creation\n- Fixed issue with MODx.Browser uploads not refreshing the main view\n- Fixed publishedon default date setting\n- Fixed date TV default value\n- Fixed default setting for symlinks\n- Fixed issue with Symlink/WebLink class_key storing\n- Fixed issue with textfield editing in Safari on Property Set grid\n- [#MODX-662] Fixed duplicate issue with elements\n- Fixed issue with property sets page and property lock\n- Fixed name issue on duplicating elements\n- Fixed symlink page setTimeout issue\n- Fixed missing file inclusions\n- Fixed element tree where categorized templates weren't showing\n- Added editing ability to resource's publishedon date\n- Fixes to package downloader panel due to ID conflicts\n- Adjusted modTransportPackage::transferPackage to rename incoming file to [signature].transport.zip rather than basename($source)\n- Fixed xml/json response classes to properly work\n- Added permission \"unlock_element_properties\", which gives ability to unlock editing of default element properties.\n- Added implementation of above permission into element properties grid\n- Fixed some logic issues with the lockMask\n- [#MODX-561] Added \"Locked\" ability to default properties for elements\n- [#MODX-633] Fixed issue with add another not respecting parent\n- Fixed TV access panel not working on new TVs\n- Fixed state management with tree nodes\n- [#MODX-661] Fixed URL TV input, where it was not setting prefix value\n- [#MODX-659] Fixed bug where root-level docs couldnt be updated b/c of parent issue\n- Fixed bug with parent being assigned to 0 always in derivative Resource classes\n- Made sure bad resources (where parent = id) are ignored when building the context cache files.\n- Fixed parent bug in controllers\n- Fixed transport.data.php with 'namespace' key on modActions\n- [#MODX-622] Updated top menu structure to be more consistent.\n- Fixed error if properties are null\n- [#MODX-651] Fixed bug when deleting a propset, would not empty grid\n- Fixed to resource page combos not setting display value correctly\n- [#MODX-658] Fixed issue where in TV -> Create, templates were not showing\n- Fixed template nodes to properly sort by templatename\n- Adjusted resource menus and such to refer to a 'Resource' without a specific class_key as 'Document' when applicable, with the exception of talking about Resources in the generic sense\n- Added Duplicate option to Property Sets\n- Fixed bug where template inheritance for resources wasn't happening\n- Fixed symlink page\n- [#MODX-632] Updating xmlrpc to 2.2.1\n- Corrected logic in setup to allow forced PDO emulation mode (XPDO_MODE == 2).\n- Added `category` field to modPropertySets; they can now be categorized\n- Enhanced UI to support new modPropertySet category ability\n- Modified MODx.Window so that the ENTER key submits the form\n- Added more IDs to element forms\n- Added ability to \"remove\" overridden properties, but only ones that are not in the default propset (ones that are should \"revert\")\n- Fixed OnWebPagePrerender event not firing as expected.\n- modOutputFilter: Refactored date modifier to return '' if the timestamp encountered == 0 or -1.\n- modOutputFilter: Added strtotime modifier.- Refactored connectors to execute in the context from which they are called, rather than their own context.\n- Updated xPDO to revision 304 for new xPDOFileVehicle feature to respect XPDO_TRANSPORT_RESOLVE_FILES options.\n- [#MODX-562], [#XPDO-24], [#XPDO-25], and [#XPDO-26] Updated xPDO to revision 302 to resolve various issues regarding transport packages and model generation.\n- [#XPDO-23] and [#MODX-604] Updated xPDO to revision 298 to resolve nesting error when logging messages during installation with improper cache directory permissions.\n- Added modPropertySet->getElements() method as shortcut to get all proper modElement instances available to the set.\n- Added overridden modElementPropertySet->getOne() to get related Element using the proper element_class value.\n- [#XPDO-21] Updated xPDO to revision 290 for updates to xPDOObject::addOne() and addMany().\n- [#MODX-553] Unpublished and deleted Resources now ignored properly in modRequest::getResource().\n- [#MODX-553] Core setup now automatically adds an ACL to the web context for members of the Administrator group.\n- Core setup now updates the Administrator group ACLs for accessing the mgr and connector contexts with an Authority of 0 (highest authority).\n- Modified OnUserNotFound event handling not to rely on references which no longer work properly with recent changes to property handling.\n- Added overridden modElement->get() to handle converting legacy property strings stored in the database.\n- Added modPropertySet class to represent persistent sets of properties that can be applied to modElement instances.\n- Added support for modElements to relate modPropertySet objects via modElementPropertySet (many-to-many).", "MODX Revolution 2.0.0-alpha-6 (LastChangedRevision: 4485 , LastChangedDate: 2008-11-25 11:58:49 -0600 (Tue, 25 Nov 2008))\n====================================\n- [#MODX-395] i18n'ed the modMail classes, added lexicon topic 'mail' for handling mail strings\n- Added check to make sure user cannot browse to subdirs with ../ in connector processor fetching\n- [#MODX-482] Implemented code to remove setup/ directory when box is checked.\n- [#MODX-408] Fix atrocious grammar in mail reception message\n- Fixed labels for static resource page\n- [#MODX-518] Make sure clearing cache clears registry output from package\n- Fixed in_array() checks against $_currentTimestamps in xPDOObject::save() that prevented timestamp/datetime fields from saving 0 values.\n- [#MODX-512] Fixing check in setup to make sure core/packages is writable\n- Fixed bug with RTE loading and saving\n- Changed 'Provisioner' references to 'Provider' in UI for nomenclature consistency purposes\n- Added lexicon load to resource processors\n- Fix error on resource view when template is empty.\n- Added namespace filter to settings grid\n- Fixed import trees\n- Hide the resource ID field if a new resource\n- [#MODX-514] Fixed issue with pub_date/unpub_date not being reset properly\n- [#MODX-484] Added missing ht.access sample to web context files in included in transport package.\n- Modified modWorkspace vehicle attributes to XPDO_TRANSPORT_UPDATE_OBJECT => false\n- Updated xPDO to revision 284 for new xPDO package-aware vehicle features when loading classes.\n- Slight styling improvement to grid to make alt-rows more apparent\n- Added clearCache() functions to modLexiconTopic, modLexiconLanguage\n- Added 'collapsible' options to the options tabs of resources. Can now collapse them to show only the content editor.\n- Prevent blank property value names\n- Adding css classes to modext components for easier styling\n- Fixed some issues related to installation of packages, namely dealing with the setup-options attribute and resolver handling\n- Added _build/build.local.xml to prepare an svn development copy for execution; builds core transport, minifies and concats the javascript and puts it in place, etc.\n- Slight fix to login box and css styles to get checkbox checked css to render properly\n- Updated xPDO to revision 281 to get fix to xPDOObject::save() when updating fields with NULL values.\n- Styling updates; make form fields bigger, tabs bigger, menus bigger...basically pretty up the UI\n- Fix to typo in createTable in modInstallVersion\n- Implemented version-specific upgrades to setup/\n- Updated xPDO to revision 275 (xPDOObject datetime/timestamp handling improvements, xPDOTransport pre-existing object restoration features, and more).\n- Changed System Events action to Error Log Viewer, which now allows you to view (and clear) the error log from the manager\n- [#MODX-509] Fixed issue with refreshing of incorrect node in dragdrops on trees\n- Fixes to CSS in setup, moved error box to fixed bottom right, i18n'ed more stuff, cleaned up HTML and simplified outputs\n- Fixed issue where the path for processors could not be overridden by changing the parameters for handleRequest in modConnectorRequest to an array of options\n- [#MODX-501] Fixed issue where trees didn't refresh when package was installed. All trees now refresh.\n- Fixed bug with duplicating resources\n- [#MODX-505] Fixed issue with creating weblink redirecting improperly\n- Fixed issue with emptying recycle bin and root-level resources\n- [#MODX-508] Weblinks are now not hidden by default\n- Fix missing published checkboxes in resource derivative classes\n- Applied patch to fix issue with label click of checkboxes not changing value\n- [#MODX-507] Fixed bug where Published checkbox wasnt showing in resource panel\n- Fixed bug in filetree that would scroll up topmenu\n- [#MODX-507] Adding in textbox for parent ID for now, will come up with better solution later\n- [#MODX-506] Fixed bug where cache wasn't cleared on drag/drop in tree\n- Fixed bug in modPackageBuilder that was preventing deletion of existing package directories and files.\n- Added constants MODX_INSTALL_MODE_NEW, MODX_INSTALL_MODE_UPGRADE_EVO, MODX_INSTALL_MODE_UPGRADE_REVO\n- Extracted install->test() to a separate class, then i18n'ed the test strings\n- LOTS of phpdoc additions to all processors, including parameter lists for each processor\n- Removed any last trace of modules from Revolution\n- Added phpdoc information to processors\n- Properly clear cache on install/uninstall/remove of packages\n- Removed \"require_once MODX_PROCESSORS_PATH.'index.php';\" from all processors\n- Only show 'Update Package' if the package comes from a provider\n- Fixes to get browser working with TinyMCE\n- Fixed issue with forced removing of packages not properly removing the resolvers\n- Standardized modRequest/modResponse methods across all derivatives (i.e. modRequest::handleRequest() always calls modRequest::prepareResponse(), which calls modResponse::outputContent()).\n- [#MODX-478] Fixed typo in lexicon import/export that prevented window hiding\n- Fixed issues with Symlinks\n- Fix to TV output/input renders when loading in a context other than web/mgr\n- Fix to invokeEvent to prevent unwanted caching of event name if plugin executes more than one event per runtime\n- [#MODX-424] Added readme viewing to package grid\n- Added ability to delete multiple element properties at once via a multiple row handler\n- [#MODX-488] Removing double click from properties grid for 'name' field to prevent unwanted breaking\n- Added back in setDirectory to modConnectorRequest\n- [#MODX-292] Properly format system settings editedon value\n- [#MODX-293] Properly format editedon for lexicon entries\n- [#MODX-481] Fixed rendering issues in element property grid columns\n- [#MODX-479] Fixed issue where first snippet property edited didn't show value\n- [#MODX-480] Fixed issue with lexicon entry update/create not loading proper topic\n- [#MODX-474] Removing package builder menu item from build script\n- [#MODX-456] Fixed issues with element property grids\n- Fixed MODx.grid.LocalGrid store bugs when dealing with grouped data\n- added pageSize and pageStart config items to MODx.grid.Grid\n- Fix to MODx.grid.Grid in case listeners are provided, dont ignore context menu\n- [#MODX-466] Fixes to dropdowns for element categories, field issues\n- [#MODX-115] Some fixes to rendering issues with comboboxes/datefields on Safari\n- Updated xPDO to rev 265 for improvements in xPDOValidator allowing multiple rules to be evaluated per column.\n- Refactored modError completely, removing all derivative classes and introducing modManagerResponse and modConnectorResponse to handle formatting modError responses appropriately.\n- Added modRequest::registerLogging() and relocated logic for detecting and taking action on register logging parameters out of loadErrorHandler().\n- Refactored modArrayError to remove Smarty dependencies, moving them to a new derivative, modSmartyError which the manager UI can utilize explicitly.\n- Added element property panel to all Element panels for managing default properties (except Modules).\n- Added modElement->setPlaceholders() to set placeholders and return any global placeholders that might need to be restored after an element is processed.\n- modChunk and modTemplateVar now restore any placeholders from the global scope after processing any local properties with the same name.\n- Added properties as local placeholders when processing modTemplateVar instances to match behavior of modChunk/modTemplate.\n- Updates to snippet property editor.\n- Added properties to modTemplateVar to make them consistent with all other elements.\n- Modify modX::getChunk() and runSnippet() to process those elements as non-cacheable instances.\n- Added modResource::getContent() and setContent() functions for extensible control of accessing raw source content.\n- Modify modElement::setProperties() and modTag::setProperties() to handle various property data formats.\n- Updated modParser::parsePropertyString() to handle local property xtypes from UI and convert legacy types.\n- Added isCacheable() and setCacheable() to modElement and modTag classes for direct, extensible control of caching.\n- Modified behavior of modTemplate/modChunk not to prefix properties turned into placeholders with the name of the element.\n- Added getContent(), setContent(), getProperties(), and setProperties() to modTag and derivatives.\n- Added modParser::parsePropertyString() to parse element properties from string or array representations.\n- Updated modElement::process() behavior to check cache sooner and avoid unnecessary source content access and other processing.\n- Additional foreign key and sorting indexes added to modElement classes.\n- Added properties to all modElement classes except modTemplateVar.\n- Added setProperties() to modElement for setting a set of default properties that will be used by the element.\n- Added getProperties() to modElement for getting the properties to be used when processing the element.\n- Added getContent() and setContent() function to modElement and provided overrides in the appropriate subclasses.\n- Removed modTransportPackage::loadTransport(); the manifest should always be loaded from the file.\n- Updated xPDO to rev 262 for improvements in the xPDOTransport manifest format.\n- Updated xPDO to rev 258 for bug fix in new xPDOObject::_setRaw() function with array and json phptype fields.\n- Updated xPDO to rev 256 for bug fix in xPDO::getSelectColumns() and new xPDOObject::_setRaw() implementation to resolve issues with native php types when using fromArray().\n- Added modPackageBuilder->setPackageAttributes() function for easily adding transport-level attributes to a package.\n- Updated xPDO to rev 252 to get new features allowing transport packages to carry transport attributes.\n- Added numerous foreign key and sorting indexes to site_content table (modResource) to improve performance of common queries.\n- Changed modX::changePassword() implementation to call modUser::changePassword().\n- Added getResourceGroups() and getUserGroups() to modUser class to retrieve those things and cache in session.\n- Renamed and moved modX::_checkPublishStatus() to modRequest::checkPublishStatus() and renabled this functionality.\n- Deprecated and moved modX::checkPreview() implementation to modResponse.\n- Added view_offline attribute to default Context access policy.\n- Removed deprecated and invalid modX::makeFriendlyURL().\n- Removed deprecated modX::webAlert() function.\n- [#MODX-364] Results of regClient*() functions are now cached into the Resource cache files to solve error on cached pages with cached snippets.\n- Removed deprecated modX::mergeDocumentMETATags() and moved feature to modResource::mergeMetatags() and modResource::mergeKeywords().\n- Removed deprecated modX::makeList() function.", "MODX Revolution 2.0.0-alpha-5 (LastChangedRevision: 4273 , LastChangedDate: 2008-10-09 12:42:42 -0500 (Thu, 09 Oct 2008))\n====================================\n- [#MODX-88] Move version checking to setup script and add notifications.\n- [#MODX-66] Change the way properties work within the scope of a chunk; placeholders set by the chunks properties are now removed after the chunk is processed.\n- Added modX::unsetPlaceholder() and modX::unsetPlaceholders() functions.\n- [#MODX-329] Fixed error with browser \"remembering\" user even when \"remember me\" is not checked. Was always using the system setting regardless of rememberme.\n- [#MODX-380] Created modSymLink resource class which forwards requests to other resources without changing the URL (as opposed to modWebLink which redirects).", "MODX Revolution 2.0.0-alpha-4 (LastChangedRevision: 4213 ,LastChangedDate: 2008-10-01 12:18:41 -0500 (Wed, 01 Oct 2008))\n====================================\n- Updated xPDO to rev 248\n- More log messages for modPackageBuilder\n- Fixed some bugs with MODx.Browser\n- Enabled specific path setting for MODx.Browser\n- Fix to remove redirect to system settings if version info differs.\n- Added MODX_SETUP_KEY to setup to identify the distribution type and allow setup logic to be conditional based on this information.\n- Introduced additional default policy attributes and policy checks throughout the controllers and processors for more robust access control.\n- [#MODX-349] Added processor and menu item to reload your own access policies without logging out and logging back in.\n- [#MODX-349] Added processor and menu item to flush all user sessions from the database.\n- [#MODX-349] Modified user policies to cache policies by Context; previously policies cached for one context were being applied to other contexts when switching or accessing both from the same browser session.\n- Updated xPDO to revision 246 to fix problem with modLexiconEntry rows being duplicated in upgrades after deleting modLexiconFocus records.\n- Modified Ant build to automatically compress and concatenate js files (SVN users cannot use compress_js option without performing the complete-wc task in build.xml).\n- Updating xPDO to revision 234.\n- Added support for logging to registers through any modError instance when loaded by modRequest::loadErrorHandler().\n- Removed modRegisterHandler and added logging helper functions to modRegistry.\n- Updating xPDO to revision 233.\n- Updated modAccessibleObject::loadCollection() based on xPDO::loadCollection() changes.\n- Updating xPDO to revision 231.\n- Various model updates to reduce memory usage [convert foreach with fetchAll() calls to while with fetch()].\n- [#MODX-137] Locked Elements now editable by users with the Admin policy attribute edit_locked (not locked as in being edited by another user, but locked explicitly in the Element attributes).\n- Moved makeUrl logic to modContext class and modX now determines which context to use when building the URL.\n- Introduced modX->getContext() to retrieve, prepare and store context configurations in modX->contexts array for reuse during the single request\n- Added _config, _systemConfig and _userConfig to hold on to various parts of the configuration settings before they are merged for use, allowing other functions to remerge the settings as needed.\n- Fixed modX->switchContext() to clear all contextual/user setting overrides and reload the bootstrap _config, _systemConfig, and make use of the modX->contexts array.\n- Implemented UI ability to choose vehicle-specific attributes when adding vehicles to packages\n- Added dynamic value replacement of {setting_key} in user settings in modX->getUser().\n- Added function to grab the request parameters to MODx.request\n- Added missing permission check on empty_cache attribute on refresh_site controller/processor.\n- Updated xPDO to revision 218.\n- [#MODX-282] Fixed bug where grid would show non-existent page in lexicon/settings grids\n- Removed permission check on logout action; doesn't make much sense.\n- Proper formatting of editedon time in system settings grid\n- Added System Settings \"Update Setting\" window for more detailed editin\n- Rebuilt core data files for the transport.core.php script and made correction to core namespace path to the value {core_path} which is calculated at run-time.\n- [#MODX-263] Access policy update grid moved to separate page\n- Created panel for editing access policies\n- [#MODX-277] Changed 'setting' to 'name' at top of System Settings grid\n- [#MODX-283] Fixed combo-boolean combobox to prevent overwriting of form variables. this was a bizarre bug.\n- Allowed modPackageBuilder to now use dynamic, on-the-fly namespaces. Separated out registerNamespace() from create()\n- Added support for loading extension_packages via configuration settings before the session is initialized.\n- Fixed dynamic value replacement of {setting_key} in system and context setting generators.\n- Updated xPDO to revision 216.\n- Added class_key field to modUser class/table to support modUser derivatives.\n- Fix to new modLexiconEntry table structure (was not installing due to NOT NULL and no default value).\n- Removed modResource::hasAccess() function to make sure and avoid confusion with security.\n- Add default admin user to the Administrator modUserGroup with a modUserGroupRole of 2 (SuperUser) on new installs and upgrades.", "MODX Revolution 2.0.0-alpha-3 (LastChangedRevision: 3867, LastChangedDate: 2008-07-22 08:44:38 -0500 (Tue, 22 Jul 2008))\n====================================\n- [#MODX-210] Changed no-longer-valid help text for resource panel\n- [#MODX-216] Fixed bug with pub_date/unpub_date for the Resource panel\n- [#MODX-213] manually entered passwords not being displayed after saving\n- Added editability to packages grid\n- [#MODX-205] Fixed category saving\n- [#MODX-196] Fixed snippet category error in IE7\n- Created modInstallError for base processing methods\n- Added object support to modInstallJsonError\n- [#MODX-201] Fixed bug with Category combo that prevented adding in a custom category\n- [#MODX-200] Added colored Not Installed text to not installed packages\n- [#MODX-70] Removed top buttons, as they are unnecessary and cause more problems than they are worth.\n- [#MODX-174] Language setting in setup is not loaded.\n- Note: renamed the language file to en.php to match the adopted IANA standard codes (see #MODX-187)\n- [#MODX-26] Manager User creation problems\n- Corrections to new user account email\n- Added MODX_URL_SCHEME define and url_scheme configuration setting\n- Added MODX_HTTP_HOST define and http_host configuration setting\n- Changed \"Modules\" top menu to \"Components\" top menu. Component developers are encouraged to put their 3rd party menus in there.\n- [#MODX-83] Radio Options not working in TV\n- [#MODX-103] Fixed blank template change warning message.\n- [#MODX-173] Language setting in manager pages is not loaded.\n- Removed ucwords on getlist processor for lexicons.\n- Fixed feed_modx_security/news keys in the build file.\n- [#MODX-184] Fixed show in menu checkbox, should have been labeled \"Hide Menu\" since the opposite is true in the database. Changed to match DB column properties.\n- [#MODX-190] Fixed bug with missing duplicate snippet error message\n- Added check for existing name in snippet duplicate processor\n- Updated build.src.url to branches/revolution\n- Fixed import html/resources\n- Fixed action pointer if version is incorrect", "MODX Revolution 2.0.0-alpha-2 (LastChangedRevision: 3841, LastChangedDate: 2008-07-15 09:18:24 -0500 (Tue, 15 Jul 2008))\n====================================\n- Adopting new product name, MODX Revolution, and changed version to 2.0.0\n- Fixed bug with content type grid\n- Replaced 'gender' with Role column in Users grid\n- [#MODX-182] Fixed invalid reference in tv/create.js\n- Fixed TV input type dropdown, added proper processor/connector\n- changed xPDOCriteria calls to more abstract newQuery ability\n- Added attachment capabilities to modMail/modPHPMailer classes\n- Added setHTML method to modPHPMailer\n- Updated documentation for modValidator class\n- Added explicit header call to set text/json; charset=UTF-8 on responses from modJSONError\n- Remote package installation now works.\n- Fixed invalid schema relationships with transport providers/packages\n- Included check for xPDO transport service config to prevent warning\n- [#MODX-108] Added more database info to the site info page - contrib by sottwell\n- Finished UI for modStaticResource\n- Added some inline documentation to widgets for help\n- Set a more appropriate default resolver target\n- Removed unnecessary package parameter from modPackageBuilder::buildSchema\n- Removed unnecessary package setting\n- Added buildSchema function to modPackageBuilder\n- Added tooltips to elements and contexts in the resource/element trees\n- Fixed bug in Module update page\n- Added a qtip to document tree nodes so they display resource longtitle/description in a tooltip\n- Moved styles to gray theme to prepare for css work\n- Weblinks now functional\n- Fixed slight bug with FF3 and panel collapsibility\n- Fixed plugin properties\n- [#MODX-162] Fixes problem where vehicle grid is not refreshed on 2nd build, as well as resets the form\n- Added 'success' event to MODx.FormPanel\n- [#MODX-172] Fix to option values for setup in IE 6. Fix by kmd.\n- [#MODX-166] - Fixed config cache issue - fix provided by kmd\n- [#MODX-165] could not save Template element - fix provided by SA\n- Fixed and cleaned up the actions/menus JS and combos\n- Removed unnecessary tertiary expression (check is already handled by the function)\n- [#MODX-131] Fixed Apache crash and enabled Tools -> Action\n- Added fix to _() JS function to allow for parameter passing:\n String: 'Testing: [[+hello]]';\n JS call: _('testkey',{'hello': 'Success!'});\n Result: 'Testing: Success!';\n- [#MODX-148] Added support for [[+placeholder]] tags in lexicon strings. i.e., with a lexicon string with key 'test' and value: 'Test me: [[+hello]]'\n Programmatically:\n $modx->lexicon('test',array('hello' => 'Success!');", " Tag:\n [[%test?hello=`Success!`]]\n- Fixed to typo on system info JS\n- Added namespacing ability to the addDirectory() and load() methods of modLexicon. Used like so:\n $modx->lexicon->addDirectory('pathhere/','testNS');\n $modx->lexicon->load('testNS:fociname');\n- [#MODX-102] fixed missing lexicon entries in php4\n- Added OnHandleRequest event, invoked before anything occurs in modRequest::handleRequest().\n- Set the modLexicon::_lexicon to an empty array even if nothing was loaded.\n- Added modX::switchContext(string $contextKey) function to make it easy to switch contexts using a plugin and the new OnHandleRequest event.\n- Fix to properly submit the content field for resources (should also handle multiple RTEs now)\n- Fixed typo in lexicon reference in event getlist\n- Fix to MODx.load to return multiple objects if they exist\n- General JS doc updates\n- Added MODx JS class, which allows for xtype loading via MODx.load()\n- Some JS doc updates\n- Fixed modErrorHandler to ignore suppressed errors like a proper error handler is expected to.\n- [#MODX-109] Fix bug with profile page loading of date.\n- Reconfigured context update window to separate into tabs for easier viewing and rendering\n- Changed TV resource group panel to a grid, instated proper remove/update code\n- [#MODX-126] Implemented 2 new modSystemSettings: feed_modx_news and feed_modx_security for dynamic setting of the RSS feeds in the welcome pane of the manager\n- [#MODX-137] Removed locked check until a resolution is made on locked elements.\n- [#MODX-119] Corrected issue with file editor stripping out SCRIPT tags. Was using $_REQUEST instead of $_POST so the values were sanitized by the request handler.\n- Updated Template management to a MODx.FormPanel\n- Altered the way modLexicon loads multiple foci for PHP4 compatibility\n- Added modLexicon::addDirectory, which adds a directory when loading lexicon foci\n- Properly load TV widgets and i18n their strings\n- Fixed bug with modLexicon and $modx reference\n- [#MODX-133] Prevent elements from being dragged into different types\n- [#MODX-125] Fixed saving pub/unpub date on resources\n- [#MODX-106] Removed assets/images check.\n- Configured Object field in Package Builder to be a combobox that loads a dropdown of the selected class_key\n- Added ability to remove vehicles from not yet built package\n- Added MODx.grid.LocalGrid as abstract class of local-data-based grids\n- Added MODx.panel.Wizard as abstract class of wizard panels\n- [#MODX-121] Fixed top menu loading incorrectly when clicking on icons\n- Fixed TV management page, specifically with TV->Template access\n- [#MODX-118] Fixed bug with creating/removing/updating directories from Directory tree\n- Added MODx.combo.ContentDisposition\n- Added ability for MODx.toolbar.Actionbuttons to support formpanel as an alternative for form config parameter\n- Added $modx->config properties to MODx.config JS array sent\n- Fixed update resource TV loading\n- [#MODX-113] Fixed bug in Safari with scrolling in grids, apparently Safari doesn't like Ext's autoHeight\n- Removed legacy tpl's in settings/ dir\n- [#MODX-107] Fixed tree refreshes when resource is saved, both in create and update. Update will now refresh only the parent node of the resource being saved, which speeds up save time\n- Fixed issues with TV Panel loading improperly on new resource\n- [#MODX-114] Prevented JS error from occurring when using page settings checkboxes\n- [#MODX-116] Fixed text for removing a category\n- Fixed Resource pages to allow for Resource Groups to be assigned access prior to Resource creation, as well as making grid not save until 'Save' is clicked\n- Fixed Template pages to allow for TVs to be assigned access prior to Template creation, as well as making grid not save until 'Save' is clicked\n- Fixed TV pages to allow for templates to be assigned access prior to TV creation, as well as making grid not save until 'Save' is clicked\n- Fixed module update, removing legacy code\n- Fixed plugin event grid: now can be used via create or update, also properly handles events, does not save until \"Save\" button is clicked on action bar", "MODx 0.9.7-alpha-1 (LastChangedRevision: 3664, LastChangedDate: 2008-04-28 12:43:15 -0500 (Mon, 28 Apr 2008))\n- Updated ExtJS from version 2.0 to 2.0.1\n- [Trac#20] When creating new document, make the 'Log Visits' checkbox respect the main configuration setting.\n- [Trac#9] Converted Database Tables tab in System Information to use Ext Grid.\n- [Trac#40] Default role settings are now set correctly when saving roles to the database.\n- [Trac#4] Converted Modules section to use Ext interface.\n- Added new resource import routine for creating resources from static content on the file system, as any valid modResource derivative.\n- Introducing context support to the manager resource trees.\n- [Trac#32] Display correct message counts for the Inbox section on the Welcome page.\n- [Trac#31] System Configuration page always showing 'New Install' message. Refactored code to use $modx->version.\n- [Trac#25] Several bugfixes and refactorings to make the Messages section function correctly.\n- [Trac#6] Remove Locks not working from the top menubar.\n- Removed custom_contenttype from system_settings and manager interface.\n- Converted and refactored Import HTML tool for the new APIs.\n- [Trac#29] Resource checkboxes on settings tab not showing accurate values when editing.\n- [Trac#28] Cache not cleared when resources are saved and the clear cache checkbox is checked.\n- [Trac#27] Cached modResources were not loading or rendering since getResource() moved to modRequest from modX. Cache files generated with new reference to the modX object ($this->modx vs $this).\n- Remove logic in modResource::addOne() that was disallowing binary content types.\n- Add conditional to check for $GLOBALS['https_port'] before attempting to use it.\n- Several fixes to modResource processors involving saving of boolean fields via checkboxes; make sure POST is filled with unchecked fields having a value of zero.\n- Upgrades now work for previous 0.9.7 installations\n- Add-on installation has been removed from setup in preparation for adding it to the manager itself.\n- Removed modManager095 and all related legacy support for ManagerAPI extender, moving this functionality to modManagerRequest.\n- Added/updated delegate controllers, templates, and processors for modWebLink and modStaticResource.\n- Added new static resource option to document tree context menus.\n- Fixed bug with chunk update processor deleting the chunk content.\n- [Trac#19] Bugs with password on user creation/update; was saving plain password (not encoded).\n- Introduction of new setup using transport packages (new installs only for now).\n- Modified modRequest::sanitize() to no longer strip old-style tags.\n- Moved MODx classes and maps out of core/xpdo/om/modx095 and into core/model/modx.\n- [xPDO] Add support for package specific include paths for models.\n- Refactored INCLUDE_ORDERING_ERROR to manager/includes/accesscheck.inc.php\n- Begin adding input and output filtering to all MODx elements and tags (modElement and modTag derivatives), including default filter implementations based on phX (not yet working).\n- Begin refactoring modx095 package to utilize xPDOQuery (modResource::getOne()).\n- [xPDO] Fixed error in xPDOObject::remove() that was trying to call the toCache function on xPDOObject rather than xPDO.\n- Added checkForLocks func to modx.class.php\n- Added checkIfIn to modmanager095.class.php, to do the annoying check if in manager in all the pages\n- Added splitter class for tables to get the line effect found in user management\n- Added ul.no_list to get list effect without bullets\n- Added formhandler.js - handles validation in forms by sending form through AJAX call. If response != true, then outputs response to a div with id 'errormsg'. Also evaluates JS scripts in the response.\n- Updated MODx model for modUserSettings and modWebUserSettings with appropriate primary key indexes and field types.\n- Updated installer SQL to remove the previous indexes and add the primary key index.\n- Fix to modX :: insideManager() to make sure there is a context object initialized before trying to get the context key.\n- [xPDO] Introduction of xPDOQuery for building SQL queries using only objects and the API.\n- [xPDO] Fix to timestamp phptype handling when stored as integer dbtype in database.\n- Modified modResource constructor to set createdon and createdby fields appropriately.\n- Fix for mcpuk GetUploadProgress script (see http://modxcms.com/forums/index.php/topic,11712.msg79581.html#msg79581)\n- Separated styles into their function, for easier manipulation and management\n- Ongoing Conversion of manager pages to xPDO, cleaning up XHTML\n- Emulated PDO can now be forced in PHP 5.1+ when PDO class is already available, but the required drivers are not available.\n- Added $modx->getTree() function for easily getting a tree structure of MODx resource ids in the current context.\n- Modified $modx->resourceMap to a simpler structure and optimized getParentIds() and getChildIds() functions. $modx->documentMap still holds the old structure but is deprecated.\n- Refactored entire caching layer, based on changes to xPDO. Files are now spread amongst logical directories, and automatic temp directory detection was also added.\n- Translated all core files and data in the core distribution/installation to the new native tag format.\n- Optimized modParser, removing run-time translation with modParser095 from normal execution and added modTranslate095 utility class, which can translate tags in database and file content, writing a log of the translation and/or making the changes to the database and files. modParser095 is experimental, and not recommended, as there are too many issues with mixed tags being parsed incorrectly.\n- Fix to make sure modX::parseChunk removes replacement placeholders for empty values.\n- Updates to MakeForm class.\n- Added modXMLRPCResource, modXMLRPCResponse classes and supporting code, including modified XML-RPC for PHP code (from version 2.1). You can now create resources that represent XMLRPC servers and clients.\n- Altered session cookie expiration that was getting set automatically on all sessions based on the default session cookie lifetime. Lifetime is now only applied if a session value is set for each context.\n- Added check to verify keys passed to modX::getPlaceholder() are valid strings to avoid PHP errors.\n- Various additional changes to prevent errors from revealing critical database credentials and connection information.\n- Fixed bug with system settings getting overwritten on mutate_settings manager page.\n- Merged from trunk (0.9.5.1-RC1) at revision 2251.\n- Latest updates and bug fixes from xPDO project.\n- Add ability to locate and use original manager/config/config.inc.php to upgrade directly on legacy installations.\n- Applied fixes to modResponse::outputContent(); was not assigning regClient script replacements to the output.\n- Changed parseChunk to parse new style tags to avoid any accidental matches on mixed tag situations.\n- Changed modChunk and modTemplate logic to create placeholders from any properties of the elements prefixed by the name of the element + '.' (added the .).\n- Fixed alias path generation, was reversing the order of parent paths in the resourceListing.\n- Fixed problems with recent changes to modRequest::sanitizeRequest() which was again truncating $_POST vars in the manager when encountering MODx tags.\n- Fixed generation of context cache files; was generating an eventMap for the mgr context at all times.\n- Fix to logic in modDocument::getMany('modTemplateVar').\n- Merge with 0.9.5.1 trunk at revision 2205.\n- Parsing adjustments to better deal with mixed old and new style tags.\n- [xPDO] Significant xPDO core update to prepare for SQLite, PostgreSQL and other ports.\n- Fix bug in install/upgrade SQL when resetting user and system settings for manager_theme.\n- Added some new configuration options for session handling and various caching features; more to come.\n- Minor changes to reduce number of unique db connections used during a request.\n- Various PHP 4 warnings fixed when assigning values by reference directly from functions (only variables can be assigned by reference in PHP 4).\n- Various improvements to MakeTable class based on usage in user_management and other manager interfaces.\n- Begin replacing Datagrid usage in manager with MakeTable (user_management, web_user_management, manage_modules, docmanager module); lots more Datagrids to replace.\n- Various changes to DataGrid and DatasetPager to try and support existing usage.\n- Fix for @EVAL bindings with more than one line of code.\n- Adjustments to modParser::collectElementTags() to better handle invalid tags (i.e. mispelled snippet names) with nested tags.\n- Adjustments to modParser095::translate() to properly handle translation from old to new configuration tags [(email_sender)] to [[++email_sender]].\n- DBAPI::escape() adjustment (again) to avoid certain issues when using native PDO along-side legacy manager code calling the mysql extension.\n- Removed & from getMany call in modCacheManager to prevent PHP warnings in PHP 4.\n- [xPDO] Added additional logic to xPDO::loadClass() which will return an error immediately if no class name is provided.\n- Adjusted modDocument::getMany() signature; added $cacheFlag= false parameter.\n- Remerged mutate_content.dynamic.php to fix several problems saving documents.\n- Adjusted queries in refresh_site.dynamic.php.\n- Added session table to install script due to failure of auto-table creation on some environments.\n- Removed unnecessary if statement around session_set_save_handler() in modX::_initSession(); the actual problem was auto-table creation was failing.\n- Fix DBAPI::escape() function; PDO::quote() adds single-quotes unlike the legacy mysql escape functions and this was causing content truncation.\n- [xPDO] xPDOCacheHandler class updated to allow configuration properties to determine a class for handling xPDO object and result set caching.\n- modX::_initSession() updated to better handle situations where session_set_save_handler() fails when trying to override default PHP session handling.\n- [xPDO] Modified fromArray() so it is not responsible for determining the _new attribute of xPDOObject instances. This is the responsibility of xPDO::getObject(), which uses xPDO::load(), and xPDO::getCollection().\n- Fix datasetpager error with PDO changes so DocManager module can load.\n- Fix WebUser login -- weblogin.processor.inc.php.\n- Fix makeUrl() -- no longer needs to add base_url.\n- Fix upgrade install script to insert new config settings properly.\n- Few tweaks to modX::_initSession function (was setting session_name twice).\n- Changed all line-endings to unix-style \\n on all files.\n- Removed assets/cache/* which is replaced by core/cache/*.\n- Updated version data format to be compatible with PHP's version_compare() function.\n- Resolved problems setting primary keys values and improperly identifying new objects when using xPDOObject::fromArray().\n- Several adjustments to xPDO::load(), xPDO::getCollection() and several xPDOObject methods based on changes to xPDOObject::fromArray().\n- Added stripslashes() to modRequest::_sanitize() when working with magic_quotes_gpc enabled.\n- Fix to MakeTable::prepareOrderByLink() to handle FURLs properly.\n- Reduce exposure of critical database credentials in xPDO::load() when errors are reported/logged.\n- Fixed error in xPDOObject::save(); updates to objects with compound primary keys were failing.\n- Added proper escapes to deprecated modX::getFullTableName() to fix issues when dashes (-) or other reserved (My)SQL characters appear in a database name.\n- Merged with trunk (0.9.5 final) at revision 2106.\n- Removed session_keepalive code.\n- Merged with trunk (0.9.5) at revision 2066.\n- Merged with trunk (0.9.5) at revision 2063.\n- Schema updates based on column size changes in 0.9.5.\n- Added missing modX::getSettings() method.\n- Various bug fixes.\n- Merged with trunk (0.9.5) at revision 1945.\n- [bug fix] Fixed a modParser bug when CDATA wrappers were encountered.\n- Add missing webAlert function to new modX class.\n- Modify categories save process to get the insert id using $modx->lastInsertId().\n- Fix to setup.sql; changed ENGINE= to TYPE= when creating new context table to avoid problems with MySQL versions before 4.1.\n- Fixed invalid reference to mergeDocumentMETATags in modResponse class.\n- [New feature] Allow custom error handler classes.\n- [New feature] Fine-grained configuration options for caching pages, database results, or disabling the cache altogether (see system settings starting with `cache.`). Turn the different caching options on/off or set a default time-to-live for those items being cached.\n- [New feature] Database result-set and xPDO object caching, with support for memcache, native-JSON object caching for high-performance AJAX requests.\n- [New feature] Configurable session management with default implementation configured for modSessionHandler, an xPDO-based implementation that stores sessions in a database, and allows a great deal of configurability, by site and/or context.\n- [New feature] Contexts allows a site to be organized into sub-sites, subdomains, etc, and override any system settings by context. The default contexts are 'web' and 'mgr' to support the legacy ideas of front-end and back-end session contexts.\n- Introducing the new MODx core built on top of xPDO; this will incrementally replace the entire existing codebase, but can co-exist until 1.0 release and provides about 90 to 95% legacy compatibility for existing tags and add-ons." ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [4, 121, 29], "buggy_code_start_loc": [4, 55, 27], "filenames": ["core/docs/changelog.txt", "core/model/modx/modmanagerrequest.class.php", "manager/templates/default/header.tpl"], "fixing_code_end_loc": [6, 123, 29], "fixing_code_start_loc": [5, 56, 27], "message": "Cross-site scripting (XSS) vulnerability in manager/templates/default/header.tpl in ModX Revolution before 2.2.11 allows remote attackers to inject arbitrary web script or HTML via the \"a\" parameter.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:modx:modx_revolution:*:*:*:*:*:*:*:*", "matchCriteriaId": "BF258698-982E-42B2-9AB6-049E5FD0017E", "versionEndExcluding": null, "versionEndIncluding": "2.2.10", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "66600BCA-D439-4743-8AE7-4E9433951F6F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "6544C9E0-CD92-407A-A17D-839CC84379CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "EF6D8ED9-01E2-429C-892C-1BDE207C0D34", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "89285DBF-9B65-4A8A-9ABC-1894C484A84E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "1E6ABC9F-775E-4D4C-91AB-35581F493EC5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "6A0B981D-AE93-4312-8AEC-99F157AAFA83", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.6:*:*:*:*:*:*:*", "matchCriteriaId": "73CA07B9-2DE2-4E6A-921D-89667AB54250", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.7:*:*:*:*:*:*:*", "matchCriteriaId": "223B2881-E108-45F5-AF97-6BF740B58420", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.8:*:*:*:*:*:*:*", "matchCriteriaId": "68D5B94B-B7FD-475E-BB9E-47871592959F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.0:*:*:*:*:*:*:*", "matchCriteriaId": "397FB64F-732C-41BC-BFAF-5D4742AD3E39", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.1:*:*:*:*:*:*:*", "matchCriteriaId": "7B762680-99DD-40A1-9D81-21E01A139BEB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.2:*:*:*:*:*:*:*", "matchCriteriaId": "3C9A56B2-5985-4CE3-B206-C657ED992280", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.3:*:*:*:*:*:*:*", "matchCriteriaId": "DDA3C9FA-A54C-4752-B2E0-986B6808423B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.4:*:*:*:*:*:*:*", "matchCriteriaId": "72BAE1E7-E1E7-45EB-AB4E-5E0DEAD84630", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.5:*:*:*:*:*:*:*", "matchCriteriaId": "539CA3F9-8AA5-44A3-917C-BCD94953B3E3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "3C4F2E50-2861-47B1-B4F8-DB3C7F4EDFAB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "357A9A52-0915-4865-B2B7-619A776BF8DD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "686065C6-CA40-4ACC-9927-AB2FD2679362", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.3:*:*:*:*:*:*:*", "matchCriteriaId": "B1B7FAA3-22E0-4464-BDCD-F77AB16FF76B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.4:*:*:*:*:*:*:*", "matchCriteriaId": "7140446F-DAAD-40EC-997E-1A9A140AC39C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.5:*:*:*:*:*:*:*", "matchCriteriaId": "D352065C-12CF-48E0-BD97-2C20178828A0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.6:*:*:*:*:*:*:*", "matchCriteriaId": "319FCE68-F2B0-4F3C-8772-C453F0B9B303", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.7:*:*:*:*:*:*:*", "matchCriteriaId": "00978BE1-0642-4A88-B2E6-B0ABD7E0E3E7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.8:*:*:*:*:*:*:*", "matchCriteriaId": "E94115D1-663A-4282-ABC0-5EE0DB2450C0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.9:*:*:*:*:*:*:*", "matchCriteriaId": "1D83A52A-A9E4-417C-AEFA-006D60518ECA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site scripting (XSS) vulnerability in manager/templates/default/header.tpl in ModX Revolution before 2.2.11 allows remote attackers to inject arbitrary web script or HTML via the \"a\" parameter."}, {"lang": "es", "value": "Vulnerabilidad de XSS en manager/templates/default/header.tpl en ModX Revolution en versiones anteriores a 2.2.11 permite a atacantes remotos inyectar secuencias de comandos web o HTML arbitrarios a trav\u00e9s del par\u00e1metro \"a\"."}], "evaluatorComment": null, "id": "CVE-2014-2080", "lastModified": "2015-07-30T14:52:44.890", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-03-01T00:01:09.590", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "http://modx.com/blog/2014/01/21/revolution-2.2.11%E2%80%94security-fixes-and-prevent-change-loss"}, {"source": "cve@mitre.org", "tags": null, "url": "http://seclists.org/oss-sec/2014/q1/431"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/65755"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Patch"], "url": "https://github.com/modxcms/revolution/commit/77463eb6a8090f474b04fdc1b72225cb93c558ea"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/modxcms/revolution/commit/77463eb6a8090f474b04fdc1b72225cb93c558ea"}, "type": "CWE-79"}
325
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * modManagerRequest\n *\n * @package modx\n */\nrequire_once MODX_CORE_PATH . 'model/modx/modrequest.class.php';\n/**\n * Encapsulates the interaction of MODX manager with an HTTP request.\n *\n * {@inheritdoc}\n *\n * @package modx\n */\nclass modManagerRequest extends modRequest {\n /**\n * @var string The action to load.\n * @access public\n */\n public $action= null;\n /**\n * @deprecated 2.0.0 Use $modx->error instead.\n * @var modError The error handler for the request.\n * @access public\n */\n public $error= null;\n /**\n * @var string The REQUEST parameter to load actions by.\n * @access public\n */\n public $actionVar = 'a';\n /**\n * @var mixed The default action to load from.\n * @access public\n */\n public $defaultAction = 0;", " /**\n * Instantiates a modManagerRequest object.\n *\n * @param modX $modx\n * @return modManagerRequest\n */\n function __construct(modX & $modx) {\n parent :: __construct($modx);\n $this->initialize();\n }", " /**\n * Initializes the manager request.\n *\n * @access public\n * @return boolean True if successful.\n */\n public function initialize() {", "", " if (!defined('MODX_INCLUDES_PATH')) {\n define('MODX_INCLUDES_PATH',$this->modx->getOption('manager_path').'includes/');\n }", " /* load smarty template engine */\n $theme = $this->modx->getOption('manager_theme',null,'default');\n $templatePath = $this->modx->getOption('manager_path') . 'templates/' . $theme . '/';\n if (!file_exists($templatePath)) { /* fallback to default */\n $templatePath = $this->modx->getOption('manager_path') . 'templates/default/';\n }\n $this->modx->getService('smarty', 'smarty.modSmarty', '', array(\n 'template_dir' => $templatePath,\n ));\n /* load context-specific cache dir */\n $this->modx->smarty->setCachePath($this->modx->context->get('key').'/smarty/'.$theme.'/');", " $this->modx->smarty->assign('_config',$this->modx->config);\n $this->modx->smarty->assignByRef('modx',$this->modx);", " /* send anti caching headers */\n header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');\n header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');\n header('Cache-Control: no-store, no-cache, must-revalidate');\n header('Cache-Control: post-check=0, pre-check=0', false);\n header('Pragma: no-cache');\n /* send the charset header */\n header('Content-Type: text/html; charset='.$this->modx->getOption('modx_charset'));", " /*\n * TODO: implement destroy active sessions if installing\n * TODO: implement regen session if not destroyed from install\n */", " /* include version info */\n if ($this->modx->version === null) $this->modx->getVersionData();", "\n if ($this->modx->getOption('manager_language')) {\n $this->modx->setOption('cultureKey',$this->modx->getOption('manager_language'));\n }", " /* load default core cache file of lexicon strings */\n $this->modx->lexicon->load('core:default');", " if ($this->modx->actionMap === null || !is_array($this->modx->actionMap)) {\n $this->loadActionMap();\n }", " return true;\n }", " /**\n * The primary MODX manager request handler (a.k.a. controller).\n *\n * @access public\n * @return boolean True if a request is handled without interruption.\n */\n public function handleRequest() {\n /* Load error handling class */\n $this->loadErrorHandler();", " $this->modx->invokeEvent('OnHandleRequest');", " /* save page to manager object. allow custom actionVar choice for extending classes. */", " $this->action = isset($_REQUEST[$this->actionVar]) ? $_REQUEST[$this->actionVar] : $this->defaultAction;", "\n /* invoke OnManagerPageInit event */\n $this->modx->invokeEvent('OnManagerPageInit',array('action' => $this->action));\n $this->prepareResponse();\n }", " /**\n * This implementation adds register logging capabilities via $_POST vars\n * when the error handler is loaded.\n *\n * @param string $class\n */\n public function loadErrorHandler($class = 'modError') {\n parent :: loadErrorHandler($class);\n $data = array_merge($_POST, array(\n 'register_class' => 'registry.modFileRegister'\n ));\n $this->registerLogging($data);\n }", " /**\n * Loads the actionMap, and generates a cache file if necessary.\n *\n * @access public\n * @return boolean True if successful.\n */\n public function loadActionMap() {\n $loaded = false;\n $cacheKey= $this->modx->context->get('key') . '/actions';\n $map = $this->modx->cacheManager->get($cacheKey, array(\n xPDO::OPT_CACHE_KEY => $this->modx->getOption('cache_action_map_key', null, 'action_map'),\n xPDO::OPT_CACHE_HANDLER => $this->modx->getOption('cache_action_map_handler', null, $this->modx->getOption(xPDO::OPT_CACHE_HANDLER)),\n xPDO::OPT_CACHE_FORMAT => (integer) $this->modx->getOption('cache_action_map_format', null, $this->modx->getOption(xPDO::OPT_CACHE_FORMAT, null, xPDOCacheManager::CACHE_PHP)),\n ));\n if (!$map) {\n $map = $this->modx->cacheManager->generateActionMap($cacheKey);\n }\n if ($map) {\n $this->modx->actionMap = $map;\n $loaded = true;\n }\n return $loaded;\n }", " /**\n * Prepares the MODX response to a mgr request that is being handled.\n *\n * @access public\n * @param array $options An array of options\n * @return boolean True if the response is properly prepared.\n */\n public function prepareResponse(array $options = array()) {\n if (!$this->modx->getResponse('modManagerResponse')) {\n $this->modx->log(modX::LOG_LEVEL_FATAL, 'Could not load response class.');\n }\n $this->modx->response->outputContent($options);\n }\n}" ]
[ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [4, 121, 29], "buggy_code_start_loc": [4, 55, 27], "filenames": ["core/docs/changelog.txt", "core/model/modx/modmanagerrequest.class.php", "manager/templates/default/header.tpl"], "fixing_code_end_loc": [6, 123, 29], "fixing_code_start_loc": [5, 56, 27], "message": "Cross-site scripting (XSS) vulnerability in manager/templates/default/header.tpl in ModX Revolution before 2.2.11 allows remote attackers to inject arbitrary web script or HTML via the \"a\" parameter.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:modx:modx_revolution:*:*:*:*:*:*:*:*", "matchCriteriaId": "BF258698-982E-42B2-9AB6-049E5FD0017E", "versionEndExcluding": null, "versionEndIncluding": "2.2.10", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "66600BCA-D439-4743-8AE7-4E9433951F6F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "6544C9E0-CD92-407A-A17D-839CC84379CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "EF6D8ED9-01E2-429C-892C-1BDE207C0D34", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "89285DBF-9B65-4A8A-9ABC-1894C484A84E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "1E6ABC9F-775E-4D4C-91AB-35581F493EC5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "6A0B981D-AE93-4312-8AEC-99F157AAFA83", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.6:*:*:*:*:*:*:*", "matchCriteriaId": "73CA07B9-2DE2-4E6A-921D-89667AB54250", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.7:*:*:*:*:*:*:*", "matchCriteriaId": "223B2881-E108-45F5-AF97-6BF740B58420", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.8:*:*:*:*:*:*:*", "matchCriteriaId": "68D5B94B-B7FD-475E-BB9E-47871592959F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.0:*:*:*:*:*:*:*", "matchCriteriaId": "397FB64F-732C-41BC-BFAF-5D4742AD3E39", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.1:*:*:*:*:*:*:*", "matchCriteriaId": "7B762680-99DD-40A1-9D81-21E01A139BEB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.2:*:*:*:*:*:*:*", "matchCriteriaId": "3C9A56B2-5985-4CE3-B206-C657ED992280", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.3:*:*:*:*:*:*:*", "matchCriteriaId": "DDA3C9FA-A54C-4752-B2E0-986B6808423B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.4:*:*:*:*:*:*:*", "matchCriteriaId": "72BAE1E7-E1E7-45EB-AB4E-5E0DEAD84630", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.5:*:*:*:*:*:*:*", "matchCriteriaId": "539CA3F9-8AA5-44A3-917C-BCD94953B3E3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "3C4F2E50-2861-47B1-B4F8-DB3C7F4EDFAB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "357A9A52-0915-4865-B2B7-619A776BF8DD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "686065C6-CA40-4ACC-9927-AB2FD2679362", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.3:*:*:*:*:*:*:*", "matchCriteriaId": "B1B7FAA3-22E0-4464-BDCD-F77AB16FF76B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.4:*:*:*:*:*:*:*", "matchCriteriaId": "7140446F-DAAD-40EC-997E-1A9A140AC39C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.5:*:*:*:*:*:*:*", "matchCriteriaId": "D352065C-12CF-48E0-BD97-2C20178828A0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.6:*:*:*:*:*:*:*", "matchCriteriaId": "319FCE68-F2B0-4F3C-8772-C453F0B9B303", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.7:*:*:*:*:*:*:*", "matchCriteriaId": "00978BE1-0642-4A88-B2E6-B0ABD7E0E3E7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.8:*:*:*:*:*:*:*", "matchCriteriaId": "E94115D1-663A-4282-ABC0-5EE0DB2450C0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.9:*:*:*:*:*:*:*", "matchCriteriaId": "1D83A52A-A9E4-417C-AEFA-006D60518ECA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site scripting (XSS) vulnerability in manager/templates/default/header.tpl in ModX Revolution before 2.2.11 allows remote attackers to inject arbitrary web script or HTML via the \"a\" parameter."}, {"lang": "es", "value": "Vulnerabilidad de XSS en manager/templates/default/header.tpl en ModX Revolution en versiones anteriores a 2.2.11 permite a atacantes remotos inyectar secuencias de comandos web o HTML arbitrarios a trav\u00e9s del par\u00e1metro \"a\"."}], "evaluatorComment": null, "id": "CVE-2014-2080", "lastModified": "2015-07-30T14:52:44.890", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-03-01T00:01:09.590", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "http://modx.com/blog/2014/01/21/revolution-2.2.11%E2%80%94security-fixes-and-prevent-change-loss"}, {"source": "cve@mitre.org", "tags": null, "url": "http://seclists.org/oss-sec/2014/q1/431"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/65755"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Patch"], "url": "https://github.com/modxcms/revolution/commit/77463eb6a8090f474b04fdc1b72225cb93c558ea"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/modxcms/revolution/commit/77463eb6a8090f474b04fdc1b72225cb93c558ea"}, "type": "CWE-79"}
325
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * modManagerRequest\n *\n * @package modx\n */\nrequire_once MODX_CORE_PATH . 'model/modx/modrequest.class.php';\n/**\n * Encapsulates the interaction of MODX manager with an HTTP request.\n *\n * {@inheritdoc}\n *\n * @package modx\n */\nclass modManagerRequest extends modRequest {\n /**\n * @var string The action to load.\n * @access public\n */\n public $action= null;\n /**\n * @deprecated 2.0.0 Use $modx->error instead.\n * @var modError The error handler for the request.\n * @access public\n */\n public $error= null;\n /**\n * @var string The REQUEST parameter to load actions by.\n * @access public\n */\n public $actionVar = 'a';\n /**\n * @var mixed The default action to load from.\n * @access public\n */\n public $defaultAction = 0;", " /**\n * Instantiates a modManagerRequest object.\n *\n * @param modX $modx\n * @return modManagerRequest\n */\n function __construct(modX & $modx) {\n parent :: __construct($modx);\n $this->initialize();\n }", " /**\n * Initializes the manager request.\n *\n * @access public\n * @return boolean True if successful.\n */\n public function initialize() {", " $this->sanitizeRequest();\n ", " if (!defined('MODX_INCLUDES_PATH')) {\n define('MODX_INCLUDES_PATH',$this->modx->getOption('manager_path').'includes/');\n }", " /* load smarty template engine */\n $theme = $this->modx->getOption('manager_theme',null,'default');\n $templatePath = $this->modx->getOption('manager_path') . 'templates/' . $theme . '/';\n if (!file_exists($templatePath)) { /* fallback to default */\n $templatePath = $this->modx->getOption('manager_path') . 'templates/default/';\n }\n $this->modx->getService('smarty', 'smarty.modSmarty', '', array(\n 'template_dir' => $templatePath,\n ));\n /* load context-specific cache dir */\n $this->modx->smarty->setCachePath($this->modx->context->get('key').'/smarty/'.$theme.'/');", " $this->modx->smarty->assign('_config',$this->modx->config);\n $this->modx->smarty->assignByRef('modx',$this->modx);", " /* send anti caching headers */\n header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');\n header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');\n header('Cache-Control: no-store, no-cache, must-revalidate');\n header('Cache-Control: post-check=0, pre-check=0', false);\n header('Pragma: no-cache');\n /* send the charset header */\n header('Content-Type: text/html; charset='.$this->modx->getOption('modx_charset'));", " /*\n * TODO: implement destroy active sessions if installing\n * TODO: implement regen session if not destroyed from install\n */", " /* include version info */\n if ($this->modx->version === null) $this->modx->getVersionData();", "\n if ($this->modx->getOption('manager_language')) {\n $this->modx->setOption('cultureKey',$this->modx->getOption('manager_language'));\n }", " /* load default core cache file of lexicon strings */\n $this->modx->lexicon->load('core:default');", " if ($this->modx->actionMap === null || !is_array($this->modx->actionMap)) {\n $this->loadActionMap();\n }", " return true;\n }", " /**\n * The primary MODX manager request handler (a.k.a. controller).\n *\n * @access public\n * @return boolean True if a request is handled without interruption.\n */\n public function handleRequest() {\n /* Load error handling class */\n $this->loadErrorHandler();", " $this->modx->invokeEvent('OnHandleRequest');", " /* save page to manager object. allow custom actionVar choice for extending classes. */", " $this->action = isset($_REQUEST[$this->actionVar]) ? (integer)$_REQUEST[$this->actionVar] : $this->defaultAction;", "\n /* invoke OnManagerPageInit event */\n $this->modx->invokeEvent('OnManagerPageInit',array('action' => $this->action));\n $this->prepareResponse();\n }", " /**\n * This implementation adds register logging capabilities via $_POST vars\n * when the error handler is loaded.\n *\n * @param string $class\n */\n public function loadErrorHandler($class = 'modError') {\n parent :: loadErrorHandler($class);\n $data = array_merge($_POST, array(\n 'register_class' => 'registry.modFileRegister'\n ));\n $this->registerLogging($data);\n }", " /**\n * Loads the actionMap, and generates a cache file if necessary.\n *\n * @access public\n * @return boolean True if successful.\n */\n public function loadActionMap() {\n $loaded = false;\n $cacheKey= $this->modx->context->get('key') . '/actions';\n $map = $this->modx->cacheManager->get($cacheKey, array(\n xPDO::OPT_CACHE_KEY => $this->modx->getOption('cache_action_map_key', null, 'action_map'),\n xPDO::OPT_CACHE_HANDLER => $this->modx->getOption('cache_action_map_handler', null, $this->modx->getOption(xPDO::OPT_CACHE_HANDLER)),\n xPDO::OPT_CACHE_FORMAT => (integer) $this->modx->getOption('cache_action_map_format', null, $this->modx->getOption(xPDO::OPT_CACHE_FORMAT, null, xPDOCacheManager::CACHE_PHP)),\n ));\n if (!$map) {\n $map = $this->modx->cacheManager->generateActionMap($cacheKey);\n }\n if ($map) {\n $this->modx->actionMap = $map;\n $loaded = true;\n }\n return $loaded;\n }", " /**\n * Prepares the MODX response to a mgr request that is being handled.\n *\n * @access public\n * @param array $options An array of options\n * @return boolean True if the response is properly prepared.\n */\n public function prepareResponse(array $options = array()) {\n if (!$this->modx->getResponse('modManagerResponse')) {\n $this->modx->log(modX::LOG_LEVEL_FATAL, 'Could not load response class.');\n }\n $this->modx->response->outputContent($options);\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [4, 121, 29], "buggy_code_start_loc": [4, 55, 27], "filenames": ["core/docs/changelog.txt", "core/model/modx/modmanagerrequest.class.php", "manager/templates/default/header.tpl"], "fixing_code_end_loc": [6, 123, 29], "fixing_code_start_loc": [5, 56, 27], "message": "Cross-site scripting (XSS) vulnerability in manager/templates/default/header.tpl in ModX Revolution before 2.2.11 allows remote attackers to inject arbitrary web script or HTML via the \"a\" parameter.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:modx:modx_revolution:*:*:*:*:*:*:*:*", "matchCriteriaId": "BF258698-982E-42B2-9AB6-049E5FD0017E", "versionEndExcluding": null, "versionEndIncluding": "2.2.10", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "66600BCA-D439-4743-8AE7-4E9433951F6F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "6544C9E0-CD92-407A-A17D-839CC84379CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "EF6D8ED9-01E2-429C-892C-1BDE207C0D34", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "89285DBF-9B65-4A8A-9ABC-1894C484A84E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "1E6ABC9F-775E-4D4C-91AB-35581F493EC5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "6A0B981D-AE93-4312-8AEC-99F157AAFA83", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.6:*:*:*:*:*:*:*", "matchCriteriaId": "73CA07B9-2DE2-4E6A-921D-89667AB54250", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.7:*:*:*:*:*:*:*", "matchCriteriaId": "223B2881-E108-45F5-AF97-6BF740B58420", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.8:*:*:*:*:*:*:*", "matchCriteriaId": "68D5B94B-B7FD-475E-BB9E-47871592959F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.0:*:*:*:*:*:*:*", "matchCriteriaId": "397FB64F-732C-41BC-BFAF-5D4742AD3E39", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.1:*:*:*:*:*:*:*", "matchCriteriaId": "7B762680-99DD-40A1-9D81-21E01A139BEB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.2:*:*:*:*:*:*:*", "matchCriteriaId": "3C9A56B2-5985-4CE3-B206-C657ED992280", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.3:*:*:*:*:*:*:*", "matchCriteriaId": "DDA3C9FA-A54C-4752-B2E0-986B6808423B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.4:*:*:*:*:*:*:*", "matchCriteriaId": "72BAE1E7-E1E7-45EB-AB4E-5E0DEAD84630", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.5:*:*:*:*:*:*:*", "matchCriteriaId": "539CA3F9-8AA5-44A3-917C-BCD94953B3E3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "3C4F2E50-2861-47B1-B4F8-DB3C7F4EDFAB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "357A9A52-0915-4865-B2B7-619A776BF8DD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "686065C6-CA40-4ACC-9927-AB2FD2679362", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.3:*:*:*:*:*:*:*", "matchCriteriaId": "B1B7FAA3-22E0-4464-BDCD-F77AB16FF76B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.4:*:*:*:*:*:*:*", "matchCriteriaId": "7140446F-DAAD-40EC-997E-1A9A140AC39C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.5:*:*:*:*:*:*:*", "matchCriteriaId": "D352065C-12CF-48E0-BD97-2C20178828A0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.6:*:*:*:*:*:*:*", "matchCriteriaId": "319FCE68-F2B0-4F3C-8772-C453F0B9B303", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.7:*:*:*:*:*:*:*", "matchCriteriaId": "00978BE1-0642-4A88-B2E6-B0ABD7E0E3E7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.8:*:*:*:*:*:*:*", "matchCriteriaId": "E94115D1-663A-4282-ABC0-5EE0DB2450C0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.9:*:*:*:*:*:*:*", "matchCriteriaId": "1D83A52A-A9E4-417C-AEFA-006D60518ECA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site scripting (XSS) vulnerability in manager/templates/default/header.tpl in ModX Revolution before 2.2.11 allows remote attackers to inject arbitrary web script or HTML via the \"a\" parameter."}, {"lang": "es", "value": "Vulnerabilidad de XSS en manager/templates/default/header.tpl en ModX Revolution en versiones anteriores a 2.2.11 permite a atacantes remotos inyectar secuencias de comandos web o HTML arbitrarios a trav\u00e9s del par\u00e1metro \"a\"."}], "evaluatorComment": null, "id": "CVE-2014-2080", "lastModified": "2015-07-30T14:52:44.890", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-03-01T00:01:09.590", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "http://modx.com/blog/2014/01/21/revolution-2.2.11%E2%80%94security-fixes-and-prevent-change-loss"}, {"source": "cve@mitre.org", "tags": null, "url": "http://seclists.org/oss-sec/2014/q1/431"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/65755"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Patch"], "url": "https://github.com/modxcms/revolution/commit/77463eb6a8090f474b04fdc1b72225cb93c558ea"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/modxcms/revolution/commit/77463eb6a8090f474b04fdc1b72225cb93c558ea"}, "type": "CWE-79"}
325
Determine whether the {function_name} code is vulnerable or not.
[ "{if $_config.manager_html5_cache EQ 1}<!DOCTYPE HTML>{else}<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">{/if}", "<html xmlns=\"http://www.w3.org/1999/xhtml\" {if $_config.manager_direction EQ 'rtl'}dir=\"rtl\"{/if} lang=\"{$_config.manager_lang_attribute}\" xml:lang=\"{$_config.manager_lang_attribute}\"{if $_config.manager_html5_cache EQ 1} manifest=\"{$_config.manager_url}cache.manifest.php\"{/if}>\n<head>\n<title>{if $_pagetitle}{$_pagetitle} | {/if}{$_config.site_name}</title>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset={$_config.modx_charset}\" />", "{if $_config.manager_favicon_url}<link rel=\"shortcut icon\" type=\"image/x-icon\" href=\"{$_config.manager_favicon_url}\" />{/if}", "{if $_config.compress_css}\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{$_config.manager_url}assets/ext3/resources/css/ext-all-notheme-min.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{$_config.manager_url}min/index.php?f={$_config.manager_url}templates/default/css/xtheme-modx.css,{$_config.manager_url}templates/default/css/index.css\" />\n{else}\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{$_config.manager_url}assets/ext3/resources/css/ext-all-notheme-min.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{$_config.manager_url}templates/default/css/xtheme-modx.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{$_config.manager_url}templates/default/css/index.css\" />\n{/if}", "{if $_config.ext_debug}\n<script src=\"{$_config.manager_url}assets/ext3/adapter/ext/ext-base-debug.js\" type=\"text/javascript\"></script>\n<script src=\"{$_config.manager_url}assets/ext3/ext-all-debug.js\" type=\"text/javascript\"></script>\n{else}\n<script src=\"{$_config.manager_url}assets/ext3/adapter/ext/ext-base.js\" type=\"text/javascript\"></script>\n<script src=\"{$_config.manager_url}assets/ext3/ext-all.js\" type=\"text/javascript\"></script>\n{/if}\n<script src=\"{$_config.manager_url}assets/modext/core/modx.js\" type=\"text/javascript\"></script>", "<script src=\"{$_config.connectors_url}lang.js.php?ctx=mgr&topic=topmenu,file,resource,{$_lang_topics}&action={$smarty.get.a|strip_tags}\" type=\"text/javascript\"></script>\n<script src=\"{$_config.connectors_url}layout/modx.config.js.php?action={$smarty.get.a|strip_tags}{if $_ctx}&wctx={$_ctx}{/if}\" type=\"text/javascript\"></script>", "\n{if $_config.compress_js && $_config.compress_js_groups}\n<script src=\"{$_config.manager_url}min/index.php?g=coreJs1\" type=\"text/javascript\"></script>\n<script src=\"{$_config.manager_url}min/index.php?g=coreJs2\" type=\"text/javascript\"></script>\n<script src=\"{$_config.manager_url}min/index.php?g=coreJs3\" type=\"text/javascript\"></script>\n{/if}", "{$maincssjs}\n{foreach from=$cssjs item=scr}\n{$scr}\n{/foreach}\n</head>\n<body id=\"modx-body-tag\">", "<div id=\"modx-browser\"></div>\n<div id=\"modx-container\">\n <div id=\"modx-mainpanel\">\n <div id=\"modx-header\">\n <div id=\"modx-topbar\">\n <div id=\"modx-logo\"><a href=\"http://modx.com\" onclick=\"window.open(this.href); return false;\"><img src=\"templates/default/images/style/modx-logo-header.png\" alt=\"\" /></a></div>", "\n <div class=\"rightlogin\">\n {if $canChangeProfile}<a class=\"modx-user-profile\" href=\"?a={$profileAction}\">{$username}</a>{else}<span class=\"modx-user-profile\">{$username}</span>{/if}\n {if $canLogout}<a class=\"modx-logout\" href=\"javascript:;\" onclick=\"MODx.logout();\">{$_lang.logout}</a>{/if}\n </div>\n <div id=\"modx-site-name\">\n {$_config.site_name}\n <span class=\"modx-version\">MODX Revolution {$_config.settings_version} ({$_config.settings_distro})</span>\n </div>\n </div>\n <div id=\"modx-navbar\">\n <div id=\"modx-topnav-div\">\n <ul id=\"modx-topnav\">\n {$navb}\n <li class=\"cls\"></li>\n </ul>\n </div>\n </div>\n </div>", " <div id=\"modAB\"></div>\n <div id=\"modx-leftbar\"></div>\n <div id=\"modx-content\">\n <div id=\"modx-panel-holder\"></div>" ]
[ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [4, 121, 29], "buggy_code_start_loc": [4, 55, 27], "filenames": ["core/docs/changelog.txt", "core/model/modx/modmanagerrequest.class.php", "manager/templates/default/header.tpl"], "fixing_code_end_loc": [6, 123, 29], "fixing_code_start_loc": [5, 56, 27], "message": "Cross-site scripting (XSS) vulnerability in manager/templates/default/header.tpl in ModX Revolution before 2.2.11 allows remote attackers to inject arbitrary web script or HTML via the \"a\" parameter.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:modx:modx_revolution:*:*:*:*:*:*:*:*", "matchCriteriaId": "BF258698-982E-42B2-9AB6-049E5FD0017E", "versionEndExcluding": null, "versionEndIncluding": "2.2.10", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "66600BCA-D439-4743-8AE7-4E9433951F6F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "6544C9E0-CD92-407A-A17D-839CC84379CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "EF6D8ED9-01E2-429C-892C-1BDE207C0D34", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "89285DBF-9B65-4A8A-9ABC-1894C484A84E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "1E6ABC9F-775E-4D4C-91AB-35581F493EC5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "6A0B981D-AE93-4312-8AEC-99F157AAFA83", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.6:*:*:*:*:*:*:*", "matchCriteriaId": "73CA07B9-2DE2-4E6A-921D-89667AB54250", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.7:*:*:*:*:*:*:*", "matchCriteriaId": "223B2881-E108-45F5-AF97-6BF740B58420", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.8:*:*:*:*:*:*:*", "matchCriteriaId": "68D5B94B-B7FD-475E-BB9E-47871592959F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.0:*:*:*:*:*:*:*", "matchCriteriaId": "397FB64F-732C-41BC-BFAF-5D4742AD3E39", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.1:*:*:*:*:*:*:*", "matchCriteriaId": "7B762680-99DD-40A1-9D81-21E01A139BEB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.2:*:*:*:*:*:*:*", "matchCriteriaId": "3C9A56B2-5985-4CE3-B206-C657ED992280", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.3:*:*:*:*:*:*:*", "matchCriteriaId": "DDA3C9FA-A54C-4752-B2E0-986B6808423B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.4:*:*:*:*:*:*:*", "matchCriteriaId": "72BAE1E7-E1E7-45EB-AB4E-5E0DEAD84630", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.5:*:*:*:*:*:*:*", "matchCriteriaId": "539CA3F9-8AA5-44A3-917C-BCD94953B3E3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "3C4F2E50-2861-47B1-B4F8-DB3C7F4EDFAB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "357A9A52-0915-4865-B2B7-619A776BF8DD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "686065C6-CA40-4ACC-9927-AB2FD2679362", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.3:*:*:*:*:*:*:*", "matchCriteriaId": "B1B7FAA3-22E0-4464-BDCD-F77AB16FF76B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.4:*:*:*:*:*:*:*", "matchCriteriaId": "7140446F-DAAD-40EC-997E-1A9A140AC39C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.5:*:*:*:*:*:*:*", "matchCriteriaId": "D352065C-12CF-48E0-BD97-2C20178828A0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.6:*:*:*:*:*:*:*", "matchCriteriaId": "319FCE68-F2B0-4F3C-8772-C453F0B9B303", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.7:*:*:*:*:*:*:*", "matchCriteriaId": "00978BE1-0642-4A88-B2E6-B0ABD7E0E3E7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.8:*:*:*:*:*:*:*", "matchCriteriaId": "E94115D1-663A-4282-ABC0-5EE0DB2450C0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.9:*:*:*:*:*:*:*", "matchCriteriaId": "1D83A52A-A9E4-417C-AEFA-006D60518ECA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site scripting (XSS) vulnerability in manager/templates/default/header.tpl in ModX Revolution before 2.2.11 allows remote attackers to inject arbitrary web script or HTML via the \"a\" parameter."}, {"lang": "es", "value": "Vulnerabilidad de XSS en manager/templates/default/header.tpl en ModX Revolution en versiones anteriores a 2.2.11 permite a atacantes remotos inyectar secuencias de comandos web o HTML arbitrarios a trav\u00e9s del par\u00e1metro \"a\"."}], "evaluatorComment": null, "id": "CVE-2014-2080", "lastModified": "2015-07-30T14:52:44.890", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-03-01T00:01:09.590", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "http://modx.com/blog/2014/01/21/revolution-2.2.11%E2%80%94security-fixes-and-prevent-change-loss"}, {"source": "cve@mitre.org", "tags": null, "url": "http://seclists.org/oss-sec/2014/q1/431"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/65755"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Patch"], "url": "https://github.com/modxcms/revolution/commit/77463eb6a8090f474b04fdc1b72225cb93c558ea"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/modxcms/revolution/commit/77463eb6a8090f474b04fdc1b72225cb93c558ea"}, "type": "CWE-79"}
325
Determine whether the {function_name} code is vulnerable or not.
[ "{if $_config.manager_html5_cache EQ 1}<!DOCTYPE HTML>{else}<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">{/if}", "<html xmlns=\"http://www.w3.org/1999/xhtml\" {if $_config.manager_direction EQ 'rtl'}dir=\"rtl\"{/if} lang=\"{$_config.manager_lang_attribute}\" xml:lang=\"{$_config.manager_lang_attribute}\"{if $_config.manager_html5_cache EQ 1} manifest=\"{$_config.manager_url}cache.manifest.php\"{/if}>\n<head>\n<title>{if $_pagetitle}{$_pagetitle} | {/if}{$_config.site_name}</title>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset={$_config.modx_charset}\" />", "{if $_config.manager_favicon_url}<link rel=\"shortcut icon\" type=\"image/x-icon\" href=\"{$_config.manager_favicon_url}\" />{/if}", "{if $_config.compress_css}\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{$_config.manager_url}assets/ext3/resources/css/ext-all-notheme-min.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{$_config.manager_url}min/index.php?f={$_config.manager_url}templates/default/css/xtheme-modx.css,{$_config.manager_url}templates/default/css/index.css\" />\n{else}\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{$_config.manager_url}assets/ext3/resources/css/ext-all-notheme-min.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{$_config.manager_url}templates/default/css/xtheme-modx.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{$_config.manager_url}templates/default/css/index.css\" />\n{/if}", "{if $_config.ext_debug}\n<script src=\"{$_config.manager_url}assets/ext3/adapter/ext/ext-base-debug.js\" type=\"text/javascript\"></script>\n<script src=\"{$_config.manager_url}assets/ext3/ext-all-debug.js\" type=\"text/javascript\"></script>\n{else}\n<script src=\"{$_config.manager_url}assets/ext3/adapter/ext/ext-base.js\" type=\"text/javascript\"></script>\n<script src=\"{$_config.manager_url}assets/ext3/ext-all.js\" type=\"text/javascript\"></script>\n{/if}\n<script src=\"{$_config.manager_url}assets/modext/core/modx.js\" type=\"text/javascript\"></script>", "<script src=\"{$_config.connectors_url}lang.js.php?ctx=mgr&topic=topmenu,file,resource,{$_lang_topics}&action={$smarty.get.a|htmlspecialchars}\" type=\"text/javascript\"></script>\n<script src=\"{$_config.connectors_url}layout/modx.config.js.php?action={$smarty.get.a|htmlspecialchars}{if $_ctx}&wctx={$_ctx}{/if}\" type=\"text/javascript\"></script>", "\n{if $_config.compress_js && $_config.compress_js_groups}\n<script src=\"{$_config.manager_url}min/index.php?g=coreJs1\" type=\"text/javascript\"></script>\n<script src=\"{$_config.manager_url}min/index.php?g=coreJs2\" type=\"text/javascript\"></script>\n<script src=\"{$_config.manager_url}min/index.php?g=coreJs3\" type=\"text/javascript\"></script>\n{/if}", "{$maincssjs}\n{foreach from=$cssjs item=scr}\n{$scr}\n{/foreach}\n</head>\n<body id=\"modx-body-tag\">", "<div id=\"modx-browser\"></div>\n<div id=\"modx-container\">\n <div id=\"modx-mainpanel\">\n <div id=\"modx-header\">\n <div id=\"modx-topbar\">\n <div id=\"modx-logo\"><a href=\"http://modx.com\" onclick=\"window.open(this.href); return false;\"><img src=\"templates/default/images/style/modx-logo-header.png\" alt=\"\" /></a></div>", "\n <div class=\"rightlogin\">\n {if $canChangeProfile}<a class=\"modx-user-profile\" href=\"?a={$profileAction}\">{$username}</a>{else}<span class=\"modx-user-profile\">{$username}</span>{/if}\n {if $canLogout}<a class=\"modx-logout\" href=\"javascript:;\" onclick=\"MODx.logout();\">{$_lang.logout}</a>{/if}\n </div>\n <div id=\"modx-site-name\">\n {$_config.site_name}\n <span class=\"modx-version\">MODX Revolution {$_config.settings_version} ({$_config.settings_distro})</span>\n </div>\n </div>\n <div id=\"modx-navbar\">\n <div id=\"modx-topnav-div\">\n <ul id=\"modx-topnav\">\n {$navb}\n <li class=\"cls\"></li>\n </ul>\n </div>\n </div>\n </div>", " <div id=\"modAB\"></div>\n <div id=\"modx-leftbar\"></div>\n <div id=\"modx-content\">\n <div id=\"modx-panel-holder\"></div>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [4, 121, 29], "buggy_code_start_loc": [4, 55, 27], "filenames": ["core/docs/changelog.txt", "core/model/modx/modmanagerrequest.class.php", "manager/templates/default/header.tpl"], "fixing_code_end_loc": [6, 123, 29], "fixing_code_start_loc": [5, 56, 27], "message": "Cross-site scripting (XSS) vulnerability in manager/templates/default/header.tpl in ModX Revolution before 2.2.11 allows remote attackers to inject arbitrary web script or HTML via the \"a\" parameter.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:modx:modx_revolution:*:*:*:*:*:*:*:*", "matchCriteriaId": "BF258698-982E-42B2-9AB6-049E5FD0017E", "versionEndExcluding": null, "versionEndIncluding": "2.2.10", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "66600BCA-D439-4743-8AE7-4E9433951F6F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "6544C9E0-CD92-407A-A17D-839CC84379CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "EF6D8ED9-01E2-429C-892C-1BDE207C0D34", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "89285DBF-9B65-4A8A-9ABC-1894C484A84E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "1E6ABC9F-775E-4D4C-91AB-35581F493EC5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "6A0B981D-AE93-4312-8AEC-99F157AAFA83", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.6:*:*:*:*:*:*:*", "matchCriteriaId": "73CA07B9-2DE2-4E6A-921D-89667AB54250", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.7:*:*:*:*:*:*:*", "matchCriteriaId": "223B2881-E108-45F5-AF97-6BF740B58420", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.0.8:*:*:*:*:*:*:*", "matchCriteriaId": "68D5B94B-B7FD-475E-BB9E-47871592959F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.0:*:*:*:*:*:*:*", "matchCriteriaId": "397FB64F-732C-41BC-BFAF-5D4742AD3E39", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.1:*:*:*:*:*:*:*", "matchCriteriaId": "7B762680-99DD-40A1-9D81-21E01A139BEB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.2:*:*:*:*:*:*:*", "matchCriteriaId": "3C9A56B2-5985-4CE3-B206-C657ED992280", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.3:*:*:*:*:*:*:*", "matchCriteriaId": "DDA3C9FA-A54C-4752-B2E0-986B6808423B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.4:*:*:*:*:*:*:*", "matchCriteriaId": "72BAE1E7-E1E7-45EB-AB4E-5E0DEAD84630", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.1.5:*:*:*:*:*:*:*", "matchCriteriaId": "539CA3F9-8AA5-44A3-917C-BCD94953B3E3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.0:*:*:*:*:*:*:*", "matchCriteriaId": "3C4F2E50-2861-47B1-B4F8-DB3C7F4EDFAB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "357A9A52-0915-4865-B2B7-619A776BF8DD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "686065C6-CA40-4ACC-9927-AB2FD2679362", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.3:*:*:*:*:*:*:*", "matchCriteriaId": "B1B7FAA3-22E0-4464-BDCD-F77AB16FF76B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.4:*:*:*:*:*:*:*", "matchCriteriaId": "7140446F-DAAD-40EC-997E-1A9A140AC39C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.5:*:*:*:*:*:*:*", "matchCriteriaId": "D352065C-12CF-48E0-BD97-2C20178828A0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.6:*:*:*:*:*:*:*", "matchCriteriaId": "319FCE68-F2B0-4F3C-8772-C453F0B9B303", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.7:*:*:*:*:*:*:*", "matchCriteriaId": "00978BE1-0642-4A88-B2E6-B0ABD7E0E3E7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.8:*:*:*:*:*:*:*", "matchCriteriaId": "E94115D1-663A-4282-ABC0-5EE0DB2450C0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:modx:modx_revolution:2.2.9:*:*:*:*:*:*:*", "matchCriteriaId": "1D83A52A-A9E4-417C-AEFA-006D60518ECA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site scripting (XSS) vulnerability in manager/templates/default/header.tpl in ModX Revolution before 2.2.11 allows remote attackers to inject arbitrary web script or HTML via the \"a\" parameter."}, {"lang": "es", "value": "Vulnerabilidad de XSS en manager/templates/default/header.tpl en ModX Revolution en versiones anteriores a 2.2.11 permite a atacantes remotos inyectar secuencias de comandos web o HTML arbitrarios a trav\u00e9s del par\u00e1metro \"a\"."}], "evaluatorComment": null, "id": "CVE-2014-2080", "lastModified": "2015-07-30T14:52:44.890", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-03-01T00:01:09.590", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "http://modx.com/blog/2014/01/21/revolution-2.2.11%E2%80%94security-fixes-and-prevent-change-loss"}, {"source": "cve@mitre.org", "tags": null, "url": "http://seclists.org/oss-sec/2014/q1/431"}, {"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/65755"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Patch"], "url": "https://github.com/modxcms/revolution/commit/77463eb6a8090f474b04fdc1b72225cb93c558ea"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/modxcms/revolution/commit/77463eb6a8090f474b04fdc1b72225cb93c558ea"}, "type": "CWE-79"}
325
Determine whether the {function_name} code is vulnerable or not.
[ "<!--\n###################################### READ ME ###########################################\n### This changelog should always be read on `main` branch. Its contents on version ###\n### branches do not necessarily reflect the changes that have gone into that branch. ###\n##########################################################################################\n-->", "# Changelog", "All notable changes to Sourcegraph are documented in this file.", "<!-- START CHANGELOG -->", "## Unreleased", "### Added", "-", "### Changed", "-", "### Fixed", "-", "", "\n### Removed", "-", "## 3.33.0", "### Added", "- More rules have been added to the search query validation so that user get faster feedback on issues with their query. [#24747](https://github.com/sourcegraph/sourcegraph/pull/24747)\n- Bloom filters have been added to the zoekt indexing backend to accelerate queries with code fragments matching `\\w{4,}`. [zoekt#126](https://github.com/sourcegraph/zoekt/pull/126)\n- For short search queries containing no filters but the name of a supported programming language we are now suggesting to run the query with a language filter. [#25792](https://github.com/sourcegraph/sourcegraph/pull/25792)\n- The API scope used by GitLab OAuth can now optionally be configured in the provider. [#26152](https://github.com/sourcegraph/sourcegraph/pull/26152)", "### Changed", "- Search context management pages are now only available in the Sourcegraph enterprise version. Search context dropdown is disabled in the OSS version. [#25147](https://github.com/sourcegraph/sourcegraph/pull/25147)\n- Search contexts GQL API is now only available in the Sourcegraph enterprise version. [#25281](https://github.com/sourcegraph/sourcegraph/pull/25281)\n- When running a commit or diff query, the accepted values of `before` and `after` have changed from \"whatever git accepts\" to a [slightly more strict subset](https://docs.sourcegraph.com/code_search/reference/language#before) of that. [#25414](https://github.com/sourcegraph/sourcegraph/pull/25414)\n- Repogroups and version contexts are deprecated in favor of search contexts. Read more about the deprecation and how to migrate to search contexts in the [blog post](https://about.sourcegraph.com/blog/introducing-search-contexts). [#25676](https://github.com/sourcegraph/sourcegraph/pull/25676)\n- Search contexts are now enabled by default in the Sourcegraph enterprise version. [#25674](https://github.com/sourcegraph/sourcegraph/pull/25674)\n- Code Insights background queries will now retry a maximum of 10 times (down from 100). [#26057](https://github.com/sourcegraph/sourcegraph/pull/26057)\n- Our `sourcegraph/cadvisor` Docker image has been upgraded to cadvisor version `v0.42.0`. [#26126](https://github.com/sourcegraph/sourcegraph/pull/26126)\n- Our `jaeger` version in the `sourcegraph/sourcegraph` Docker image has been upgraded to `1.24.0`. [#26215](https://github.com/sourcegraph/sourcegraph/pull/26215)", "### Fixed", "- A search regression in 3.32.0 which caused instances with search indexing _disabled_ (very rare) via `\"search.index.enabled\": false,` in their site config to crash with a panic. [#25321](https://github.com/sourcegraph/sourcegraph/pull/25321)\n- An issue where the default `search.index.enabled` value on single-container Docker instances would incorrectly be computed as `false` in some situations. [#25321](https://github.com/sourcegraph/sourcegraph/pull/25321)\n- StatefulSet service discovery in Kubernetes correctly constructs pod hostnames in the case where the ServiceName is different from the StatefulSet name. [#25146](https://github.com/sourcegraph/sourcegraph/pull/25146)\n- An issue where clicking on a link in the 'Revisions' search sidebar section would result in an invalid query if the query didn't already contain a 'repo:' filter. [#25076](https://github.com/sourcegraph/sourcegraph/pull/25076)\n- An issue where links to jump to Bitbucket Cloud wouldn't render in the UI. [#25533](https://github.com/sourcegraph/sourcegraph/pull/25533)\n- Fixed some code insights pings being aggregated on `anonymous_user_id` instead of `user_id`. [#25926](https://github.com/sourcegraph/sourcegraph/pull/25926)\n- Code insights running over all repositories using a commit search (`type:commit` or `type:diff`) would fail to deserialize and produce no results. [#25928](https://github.com/sourcegraph/sourcegraph/pull/25928)\n- Fixed an issue where code insights queries could produce a panic on queued records that did not include a `record_time` [#25929](https://github.com/sourcegraph/sourcegraph/pull/25929)\n- Fixed an issue where Batch Change changeset diffs would sometimes render incorrectly when previewed from the UI if they contained deleted empty lines. [#25866](https://github.com/sourcegraph/sourcegraph/pull/25866)\n- An issue where `repo:contains.commit.after()` would fail on some malformed git repositories. [#25974](https://github.com/sourcegraph/sourcegraph/issues/25974)\n- Fixed primary email bug where users with no primary email set would break the email setting page when trying to add a new email. [#25008](https://github.com/sourcegraph/sourcegraph/pull/25008)\n- An issue where keywords like `and`, `or`, `not` would not be highlighted properly in the search bar due to the presence of quotes. [#26135](https://github.com/sourcegraph/sourcegraph/pull/26135)\n- An issue where frequent search indexing operations led to incoming search queries timing out. When these timeouts happened in quick succession, `zoekt-webserver` processes would shut themselves down via their `watchdog` routine. This should now only happen when a given `zoekt-webserver` is under-provisioned on CPUs. [#25872](https://github.com/sourcegraph/sourcegraph/issues/25872)\n- Since 3.28.0, Batch Changes webhooks would not update changesets opened in private repositories. This has been fixed. [#26380](https://github.com/sourcegraph/sourcegraph/issues/26380)\n- Reconciling batch changes could stall when updating the state of a changeset that already existed. This has been fixed. [#26386](https://github.com/sourcegraph/sourcegraph/issues/26386)", "### Removed", "- Batch Changes changeset specs stored the raw JSON used when creating them, which is no longer used and is not exposed in the API. This column has been removed, thereby saving space in the Sourcegraph database. [#25453](https://github.com/sourcegraph/sourcegraph/issues/25453)\n- The query builder page experimental feature, which was disabled in 3.21, is now removed. The setting `{ \"experimentalFeatures\": { \"showQueryBuilder\": true } }` now has no effect. [#26125](https://github.com/sourcegraph/sourcegraph/pull/26125)", "## 3.32.0", "### Added", "- The search sidebar shows a revisions section if all search results are from a single repository. This makes it easier to search in and switch between different revisions. [#23835](https://github.com/sourcegraph/sourcegraph/pull/23835)\n- The various alerts overview panels in Grafana can now be clicked to go directly to the relevant panels and dashboards. [#24920](https://github.com/sourcegraph/sourcegraph/pull/24920)\n- Added a `Documentation` tab to the Site Admin Maintenance panel that links to the official Sourcegraph documentation. [#24917](https://github.com/sourcegraph/sourcegraph/pull/24917)\n- Code Insights that run over all repositories now generate a moving daily snapshot between time points. [#24804](https://github.com/sourcegraph/sourcegraph/pull/24804)\n- The Code Insights GraphQL API now restricts the results to user, org, and globally scoped insights. Insights will be synced to the database with access associated to the user or org setting containing the insight definition. [#25017](https://github.com/sourcegraph/sourcegraph/pull/25017)\n- The timeout for long-running Git commands can be customized via `gitLongCommandTimeout` in the site config. [#25080](https://github.com/sourcegraph/sourcegraph/pull/25080)", "### Changed", "- `allowGroupsPermissionsSync` in the GitHub authorization provider is now required to enable the experimental GitHub teams and organization permissions caching. [#24561](https://github.com/sourcegraph/sourcegraph/pull/24561)\n- GitHub external code hosts now validate if a corresponding authorization provider is set, and emits a warning if not. [#24526](https://github.com/sourcegraph/sourcegraph/pull/24526)\n- Sourcegraph is now built with Go 1.17. [#24566](https://github.com/sourcegraph/sourcegraph/pull/24566)\n- Code Insights is now available only in the Sourcegraph enterprise. [#24741](https://github.com/sourcegraph/sourcegraph/pull/24741)\n- Prometheus in Sourcegraph with Docker Compose now scrapes Postgres and Redis instances for metrics. [deploy-sourcegraph-docker#580](https://github.com/sourcegraph/deploy-sourcegraph-docker/pull/580)\n- Symbol suggestions now leverage optimizations for global searches. [#24943](https://github.com/sourcegraph/sourcegraph/pull/24943)", "### Fixed", "- Fixed a number of issues where repository permissions sync may fail for instances with very large numbers of repositories. [#24852](https://github.com/sourcegraph/sourcegraph/pull/24852), [#24972](https://github.com/sourcegraph/sourcegraph/pull/24972)\n- Fixed excessive re-rendering of the whole web application on every keypress in the search query input. [#24844](https://github.com/sourcegraph/sourcegraph/pull/24844)\n- Code Insights line chart now supports different timelines for each data series (lines). [#25005](https://github.com/sourcegraph/sourcegraph/pull/25005)\n- Postgres exporter now exposes pg_stat_activity account to show the number of active DB connections. [#25086](https://github.com/sourcegraph/sourcegraph/pull/25086)", "### Removed", "- The `PRECISE_CODE_INTEL_DATA_TTL` environment variable is no longer read by the worker service. Instead, global and repository-specific data retention policies configurable in the UI by site-admins will control the length of time LSIF uploads are considered _fresh_. [#24793](https://github.com/sourcegraph/sourcegraph/pull/24793)\n- The `repo.cloned` column was removed as it was deprecated in 3.26. [#25066](https://github.com/sourcegraph/sourcegraph/pull/25066)", "## 3.31.2", "### Fixed", "- Fixed multiple CVEs for [libssl](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-3711) and [Python3](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-29921). [#24700](https://github.com/sourcegraph/sourcegraph/pull/24700) [#24620](https://github.com/sourcegraph/sourcegraph/pull/24620) [#24695](https://github.com/sourcegraph/sourcegraph/pull/24695)", "## 3.31.1", "### Added", "- The required authentication scopes required to enable caching behaviour for GitHub repository permissions can now be requested via `allowGroupsPermissionsSync` in GitHub `auth.providers`. [#24328](https://github.com/sourcegraph/sourcegraph/pull/24328)", "### Changed", "- Caching behaviour for GitHub repository permissions enabled via the `authorization.groupsCacheTTL` field in the code host config can now leverage additional caching of team and organization permissions for repository permissions syncing (on top of the caching for user permissions syncing introduced in 3.31). [#24328](https://github.com/sourcegraph/sourcegraph/pull/24328)", "## 3.31.0", "### Added", "- Backend Code Insights GraphQL queries now support arguments `includeRepoRegex` and `excludeRepoRegex` to filter on repository names. [#23256](https://github.com/sourcegraph/sourcegraph/pull/23256)\n- Code Insights background queries now process in a priority order backwards through time. This will allow insights to populate concurrently. [#23101](https://github.com/sourcegraph/sourcegraph/pull/23101)\n- Operator documentation has been added to the Search Reference sidebar section. [#23116](https://github.com/sourcegraph/sourcegraph/pull/23116)\n- Syntax highlighting support for the [Cue](https://cuelang.org) language.\n- Reintroduced a revised version of the Search Types sidebar section. [#23170](https://github.com/sourcegraph/sourcegraph/pull/23170)\n- Improved usability where filters followed by a space in the search query will warn users that the filter value is empty. [#23646](https://github.com/sourcegraph/sourcegraph/pull/23646)\n- Perforce: [`git p4`'s `--use-client-spec` option](https://git-scm.com/docs/git-p4#Documentation/git-p4.txt---use-client-spec) can now be enabled by configuring the `p4.client` field. [#23833](https://github.com/sourcegraph/sourcegraph/pull/23833), [#23845](https://github.com/sourcegraph/sourcegraph/pull/23845)\n- Code Insights will do a one-time reset of ephemeral insights specific database tables to clean up stale and invalid data. Insight data will regenerate automatically. [23791](https://github.com/sourcegraph/sourcegraph/pull/23791)\n- Perforce: added basic support for Perforce permission table path wildcards. [#23755](https://github.com/sourcegraph/sourcegraph/pull/23755)\n- Added autocompletion and search filtering of branch/tag/commit revisions to the repository compare page. [#23977](https://github.com/sourcegraph/sourcegraph/pull/23977)\n- Batch Changes changesets can now be [set to published when previewing new or updated batch changes](https://docs.sourcegraph.com/batch_changes/how-tos/publishing_changesets#within-the-ui). [#22912](https://github.com/sourcegraph/sourcegraph/issues/22912)\n- Added Python3 to server and gitserver images to enable git-p4 support. [#24204](https://github.com/sourcegraph/sourcegraph/pull/24204)\n- Code Insights drill-down filters now allow filtering insights data on the dashboard page using repo: filters. [#23186](https://github.com/sourcegraph/sourcegraph/issues/23186)\n- GitHub repository permissions can now leverage caching of team and organization permissions for user permissions syncing. Caching behaviour can be enabled via the `authorization.groupsCacheTTL` field in the code host config. This can significantly reduce the amount of time it takes to perform a full permissions sync due to reduced instances of being rate limited by the code host. [#23978](https://github.com/sourcegraph/sourcegraph/pull/23978)", "### Changed", "- Code Insights will now always backfill from the time the data series was created. [#23430](https://github.com/sourcegraph/sourcegraph/pull/23430)\n- Code Insights queries will now extract repository name out of the GraphQL response instead of going to the database. [#23388](https://github.com/sourcegraph/sourcegraph/pull/23388)\n- Code Insights backend has moved from the `repo-updater` service to the `worker` service. [#23050](https://github.com/sourcegraph/sourcegraph/pull/23050)\n- Code Insights feature flag `DISABLE_CODE_INSIGHTS` environment variable has moved from the `repo-updater` service to the `worker` service. Any users of this flag will need to update their `worker` service configuration to continue using it. [#23050](https://github.com/sourcegraph/sourcegraph/pull/23050)\n- Updated Docker-Compose Caddy Image to v2.0.0-alpine. [#468](https://github.com/sourcegraph/deploy-sourcegraph-docker/pull/468)\n- Code Insights historical samples will record using the timestamp of the commit that was searched. [#23520](https://github.com/sourcegraph/sourcegraph/pull/23520)\n- Authorization checks are now handled using role based permissions instead of manually altering SQL statements. [23398](https://github.com/sourcegraph/sourcegraph/pull/23398)\n- Docker Compose: the Jaeger container's `SAMPLING_STRATEGIES_FILE` now has a default value. If you are currently using a custom sampling strategies configuration, you may need to make sure your configuration is not overridden by the change when upgrading. [sourcegraph/deploy-sourcegraph#489](https://github.com/sourcegraph/deploy-sourcegraph-docker/pull/489)\n- Code Insights historical samples will record using the most recent commit to the start of the frame instead of the middle of the frame. [#23573](https://github.com/sourcegraph/sourcegraph/pull/23573)\n- The copy icon displayed next to files and repositories will now copy the file or repository path. Previously, this action copied the URL to clipboard. [#23390](https://github.com/sourcegraph/sourcegraph/pull/23390)\n- Sourcegraph's Prometheus dependency has been upgraded to v2.28.1. [23663](https://github.com/sourcegraph/sourcegraph/pull/23663)\n- Sourcegraph's Alertmanager dependency has been upgraded to v0.22.2. [23663](https://github.com/sourcegraph/sourcegraph/pull/23714)\n- Code Insights will now schedule sample recordings for the first of the next month after creation or a previous recording. [#23799](https://github.com/sourcegraph/sourcegraph/pull/23799)\n- Code Insights now stores data in a new format. Data points will store complete vectors for all repositories even if the underlying Sourcegraph queries were compressed. [#23768](https://github.com/sourcegraph/sourcegraph/pull/23768)\n- Code Insights rate limit values have been tuned for a more reasonable performance. [#23860](https://github.com/sourcegraph/sourcegraph/pull/23860)\n- Code Insights will now generate historical data once per month on the first of the month, up to the configured `insights.historical.frames` number of frames. [#23768](https://github.com/sourcegraph/sourcegraph/pull/23768)\n- Code Insights will now schedule recordings for the first of the next calendar month after an insight is created or recorded. [#23799](https://github.com/sourcegraph/sourcegraph/pull/23799)\n- Code Insights will attempt to sync insight definitions from settings to the database once every 10 minutes. [23805](https://github.com/sourcegraph/sourcegraph/pull/23805)\n- Code Insights exposes information about queries that are flagged `dirty` through the `insights` GraphQL query. [#23857](https://github.com/sourcegraph/sourcegraph/pull/23857/)\n- Code Insights GraphQL query `insights` will now fetch 12 months of data instead of 6 if a specific time range is not provided. [#23786](https://github.com/sourcegraph/sourcegraph/pull/23786)\n- Code Insights will now generate 12 months of historical data during a backfill instead of 6. [#23860](https://github.com/sourcegraph/sourcegraph/pull/23860)\n- The `sourcegraph-frontend.Role` in Kubernetes deployments was updated to permit statefulsets access in the Kubernetes API. This is needed to better support stable service discovery for stateful sets during deployments, which isn't currently possible by using service endpoints. [#3670](https://github.com/sourcegraph/deploy-sourcegraph/pull/3670) [#23889](https://github.com/sourcegraph/sourcegraph/pull/23889)\n- For Docker-Compose and Kubernetes users, the built-in main Postgres and codeintel databases have switched to an alpine Docker image. This requires re-indexing the entire database. This process can take up to a few hours on systems with large datasets. [#23697](https://github.com/sourcegraph/sourcegraph/pull/23697)\n- Results are now streamed from searcher by default, improving memory usage and latency for large, unindexed searches. [#23754](https://github.com/sourcegraph/sourcegraph/pull/23754)\n- [`deploy-sourcegraph` overlays](https://docs.sourcegraph.com/admin/install/kubernetes/configure#overlays) now use `resources:` instead of the [deprecated `bases:` field](https://kubectl.docs.kubernetes.io/references/kustomize/kustomization/bases/) for referencing Kustomize bases. [deploy-sourcegraph#3606](https://github.com/sourcegraph/deploy-sourcegraph/pull/3606)\n- The `deploy-sourcegraph-docker` Pure Docker deployment scripts and configuration has been moved to the `./pure-docker` subdirectory. [deploy-sourcegraph-docker#454](https://github.com/sourcegraph/deploy-sourcegraph-docker/pull/454)\n- In Kubernetes deployments, setting the `SRC_GIT_SERVERS` environment variable explicitly is no longer needed. Addresses of the gitserver pods will be discovered automatically and in the same numerical order as with the static list. Unset the env var in your `frontend.Deployment.yaml` to make use of this feature. [#24094](https://github.com/sourcegraph/sourcegraph/pull/24094)\n- The consistent hashing scheme used to distribute repositories across indexed-search replicas has changed to improve distribution and reduce load discrepancies. In the next upgrade, indexed-search pods will re-index the majority of repositories since the repo to replica assignments will change. This can take a few hours in large instances, but searches should succeed during that time since a replica will only delete a repo once it has been indexed in the new replica that owns it. You can monitor this process in the Zoekt Index Server Grafana dashboard - the \"assigned\" repos in \"Total number of repos\" will spike and then reduce until it becomes the same as \"indexed\". As a fail-safe, the old consistent hashing scheme can be enabled by setting the `SRC_ENDPOINTS_CONSISTENT_HASH` env var to `consistent(crc32ieee)` in the `sourcegraph-frontend` deployment. [#23921](https://github.com/sourcegraph/sourcegraph/pull/23921)\n- In Kubernetes deployments an emptyDir (`/dev/shm`) is now mounted in the `pgsql` deployment to allow Postgres to access more than 64KB shared memory. This value should be configured to match the `shared_buffers` value in your Postgres configuration. [deploy-sourcegraph#3784](https://github.com/sourcegraph/deploy-sourcegraph/pull/3784/)", "### Fixed", "- The search reference will now show matching entries when using the filter input. [#23224](https://github.com/sourcegraph/sourcegraph/pull/23224)\n- Graceful termination periods have been added to database deployments. [#3358](https://github.com/sourcegraph/deploy-sourcegraph/pull/3358) & [#477](https://github.com/sourcegraph/deploy-sourcegraph-docker/pull/477)\n- All commit search results for `and`-expressions are now highlighted. [#23336](https://github.com/sourcegraph/sourcegraph/pull/23336)\n- Email notifiers in `observability.alerts` now correctly respect the `email.smtp.noVerifyTLS` site configuration field. [#23636](https://github.com/sourcegraph/sourcegraph/issues/23636)\n- Alertmanager (Prometheus) now respects `SMTPServerConfig.noVerifyTLS` field. [#23636](https://github.com/sourcegraph/sourcegraph/issues/23636)\n- Clicking on symbols in the left search pane now renders hover tooltips for indexed repositories. [#23664](https://github.com/sourcegraph/sourcegraph/pull/23664)\n- Fixed a result streaming throttling issue that was causing significantly increased latency for some searches. [#23736](https://github.com/sourcegraph/sourcegraph/pull/23736)\n- GitCredentials passwords stored in AWS CodeCommit configuration is now redacted. [#23832](https://github.com/sourcegraph/sourcegraph/pull/23832)\n- Patched a vulnerability in `apk-tools`. [#23917](https://github.com/sourcegraph/sourcegraph/pull/23917)\n- Line content was being duplicated in unindexed search payloads, causing memory instability for some dense search queries. [#23918](https://github.com/sourcegraph/sourcegraph/pull/23918)\n- Updating draft merge requests on GitLab from batch changes no longer removes the draft status. [#23944](https://github.com/sourcegraph/sourcegraph/issues/23944)\n- Report highlight matches instead of line matches in search results. [#21443](https://github.com/sourcegraph/sourcegraph/issues/21443)\n- Force the `codeinsights-db` database to read from the `configMap` configuration file by explicitly setting the `POSTGRESQL_CONF_DIR` environment variable to the `configMap` mount path. [deploy-sourcegraph#3788](https://github.com/sourcegraph/deploy-sourcegraph/pull/3788)", "### Removed", "- The old batch repository syncer was removed and can no longer be activated by setting `ENABLE_STREAMING_REPOS_SYNCER=false`. [#22949](https://github.com/sourcegraph/sourcegraph/pull/22949)\n- Email notifications for saved searches are now deprecated in favor of Code Monitoring. Email notifications can no longer be enabled for saved searches. Saved searches that already have notifications enabled will continue to work, but there is now a button users can click to migrate to code monitors. Notifications for saved searches will be removed entirely in the future. [#23275](https://github.com/sourcegraph/sourcegraph/pull/23275)\n- The `sg_service` Postgres role and `sg_repo_access_policy` policy on the `repo` table have been removed due to performance concerns. [#23622](https://github.com/sourcegraph/sourcegraph/pull/23622)\n- Deprecated site configuration field `email.smtp.disableTLS` has been removed. [#23639](https://github.com/sourcegraph/sourcegraph/pull/23639)\n- Deprecated language servers have been removed from `deploy-sourcegraph`. [deploy-sourcegraph#3605](https://github.com/sourcegraph/deploy-sourcegraph/pull/3605)\n- The experimental `codeInsightsAllRepos` feature flag has been removed. [#23850](https://github.com/sourcegraph/sourcegraph/pull/23850)", "## 3.30.4", "### Added", "- Add a new environment variable `SRC_HTTP_CLI_EXTERNAL_TIMEOUT` to control the timeout for all external HTTP requests. [#23620](https://github.com/sourcegraph/sourcegraph/pull/23620)", "### Changed", "- Postgres has been upgraded to `12.8` in the single-server Sourcegraph image [#23999](https://github.com/sourcegraph/sourcegraph/pull/23999)", "## 3.30.3", "**⚠️ Users on 3.29.x are advised to upgrade directly to 3.30.3**. If you have already upgraded to 3.30.0, 3.30.1, or 3.30.2 please follow [this migration guide](https://docs.sourcegraph.com/admin/migration/3_30).", "### Fixed", "- Codeintel-db database images have been reverted back to debian due to corruption caused by glibc and alpine. [23324](https://github.com/sourcegraph/sourcegraph/pull/23324)", "## 3.30.2", "**⚠️ Users on 3.29.x are advised to upgrade directly to 3.30.3**. If you have already upgraded to 3.30.0, 3.30.1, or 3.30.2 please follow [this migration guide](https://docs.sourcegraph.com/admin/migration/3_30).", "### Fixed", "- Postgres database images have been reverted back to debian due to corruption caused by glibc and alpine. [23302](https://github.com/sourcegraph/sourcegraph/pull/23302)", "## 3.30.1", "**⚠️ Users on 3.29.x are advised to upgrade directly to 3.30.3**. If you have already upgraded to 3.30.0, 3.30.1, or 3.30.2 please follow [this migration guide](https://docs.sourcegraph.com/admin/migration/3_30).", "### Fixed", "- An issue where the UI would occasionally display `lsifStore.Ranges: ERROR: relation \\\"lsif_documentation_mappings\\\" does not exist (SQLSTATE 42P01)` [#23115](https://github.com/sourcegraph/sourcegraph/pull/23115)\n- Fixed a vulnerability in our Postgres Alpine image related to libgcrypt [#23174](https://github.com/sourcegraph/sourcegraph/pull/23174)\n- When syncing in streaming mode, repo-updater will now ensure a repo's transaction is committed before notifying gitserver to update that repo. [#23169](https://github.com/sourcegraph/sourcegraph/pull/23169)\n- When encountering spurious errors during streaming syncing (like temporary 500s from codehosts), repo-updater will no longer delete all associated repos that weren't seen. Deletion will happen only if there were no errors or if the error was one of \"Unauthorized\", \"Forbidden\" or \"Account Suspended\". [#23171](https://github.com/sourcegraph/sourcegraph/pull/23171)\n- External HTTP requests are now automatically retried when appropriate. [#23131](https://github.com/sourcegraph/sourcegraph/pull/23131)", "## 3.30.0", "**⚠️ Users on 3.29.x are advised to upgrade directly to 3.30.3**. If you have already upgraded to 3.30.0, 3.30.1, or 3.30.2 please follow [this migration guide](https://docs.sourcegraph.com/admin/migration/3_30).", "### Added", "- Added support for `select:file.directory` in search queries, which returns unique directory paths for results that satisfy the query. [#22449](https://github.com/sourcegraph/sourcegraph/pull/22449)\n- An `sg_service` Postgres role has been introduced, as well as an `sg_repo_access_policy` policy on the `repo` table that restricts access to that role. The role that owns the `repo` table will continue to get unrestricted access. [#22303](https://github.com/sourcegraph/sourcegraph/pull/22303)\n- Every service that connects to the database (i.e. Postgres) now has a \"Database connections\" monitoring section in its Grafana dashboard. [#22570](https://github.com/sourcegraph/sourcegraph/pull/22570)\n- A new bulk operation to close many changesets at once has been added to Batch Changes. [#22547](https://github.com/sourcegraph/sourcegraph/pull/22547)\n- Backend Code Insights will aggregate viewable repositories based on the authenticated user. [#22471](https://github.com/sourcegraph/sourcegraph/pull/22471)\n- Added support for highlighting .frugal files as Thrift syntax.\n- Added `file:contains.content(regexp)` predicate, which filters only to files that contain matches of the given pattern. [#22666](https://github.com/sourcegraph/sourcegraph/pull/22666)\n- Repository syncing is now done in streaming mode by default. Customers with many repositories should notice code host updates much faster, with repo-updater consuming less memory. Using the previous batch mode can be done by setting the `ENABLE_STREAMING_REPOS_SYNCER` environment variable to `false` in `repo-updater`. That environment variable will be deleted in the next release. [#22756](https://github.com/sourcegraph/sourcegraph/pull/22756)\n- Enabled the ability to query Batch Changes changesets, changesets stats, and file diff stats for an individual repository via the Sourcegraph GraphQL API. [#22744](https://github.com/sourcegraph/sourcegraph/pull/22744/)\n- Added \"Groovy\" to the initial `lang:` filter suggestions in the search bar. [#22755](https://github.com/sourcegraph/sourcegraph/pull/22755)\n- The `lang:` filter suggestions now show all supported, matching languages as the user types a language name. [#22765](https://github.com/sourcegraph/sourcegraph/pull/22765)\n- Code Insights can now be grouped into dashboards. [#22215](https://github.com/sourcegraph/sourcegraph/issues/22215)\n- Batch Changes changesets can now be [published from the Sourcegraph UI](https://docs.sourcegraph.com/batch_changes/how-tos/publishing_changesets#within-the-ui). [#18277](https://github.com/sourcegraph/sourcegraph/issues/18277)\n- The repository page now has a new button to view batch change changesets created in that specific repository, with a badge indicating how many changesets are currently open. [#22804](https://github.com/sourcegraph/sourcegraph/pull/22804)\n- Experimental: Search-based code insights can run over all repositories on the instance. To enable, use the feature flag `\"experimentalFeatures\": { \"codeInsightsAllRepos\": true }` and tick the checkbox in the insight creation/edit UI. [#22759](https://github.com/sourcegraph/sourcegraph/issues/22759)\n- Search References is a new search sidebar section to simplify learning about the available search filters directly where they are used. [#21539](https://github.com/sourcegraph/sourcegraph/issues/21539)", "### Changed", "- Backend Code Insights only fills historical data frames that have changed to reduce the number of searches required. [#22298](https://github.com/sourcegraph/sourcegraph/pull/22298)\n- Backend Code Insights displays data points for a fixed 6 months period in 2 week intervals, and will carry observations forward that are missing. [#22298](https://github.com/sourcegraph/sourcegraph/pull/22298)\n- Backend Code Insights now aggregate over 26 weeks instead of 6 months. [#22527](https://github.com/sourcegraph/sourcegraph/pull/22527)\n- Search queries now disallow specifying `rev:` without `repo:`. Note that to search across potentially multiple revisions, a query like `repo:.* rev:<revision>` remains valid. [#22705](https://github.com/sourcegraph/sourcegraph/pull/22705)\n- The extensions status bar on diff pages has been redesigned and now shows information for both the base and head commits. [#22123](https://github.com/sourcegraph/sourcegraph/pull/22123/files)\n- The `applyBatchChange` and `createBatchChange` mutations now accept an optional `publicationStates` argument to set the publication state of specific changesets within the batch change. [#22485](https://github.com/sourcegraph/sourcegraph/pull/22485) and [#22854](https://github.com/sourcegraph/sourcegraph/pull/22854)\n- Search queries now return up to 80 suggested filters. Previously we returned up to 24. [#22863](https://github.com/sourcegraph/sourcegraph/pull/22863)\n- GitHub code host connections can now include `repositoryQuery` entries that match more than 1000 repositories from the GitHub search API without requiring the previously documented work-around of splitting the query up with `created:` qualifiers, which is now done automatically. [#2562](https://github.com/sourcegraph/sourcegraph/issues/2562)", "### Fixed", "- The Batch Changes user and site credential encryption migrators added in Sourcegraph 3.28 could report zero progress when encryption was disabled, even though they had nothing to do. This has been fixed, and progress will now be correctly reported. [#22277](https://github.com/sourcegraph/sourcegraph/issues/22277)\n- Listing Github Entreprise org repos now returns internal repos as well. [#22339](https://github.com/sourcegraph/sourcegraph/pull/22339)\n- Jaeger works in Docker-compose deployments again. [#22691](https://github.com/sourcegraph/sourcegraph/pull/22691)\n- A bug where the pattern `)` makes the browser unresponsive. [#22738](https://github.com/sourcegraph/sourcegraph/pull/22738)\n- An issue where using `select:repo` in conjunction with `and` patterns did not yield expected repo results. [#22743](https://github.com/sourcegraph/sourcegraph/pull/22743)\n- The `isLocked` and `isDisabled` fields of GitHub repositories are now fetched correctly from the GraphQL API of GitHub Enterprise instances. Users that rely on the `repos` config in GitHub code host connections should update so that locked and disabled repositories defined in that list are actually skipped. [#22788](https://github.com/sourcegraph/sourcegraph/pull/22788)\n- Homepage no longer fails to load if there are invalid entries in user's search history. [#22857](https://github.com/sourcegraph/sourcegraph/pull/22857)\n- An issue where regexp query highlighting in the search bar would render incorrectly on Firefox. [#23043](https://github.com/sourcegraph/sourcegraph/pull/23043)\n- Code intelligence uploads and indexes are restricted to only site-admins. It was read-only for any user. [#22890](https://github.com/sourcegraph/sourcegraph/pull/22890)\n- Daily usage statistics are restricted to only site-admins. It was read-only for any user. [#23026](https://github.com/sourcegraph/sourcegraph/pull/23026)\n- Ephemeral storage requests now match their cache size requests for Kubernetes deployments. [#2953](https://github.com/sourcegraph/deploy-sourcegraph/pull/2953)", "### Removed", "- The experimental paginated search feature (the `stable:` keyword) has been removed, to be replaced with streaming search. [#22428](https://github.com/sourcegraph/sourcegraph/pull/22428)\n- The experimental extensions view page has been removed. [#22565](https://github.com/sourcegraph/sourcegraph/pull/22565)\n- A search query diagnostic that previously warned the user when quotes are interpreted literally has been removed. The literal meaning has been Sourcegraph's default search behavior for some time now. [#22892](https://github.com/sourcegraph/sourcegraph/pull/22892)\n- Non-root overlays were removed for `deploy-sourcegraph` in favor of using `non-privileged`. [#3404](https://github.com/sourcegraph/deploy-sourcegraph/pull/3404)", "### API docs (experimental)", "API docs is a new experimental feature of Sourcegraph ([learn more](https://docs.sourcegraph.com/code_intelligence/apidocs)). It is enabled by default in Sourcegraph 3.30.0.", "- API docs is enabled by default in Sourcegraph 3.30.0. It can be disabled by adding `\"apiDocs\": false` to the `experimentalFeatures` section of user settings.\n- The API docs landing page now indicates what API docs are and provide more info.\n- The API docs landing page now represents the code in the repository root, instead of an empty page.\n- Pages now correctly indicate it is an experimental feature, and include a feedback widget.\n- Subpages linked via the sidebar are now rendered much better, and have an expandable section.\n- Symbols in documentation now have distinct icons for e.g. functions/vars/consts/etc.\n- Symbols are now sorted in exported-first, alphabetical order.\n- Repositories without LSIF documentation data now show a friendly error page indicating what languages are supported, how to set it up, etc.\n- API docs can now distinguish between different types of symbols, tests, examples, benchmarks, etc. and whether symbols are public/private - to support filtering in the future.\n- Only public/exported symbols are included by default for now.\n- URL paths for Go packages are now friendlier, e.g. `/-/docs/cmd/frontend/auth` instead of `/-/docs/cmd-frontend-auth`.\n- URLs are now formatted by the language indexer, in a way that makes sense for the language, e.g. `#Mocks.CreateUserAndSave` instead of `#ypeMocksCreateUserAndSave` for a Go method `CreateUserAndSave` on type `Mocks`.\n- Go blank identifier assignments `var _ = ...` are no longer incorrectly included.\n- Go symbols defined within functions, e.g. a `var` inside a `func` scope are no longer incorrectly included.\n- `Functions`, `Variables`, and other top-level sections are no longer rendered empty if there are none in that section.\n- A new test suite for LSIF indexers implementing the Sourcegraph documentation extension to LSIF [is available](https://github.com/sourcegraph/lsif-static-doc).\n- We now emit the LSIF data needed to in the future support \"Jump to API docs\" from code views, \"View code\" from API docs, usage examples in API docs, and search indexing.\n- Various UI style issues, color contrast issues, etc. have been fixed.\n- Major improvements to the GraphQL APIs for API documentation.", "## 3.29.0", "### Added", "- Code Insights queries can now run concurrently up to a limit set by the `insights.query.worker.concurrency` site config. [#21219](https://github.com/sourcegraph/sourcegraph/pull/21219)\n- Code Insights workers now support a rate limit for query execution and historical data frame analysis using the `insights.query.worker.rateLimit` and `insights.historical.worker.rateLimit` site configurations. [#21533](https://github.com/sourcegraph/sourcegraph/pull/21533)\n- The GraphQL `Site` `SettingsSubject` type now has an `allowSiteSettingsEdits` field to allow clients to determine whether the instance uses the `GLOBAL_SETTINGS_FILE` environment variable. [#21827](https://github.com/sourcegraph/sourcegraph/pull/21827)\n- The Code Insights creation UI now remembers previously filled-in field values when returning to the form after having navigated away. [#21744](https://github.com/sourcegraph/sourcegraph/pull/21744)\n- The Code Insights creation UI now shows autosuggestions for the repository field. [#21699](https://github.com/sourcegraph/sourcegraph/pull/21699)\n- A new bulk operation to retry many changesets at once has been added to Batch Changes. [#21173](https://github.com/sourcegraph/sourcegraph/pull/21173)\n- A `security_event_logs` database table has been added in support of upcoming security-related efforts. [#21949](https://github.com/sourcegraph/sourcegraph/pull/21949)\n- Added featured Sourcegraph extensions query to the GraphQL API, as well as a section in the extension registry to display featured extensions. [#21665](https://github.com/sourcegraph/sourcegraph/pull/21665)\n- The search page now has a `create insight` button to create search-based insight based on your search query [#21943](https://github.com/sourcegraph/sourcegraph/pull/21943)\n- Added support for Terraform syntax highlighting. [#22040](https://github.com/sourcegraph/sourcegraph/pull/22040)\n- A new bulk operation to merge many changesets at once has been added to Batch Changes. [#21959](https://github.com/sourcegraph/sourcegraph/pull/21959)\n- Pings include aggregated usage for the Code Insights creation UI, organization visible insight count per insight type, and insight step size in days. [#21671](https://github.com/sourcegraph/sourcegraph/pull/21671)\n- Search-based insight creation UI now supports `count:` filter in data series query input. [#22049](https://github.com/sourcegraph/sourcegraph/pull/22049)\n- Code Insights background workers will now index commits in a new table `commit_index` for future optimization efforts. [#21994](https://github.com/sourcegraph/sourcegraph/pull/21994)\n- The creation UI for search-based insights now supports the `count:` filter in the data series query input. [#22049](https://github.com/sourcegraph/sourcegraph/pull/22049)\n- A new service, `worker`, has been introduced to run background jobs that were previously run in the frontend. See the [deployment documentation](https://docs.sourcegraph.com/admin/workers) for additional details. [#21768](https://github.com/sourcegraph/sourcegraph/pull/21768)", "### Changed", "- SSH public keys generated to access code hosts with batch changes now include a comment indicating they originated from Sourcegraph. [#20523](https://github.com/sourcegraph/sourcegraph/issues/20523)\n- The copy query button is now permanently enabled and `experimentalFeatures.copyQueryButton` setting has been deprecated. [#21364](https://github.com/sourcegraph/sourcegraph/pull/21364)\n- Search streaming is now permanently enabled and `experimentalFeatures.searchStreaming` setting has been deprecated. [#21522](https://github.com/sourcegraph/sourcegraph/pull/21522)\n- Pings removes the collection of aggregate search filter usage counts and adds a smaller set of aggregate usage counts for query operators, predicates, and pattern counts. [#21320](https://github.com/sourcegraph/sourcegraph/pull/21320)\n- Sourcegraph will now refuse to start if there are unfinished [out-of-band-migrations](https://docs.sourcegraph.com/admin/migrations) that are deprecated in the current version. See the [upgrade documentation](https://docs.sourcegraph.com/admin/updates) for changes to the upgrade process. [#20967](https://github.com/sourcegraph/sourcegraph/pull/20967)\n- Code Insight pages now have new URLs [#21856](https://github.com/sourcegraph/sourcegraph/pull/21856)\n- We are proud to bring you [an entirely new visual design for the Sourcegraph UI](https://about.sourcegraph.com/blog/introducing-sourcegraphs-new-ui/). We think you’ll find this new design improves your experience and sets the stage for some incredible features to come. Some of the highlights include:", " - **Refined search results:** The redesigned search bar provides more space for expressive queries, and the new results sidebar helps to discover search syntax without referencing documentation.\n - **Improved focus on code:** We’ve reduced non-essential UI elements to provide greater focus on the code itself, and positioned the most important items so they’re unobtrusive and located exactly where they are needed.\n - **Improved layouts:** We’ve improved pages like diff views to make them easier to use and to help find information quickly.\n - **New navigation:** A new global navigation provides immediate discoverability and access to current and future functionality.\n - **Promoting extensibility:** We've brought the extension registry back to the main navigation and improved its design and navigation.", " With bulk of the redesign complete, future releases will include more improvements and refinements.", "### Fixed", "- Stricter validation of structural search queries. The `type:` parameter is not supported for structural searches and returns an appropriate alert. [#21487](https://github.com/sourcegraph/sourcegraph/pull/21487)\n- Batch changeset specs that are not attached to changesets will no longer prematurely expire before the batch specs that they are associated with. [#21678](https://github.com/sourcegraph/sourcegraph/pull/21678)\n- The Y-axis of Code Insights line charts no longer start at a negative value. [#22018](https://github.com/sourcegraph/sourcegraph/pull/22018)\n- Correctly handle field aliases in the query (like `r:` versus `repo:`) when used with `contains` predicates. [#22105](https://github.com/sourcegraph/sourcegraph/pull/22105)\n- Running a code insight over a timeframe when the repository didn't yet exist doesn't break the entire insight anymore. [#21288](https://github.com/sourcegraph/sourcegraph/pull/21288)", "### Removed", "- The deprecated GraphQL `icon` field on CommitSearchResult and Repository was removed. [#21310](https://github.com/sourcegraph/sourcegraph/pull/21310)\n- The undocumented `index` filter was removed from search type-ahead suggestions. [#18806](https://github.com/sourcegraph/sourcegraph/issues/18806)\n- Code host connection tokens aren't used for creating changesets anymore when the user is site admin and no credential has been specified. [#16814](https://github.com/sourcegraph/sourcegraph/issues/16814)", "## 3.28.0", "### Added", "- Added `select:commit.diff.added` and `select:commit.diff.removed` for `type:diff` search queries. These selectors return commit diffs only if a pattern matches in `added` (respespectively, `removed`) lines. [#20328](https://github.com/sourcegraph/sourcegraph/pull/20328)\n- Additional language autocompletions for the `lang:` filter in the search bar. [#20535](https://github.com/sourcegraph/sourcegraph/pull/20535)\n- Steps in batch specs can now have an `if:` attribute to enable conditional execution of different steps. [#20701](https://github.com/sourcegraph/sourcegraph/pull/20701)\n- Extensions can now log messages through `sourcegraph.app.log` to aid debugging user issues. [#20474](https://github.com/sourcegraph/sourcegraph/pull/20474)\n- Bulk comments on many changesets are now available in Batch Changes. [#20361](https://github.com/sourcegraph/sourcegraph/pull/20361)\n- Batch specs are now viewable when previewing changesets. [#19534](https://github.com/sourcegraph/sourcegraph/issues/19534)\n- Added a new UI for creating code insights. [#20212](https://github.com/sourcegraph/sourcegraph/issues/20212)", "### Changed", "- User and site credentials used in Batch Changes are now encrypted in the database if encryption is enabled with the `encryption.keys` config. [#19570](https://github.com/sourcegraph/sourcegraph/issues/19570)\n- All Sourcegraph images within [deploy-sourcegraph](https://github.com/sourcegraph/deploy-sourcegraph) now specify the registry. Thanks! @k24dizzle [#2901](https://github.com/sourcegraph/deploy-sourcegraph/pull/2901).\n- Default reviewers are now added to Bitbucket Server PRs opened by Batch Changes. [#20551](https://github.com/sourcegraph/sourcegraph/pull/20551)\n- The default memory requirements for the `redis-*` containers have been raised by 1GB (to a new total of 7GB). This change allows Redis to properly run its key-eviction routines (when under memory pressure) without getting killed by the host machine. This affects both the docker-compose and Kubernetes deployments. [sourcegraph/deploy-sourcegraph-docker#373](https://github.com/sourcegraph/deploy-sourcegraph-docker/pull/373) and [sourcegraph/deploy-sourcegraph#2898](https://github.com/sourcegraph/deploy-sourcegraph/pull/2898)\n- Only site admins can now list users on an instance. [#20619](https://github.com/sourcegraph/sourcegraph/pull/20619)\n- Repository permissions can now be enabled for site admins via the `authz.enforceForSiteAdmins` setting. [#20674](https://github.com/sourcegraph/sourcegraph/pull/20674)\n- Site admins can no longer view user added code host configuration. [#20851](https://github.com/sourcegraph/sourcegraph/pull/20851)\n- Site admins cannot add access tokens for any user by default. [#20988](https://github.com/sourcegraph/sourcegraph/pull/20988)\n- Our namespaced overlays now only scrape container metrics within that namespace. [#2969](https://github.com/sourcegraph/deploy-sourcegraph/pull/2969)\n- The extension registry main page has a new visual design that better conveys the most useful information about extensions, and individual extension pages have better information architecture. [#20822](https://github.com/sourcegraph/sourcegraph/pull/20822)", "### Fixed", "- Search returned inconsistent result counts when a `count:` limit was not specified.\n- Indexed search failed when the `master` branch needed indexing but was not the default. [#20260](https://github.com/sourcegraph/sourcegraph/pull/20260)\n- `repo:contains(...)` built-in did not respect parameters that affect repo filtering (e.g., `repogroup`, `fork`). It now respects these. [#20339](https://github.com/sourcegraph/sourcegraph/pull/20339)\n- An issue where duplicate results would render for certain `or`-expressions. [#20480](https://github.com/sourcegraph/sourcegraph/pull/20480)\n- Issue where the search query bar suggests that some `lang` values are not valid. [#20534](https://github.com/sourcegraph/sourcegraph/pull/20534)\n- Pull request event webhooks received from GitHub with unexpected actions no longer cause panics. [#20571](https://github.com/sourcegraph/sourcegraph/pull/20571)\n- Repository search patterns like `^repo/(prefix-suffix|prefix)$` now correctly match both `repo/prefix-suffix` and `repo/prefix`. [#20389](https://github.com/sourcegraph/sourcegraph/issues/20389)\n- Ephemeral storage requests and limits now match the default cache size to avoid Symbols pods being evicted. The symbols pod now requires 10GB of ephemeral space as a minimum to scheduled. [#2369](https://github.com/sourcegraph/deploy-sourcegraph/pull/2369)\n- Minor query syntax highlighting bug for `repo:contains` predicate. [#21038](https://github.com/sourcegraph/sourcegraph/pull/21038)\n- An issue causing diff and commit results with file filters to return invalid results. [#21039](https://github.com/sourcegraph/sourcegraph/pull/21039)\n- All databases now have the Kubernetes Quality of Service class of 'Guaranteed' which should reduce the chance of them\n being evicted during NodePressure events. [#2900](https://github.com/sourcegraph/deploy-sourcegraph/pull/2900)\n- An issue causing diff views to display without syntax highlighting [#21160](https://github.com/sourcegraph/sourcegraph/pull/21160)", "### Removed", "- The deprecated `SetRepositoryEnabled` mutation was removed. [#21044](https://github.com/sourcegraph/sourcegraph/pull/21044)", "## 3.27.5", "### Fixed", "- Fix scp style VCS url parsing. [#20799](https://github.com/sourcegraph/sourcegraph/pull/20799)", "## 3.27.4", "### Fixed", "- Fixed an issue related to Gitolite repos with `@` being prepended with a `?`. [#20297](https://github.com/sourcegraph/sourcegraph/pull/20297)\n- Add missing return from handler when DisableAutoGitUpdates is true. [#20451](https://github.com/sourcegraph/sourcegraph/pull/20451)", "## 3.27.3", "### Fixed", "- Pushing batch changes to Bitbucket Server code hosts over SSH was broken in 3.27.0, and has been fixed. [#20324](https://github.com/sourcegraph/sourcegraph/issues/20324)", "## 3.27.2", "### Fixed", "- Fixed an issue with our release tooling that was preventing all images from being tagged with the correct version.\n All sourcegraph images have the proper release version now.", "## 3.27.1", "### Fixed", "- Indexed search failed when the `master` branch needed indexing but was not the default. [#20260](https://github.com/sourcegraph/sourcegraph/pull/20260)\n- Fixed a regression that caused \"other\" code hosts urls to not be built correctly which prevents code to be cloned / updated in 3.27.0. This change will provoke some cloning errors on repositories that are already sync'ed, until the next code host sync. [#20258](https://github.com/sourcegraph/sourcegraph/pull/20258)", "## 3.27.0", "### Added", "- `count:` now supports \"all\" as value. Queries with `count:all` will return up to 999999 results. [#19756](https://github.com/sourcegraph/sourcegraph/pull/19756)\n- Credentials for Batch Changes are now validated when adding them. [#19602](https://github.com/sourcegraph/sourcegraph/pull/19602)\n- Batch Changes now ignore repositories that contain a `.batchignore` file. [#19877](https://github.com/sourcegraph/sourcegraph/pull/19877) and [src-cli#509](https://github.com/sourcegraph/src-cli/pull/509)\n- Side-by-side diff for commit visualization. [#19553](https://github.com/sourcegraph/sourcegraph/pull/19553)\n- The site configuration now supports defining batch change rollout windows, which can be used to slow or disable pushing changesets at particular times of day or days of the week. [#19796](https://github.com/sourcegraph/sourcegraph/pull/19796), [#19797](https://github.com/sourcegraph/sourcegraph/pull/19797), and [#19951](https://github.com/sourcegraph/sourcegraph/pull/19951).\n- Search functionality via built-in `contains` predicate: `repo:contains(...)`, `repo:contains.file(...)`, `repo:contains.content(...)`, repo:contains.commit.after(...)`. [#18584](https://github.com/sourcegraph/sourcegraph/issues/18584)\n- Database encryption, external service config & user auth data can now be encrypted in the database using the `encryption.keys` config. See [the docs](https://docs.sourcegraph.com/admin/encryption) for more info.\n- Repositories that gitserver fails to clone or fetch are now gradually moved to the back of the background update queue instead of remaining at the front. [#20204](https://github.com/sourcegraph/sourcegraph/pull/20204)\n- The new `disableAutoCodeHostSyncs` setting allows site admins to disable any periodic background syncing of configured code host connections. That includes syncing of repository metadata (i.e. not git updates, use `disableAutoGitUpdates` for that), permissions and batch changes changesets, but may include other data we'd sync from the code host API in the future.", "### Changed", "- Bumped the minimum supported version of Postgres from `9.6` to `12`. The upgrade procedure is mostly automated for existing deployments, but may require action if using the single-container deployment or an external database. See the [upgrade documentation](https://docs.sourcegraph.com/admin/updates) for your deployment type for detailed instructions.\n- Changesets in batch changes will now be marked as archived instead of being detached when a new batch spec that doesn't include the changesets is applied. Once they're archived users can manually detach them in the UI. [#19527](https://github.com/sourcegraph/sourcegraph/pull/19527)\n- The default replica count on `sourcegraph-frontend` and `precise-code-intel-worker` for Kubernetes has changed from `1` -> `2`.\n- Changes to code monitor trigger search queries [#19680](https://github.com/sourcegraph/sourcegraph/pull/19680)\n - A `repo:` filter is now required. This is due to an existing limitations where only 50 repositories can be searched at a time, so using a `repo:` filter makes sure the right code is being searched. Any existing code monitor without `repo:` in the trigger query will continue to work (with the limitation that not all repositories will be searched) but will require a `repo:` filter to be added when making any changes to it.\n - A `patternType` filter is no longer required. `patternType:literal` will be added to a code monitor query if not specified.\n - Added a new checklist UI to make it more intuitive to create code monitor trigger queries.\n- Deprecated the GraphQL `icon` field on `GenericSearchResultInterface`. It will be removed in a future release. [#20028](https://github.com/sourcegraph/sourcegraph/pull/20028/files)\n- Creating changesets through Batch Changes as a site-admin without configured Batch Changes credentials has been deprecated. Please configure user or global credentials before Sourcegraph 3.29 to not experience any interruptions in changeset creation. [#20143](https://github.com/sourcegraph/sourcegraph/pull/20143)\n- Deprecated the GraphQL `limitHit` field on `LineMatch`. It will be removed in a future release. [#20164](https://github.com/sourcegraph/sourcegraph/pull/20164)", "### Fixed", "- A regression caused by search onboarding tour logic to never focus input in the search bar on the homepage. Input now focuses on the homepage if the search tour isn't in effect. [#19678](https://github.com/sourcegraph/sourcegraph/pull/19678)\n- New changes of a Perforce depot will now be reflected in `master` branch after the initial clone. [#19718](https://github.com/sourcegraph/sourcegraph/pull/19718)\n- Gitolite and Other type code host connection configuration can be correctly displayed. [#19976](https://github.com/sourcegraph/sourcegraph/pull/19976)\n- Fixed a regression that caused user and code host limits to be ignored. [#20089](https://github.com/sourcegraph/sourcegraph/pull/20089)\n- A regression where incorrect query highlighting happens for certain quoted values. [#20110](https://github.com/sourcegraph/sourcegraph/pull/20110)\n- We now respect the `disableAutoGitUpdates` setting when cloning or fetching repos on demand and during cleanup tasks that may re-clone old repos. [#20194](https://github.com/sourcegraph/sourcegraph/pull/20194)", "## 3.26.3", "### Fixed", "- Setting `gitMaxCodehostRequestsPerSecond` to `0` now actually blocks all Git operations happening on the gitserver. [#19716](https://github.com/sourcegraph/sourcegraph/pull/19716)", "## 3.26.2", "### Fixed", "- Our indexed search logic now correctly handles de-duplication of search results across multiple replicas. [#19743](https://github.com/sourcegraph/sourcegraph/pull/19743)", "## 3.26.1", "### Added", "- Experimental: Sync permissions of Perforce depots through the Sourcegraph UI. To enable, use the feature flag `\"experimentalFeatures\": { \"perforce\": \"enabled\" }`. For more information, see [how to enable permissions for your Perforce depots](https://docs.sourcegraph.com/admin/repo/perforce). [#16705](https://github.com/sourcegraph/sourcegraph/issues/16705)\n- Added support for user email headers in the HTTP auth proxy. See [HTTP Auth Proxy docs](https://docs.sourcegraph.com/admin/auth#http-authentication-proxies) for more information.\n- Ignore locked and disabled GitHub Enterprise repositories. [#19500](https://github.com/sourcegraph/sourcegraph/pull/19500)\n- Remote code host git operations (such as `clone` or `ls-remote`) can now be rate limited beyond concurrency (which was already possible with `gitMaxConcurrentClones`). Set `gitMaxCodehostRequestsPerSecond` in site config to control the maximum rate of these operations per git-server instance. [#19504](https://github.com/sourcegraph/sourcegraph/pull/19504)", "### Changed", "-", "### Fixed", "- Commit search returning duplicate commits. [#19460](https://github.com/sourcegraph/sourcegraph/pull/19460)\n- Clicking the Code Monitoring tab tries to take users to a non-existent repo. [#19525](https://github.com/sourcegraph/sourcegraph/pull/19525)\n- Diff and commit search not highlighting search terms correctly for some files. [#19543](https://github.com/sourcegraph/sourcegraph/pull/19543), [#19639](https://github.com/sourcegraph/sourcegraph/pull/19639)\n- File actions weren't appearing on large window sizes in Firefox and Safari. [#19380](https://github.com/sourcegraph/sourcegraph/pull/19380)", "### Removed", "-", "## 3.26.0", "### Added", "- Searches are streamed into Sourcegraph by default. [#19300](https://github.com/sourcegraph/sourcegraph/pull/19300)\n - This gives a faster time to first result.\n - Several heuristics around result limits have been improved. You should see more consistent result counts now.\n - Can be disabled with the setting `experimentalFeatures.streamingSearch`.\n- Opsgenie API keys can now be added via an environment variable. [#18662](https://github.com/sourcegraph/sourcegraph/pull/18662)\n- It's now possible to control where code insights are displayed through the boolean settings `insights.displayLocation.homepage`, `insights.displayLocation.insightsPage` and `insights.displayLocation.directory`. [#18979](https://github.com/sourcegraph/sourcegraph/pull/18979)\n- Users can now create changesets in batch changes on repositories that are cloned using SSH. [#16888](https://github.com/sourcegraph/sourcegraph/issues/16888)\n- Syntax highlighting for Elixir, Elm, REG, Julia, Move, Nix, Puppet, VimL, Coq. [#19282](https://github.com/sourcegraph/sourcegraph/pull/19282)\n- `BUILD.in` files are now highlighted as Bazel/Starlark build files. Thanks to @jjwon0 [#19282](https://github.com/sourcegraph/sourcegraph/pull/19282)\n- `*.pyst` and `*.pyst-include` are now highlighted as Python files. Thanks to @jjwon0 [#19282](https://github.com/sourcegraph/sourcegraph/pull/19282)\n- The code monitoring feature flag is now enabled by default. [#19295](https://github.com/sourcegraph/sourcegraph/pull/19295)\n- New query field `select` enables returning only results of the desired type. See [documentation](https://docs.sourcegraph.com/code_search/reference/language#select) for details. [#19236](https://github.com/sourcegraph/sourcegraph/pull/19236)\n- Syntax highlighting for Elixer, Elm, REG, Julia, Move, Nix, Puppet, VimL thanks to @rvantonder\n- `BUILD.in` files are now highlighted as Bazel/Starlark build files. Thanks to @jjwon0\n- `*.pyst` and `*.pyst-include` are now highlighted as Python files. Thanks to @jjwon0\n- Added a `search.defaultCaseSensitive` setting to configure whether query patterns should be treated case sensitivitely by default.", "### Changed", "- Campaigns have been renamed to Batch Changes! See [#18771](https://github.com/sourcegraph/sourcegraph/issues/18771) for a detailed log on what has been renamed.\n - A new [Sourcegraph CLI](https://docs.sourcegraph.com/cli) version will use `src batch [preview|apply]` commands, while keeping the old ones working to be used with older Sourcegraph versions.\n - Old URLs in the application and in the documentation will redirect.\n - GraphQL API entities with \"campaign\" in their name have been deprecated and have new Batch Changes counterparts:\n - Deprecated GraphQL entities: `CampaignState`, `Campaign`, `CampaignSpec`, `CampaignConnection`, `CampaignsCodeHostConnection`, `CampaignsCodeHost`, `CampaignsCredential`, `CampaignDescription`\n - Deprecated GraphQL mutations: `createCampaign`, `applyCampaign`, `moveCampaign`, `closeCampaign`, `deleteCampaign`, `createCampaignSpec`, `createCampaignsCredential`, `deleteCampaignsCredential`\n - Deprecated GraphQL queries: `Org.campaigns`, `User.campaigns`, `User.campaignsCodeHosts`, `camapigns`, `campaign`\n - Site settings with `campaigns` in their name have been replaced with equivalent `batchChanges` settings.\n- A repository's `remote.origin.url` is not stored on gitserver disk anymore. Note: if you use the experimental feature `customGitFetch` your setting may need to be updated to specify the remote URL. [#18535](https://github.com/sourcegraph/sourcegraph/pull/18535)\n- Repositories and files containing spaces will now render with escaped spaces in the query bar rather than being\n quoted. [#18642](https://github.com/sourcegraph/sourcegraph/pull/18642)\n- Sourcegraph is now built with Go 1.16. [#18447](https://github.com/sourcegraph/sourcegraph/pull/18447)\n- Cursor hover information in the search query bar will now display after 150ms (previously 0ms). [#18916](https://github.com/sourcegraph/sourcegraph/pull/18916)\n- The `repo.cloned` column is deprecated in favour of `gitserver_repos.clone_status`. It will be removed in a subsequent release.\n- Precision class indicators have been improved for code intelligence results in both the hover overlay as well as the definition and references locations panel. [#18843](https://github.com/sourcegraph/sourcegraph/pull/18843)\n- Pings now contain added, aggregated campaigns usage data: aggregate counts of unique monthly users and Weekly campaign and changesets counts for campaign cohorts created in the last 12 months. [#18604](https://github.com/sourcegraph/sourcegraph/pull/18604)", "### Fixed", "- Auto complete suggestions for repositories and files containing spaces will now be automatically escaped when accepting the suggestion. [#18635](https://github.com/sourcegraph/sourcegraph/issues/18635)\n- An issue causing repository results containing spaces to not be clickable in some cases. [#18668](https://github.com/sourcegraph/sourcegraph/pull/18668)\n- Closing a batch change now correctly closes the entailed changesets, when requested by the user. [#18957](https://github.com/sourcegraph/sourcegraph/pull/18957)\n- TypesScript highlighting bug. [#15930](https://github.com/sourcegraph/sourcegraph/issues/15930)\n- The number of shards is now reported accurately in Site Admin > Repository Status > Settings > Indexing. [#19265](https://github.com/sourcegraph/sourcegraph/pull/19265)", "### Removed", "- Removed the deprecated GraphQL fields `SearchResults.repositoriesSearched` and `SearchResults.indexedRepositoriesSearched`.\n- Removed the deprecated search field `max`\n- Removed the `experimentalFeatures.showBadgeAttachments` setting", "## 3.25.2", "### Fixed", "- A security vulnerability with in the authentication workflow has been fixed. [#18686](https://github.com/sourcegraph/sourcegraph/pull/18686)", "## 3.25.1", "### Added", "- Experimental: Sync Perforce depots directly through the Sourcegraph UI. To enable, use the feature flag `\"experimentalFeatures\": { \"perforce\": \"enabled\" }`. For more information, see [how to add your Perforce depots](https://docs.sourcegraph.com/admin/repo/perforce). [#16703](https://github.com/sourcegraph/sourcegraph/issues/16703)", "## 3.25.0", "**IMPORTANT** Sourcegraph now uses Go 1.15. This may break AWS RDS database connections with older x509 certificates. Please follow the Amazon [docs](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL-certificate-rotation.html) to rotate your certificate.", "### Added", "- New site config option `\"log\": { \"sentry\": { \"backendDSN\": \"<REDACTED>\" } }` to use a separate Sentry project for backend errors. [#17363](https://github.com/sourcegraph/sourcegraph/pull/17363)\n- Structural search now supports searching indexed branches other than default. [#17726](https://github.com/sourcegraph/sourcegraph/pull/17726)\n- Structural search now supports searching unindexed revisions. [#17967](https://github.com/sourcegraph/sourcegraph/pull/17967)\n- New site config option `\"allowSignup\"` for SAML authentication to determine if automatically create new users is allowed. [#17989](https://github.com/sourcegraph/sourcegraph/pull/17989)\n- Experimental: The webapp can now stream search results to the client, improving search performance. To enable it, add `{ \"experimentalFeatures\": { \"searchStreaming\": true } }` in user settings. [#16097](https://github.com/sourcegraph/sourcegraph/pull/16097)\n- New product research sign-up page. This can be accessed by all users in their user settings. [#17945](https://github.com/sourcegraph/sourcegraph/pull/17945)\n- New site config option `productResearchPage.enabled` to disable access to the product research sign-up page. [#17945](https://github.com/sourcegraph/sourcegraph/pull/17945)\n- Pings now contain Sourcegraph extension activation statistics. [#16421](https://github.com/sourcegraph/sourcegraph/pull/16421)\n- Pings now contain aggregate Sourcegraph extension activation statistics: the number of users and number of activations per (public) extension per week, and the number of total extension users per week and average extensions activated per user. [#16421](https://github.com/sourcegraph/sourcegraph/pull/16421)\n- Pings now contain aggregate code insights usage data: total insight views, interactions, edits, creations, removals, and counts of unique users that view and create insights. [#16421](https://github.com/sourcegraph/sourcegraph/pull/17805)\n- When previewing a campaign spec, changesets can be filtered by current state or the action(s) to be performed. [#16960](https://github.com/sourcegraph/sourcegraph/issues/16960)", "### Changed", "- Alert solutions links included in [monitoring alerts](https://docs.sourcegraph.com/admin/observability/alerting) now link to the relevant documentation version. [#17828](https://github.com/sourcegraph/sourcegraph/pull/17828)\n- Secrets (such as access tokens and passwords) will now appear as REDACTED when editing external service config, and in graphql API responses. [#17261](https://github.com/sourcegraph/sourcegraph/issues/17261)\n- Sourcegraph is now built with Go 1.15\n - Go `1.15` introduced changes to SSL/TLS connection validation which requires certificates to include a `SAN`. This field was not included in older certificates and clients relied on the `CN` field. You might see an error like `x509: certificate relies on legacy Common Name field`. We recommend that customers using Sourcegraph with an external database and connecting to it using SSL/TLS check whether the certificate is up to date.\n - RDS Customers please reference [AWS' documentation on updating the SSL/TLS certificate](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL-certificate-rotation.html).\n- Search results on `.rs` files now recommend `lang:rust` instead of `lang:renderscript` as a filter. [#18316](https://github.com/sourcegraph/sourcegraph/pull/18316)\n- Campaigns users creating Personal Access Tokens on GitHub are now asked to request the `user:email` scope in addition to the [previous scopes](https://docs.sourcegraph.com/@3.24/admin/external_service/github#github-api-token-and-access). This will be used in a future Sourcegraph release to display more fine-grained information on the progress of pull requests. [#17555](https://github.com/sourcegraph/sourcegraph/issues/17555)", "### Fixed", "- Fixes an issue that prevented the hard deletion of a user if they had saved searches. [#17461](https://github.com/sourcegraph/sourcegraph/pull/17461)\n- Fixes an issue that caused some missing results for `type:commit` when a pattern was used instead of the `message` field. [#17490](https://github.com/sourcegraph/sourcegraph/pull/17490#issuecomment-764004758)\n- Fixes an issue where cAdvisor-based alerts would not fire correctly for services with multiple replicas. [#17600](https://github.com/sourcegraph/sourcegraph/pull/17600)\n- Significantly improved performance of structural search on monorepo deployments [#17846](https://github.com/sourcegraph/sourcegraph/pull/17846)\n- Fixes an issue where upgrades on Kubernetes may fail due to null environment variable lists in deployment manifests [#1781](https://github.com/sourcegraph/deploy-sourcegraph/pull/1781)\n- Fixes an issue where counts on search filters were inaccurate. [#18158](https://github.com/sourcegraph/sourcegraph/pull/18158)\n- Fixes services with emptyDir volumes being evicted from nodes. [#1852](https://github.com/sourcegraph/deploy-sourcegraph/pull/1852)", "### Removed", "- Removed the `search.migrateParser` setting. As of 3.20 and onward, a new parser processes search queries by default. Previously, `search.migrateParser` was available to enable the legacy parser. Enabling/disabling this setting now no longer has any effect. [#17344](https://github.com/sourcegraph/sourcegraph/pull/17344)", "## 3.24.1", "### Fixed", "- Fixes an issue that SAML is not able to proceed with the error `Expected Enveloped and C14N transforms`. [#13032](https://github.com/sourcegraph/sourcegraph/issues/13032)", "## 3.24.0", "### Added", "- Panels in the [Sourcegraph monitoring dashboards](https://docs.sourcegraph.com/admin/observability/metrics#grafana) now:\n - include links to relevant alerts documentation and the new [monitoring dashboards reference](https://docs.sourcegraph.com/admin/observability/dashboards). [#16939](https://github.com/sourcegraph/sourcegraph/pull/16939)\n - include alert events and version changes annotations that can be enabled from the top of each service dashboard. [#17198](https://github.com/sourcegraph/sourcegraph/pull/17198)\n- Suggested filters in the search results page can now be scrolled. [#17097](https://github.com/sourcegraph/sourcegraph/pull/17097)\n- Structural search queries can now be used in saved searches by adding `patternType:structural`. [#17265](https://github.com/sourcegraph/sourcegraph/pull/17265)", "### Changed", "- Dashboard links included in [monitoring alerts](https://docs.sourcegraph.com/admin/observability/alerting) now:\n - link directly to the relevant Grafana panel, instead of just the service dashboard. [#17014](https://github.com/sourcegraph/sourcegraph/pull/17014)\n - link to a time frame relevant to the alert, instead of just the past few hours. [#17034](https://github.com/sourcegraph/sourcegraph/pull/17034)\n- Added `serviceKind` field of the `ExternalServiceKind` type to `Repository.externalURLs` GraphQL API, `serviceType` field is deprecated and will be removed in the future releases. [#14979](https://github.com/sourcegraph/sourcegraph/issues/14979)\n- Deprecated the GraphQL fields `SearchResults.repositoriesSearched` and `SearchResults.indexedRepositoriesSearched`.\n- The minimum Kubernetes version required to use the [Kubernetes deployment option](https://docs.sourcegraph.com/admin/install/kubernetes) is now [v1.15 (released June 2019)](https://kubernetes.io/blog/2019/06/19/kubernetes-1-15-release-announcement/).", "### Fixed", "- Imported changesets acquired an extra button to download the \"generated diff\", which did nothing, since imported changesets don't have a generated diff. This button has been removed. [#16778](https://github.com/sourcegraph/sourcegraph/issues/16778)\n- Quoted global filter values (case, patterntype) are now properly extracted and set in URL parameters. [#16186](https://github.com/sourcegraph/sourcegraph/issues/16186)\n- The endpoint for \"Open in Sourcegraph\" functionality in editor extensions now uses code host connection information to resolve the repository, which makes it more correct and respect the `repositoryPathPattern` setting. [#16846](https://github.com/sourcegraph/sourcegraph/pull/16846)\n- Fixed an issue that prevented search expressions of the form `repo:foo (rev:a or rev:b)` from evaluating all revisions [#16873](https://github.com/sourcegraph/sourcegraph/pull/16873)\n- Updated language detection library. Includes language detection for `lang:starlark`. [#16900](https://github.com/sourcegraph/sourcegraph/pull/16900)\n- Fixed retrieving status for indexed tags and deduplicated main branches in the indexing settings page. [#13787](https://github.com/sourcegraph/sourcegraph/issues/13787)\n- Specifying a ref that doesn't exist would show an alert, but still return results [#15576](https://github.com/sourcegraph/sourcegraph/issues/15576)\n- Fixed search highlighting the wrong line. [#10468](https://github.com/sourcegraph/sourcegraph/issues/10468)\n- Fixed an issue where searches of the form `foo type:file` returned results of type `path` too. [#17076](https://github.com/sourcegraph/sourcegraph/issues/17076)\n- Fixed queries like `(type:commit or type:diff)` so that if the query matches both the commit message and the diff, both are returned as results. [#16899](https://github.com/sourcegraph/sourcegraph/issues/16899)\n- Fixed container monitoring and provisioning dashboard panels not displaying metrics in certain deployment types and environments. If you continue to have issues with these panels not displaying any metrics after upgrading, please [open an issue](https://github.com/sourcegraph/sourcegraph/issues/new).\n- Fixed a nonexistent field in site configuration being marked as \"required\" when configuring PagerDuty alert notifications. [#17277](https://github.com/sourcegraph/sourcegraph/pull/17277)\n- Fixed cases of incorrect highlighting for symbol definitions in the definitions panel. [#17258](https://github.com/sourcegraph/sourcegraph/pull/17258)\n- Fixed a Cross-Site Scripting vulnerability where quick links created on the homepage were not sanitized and allowed arbitrary JavaScript execution. [#17099](https://github.com/sourcegraph/sourcegraph/pull/17099)", "### Removed", "- Interactive mode has now been removed. [#16868](https://github.com/sourcegraph/sourcegraph/pull/16868).", "## 3.23.0", "### Added", "- Password reset link expiration can be customized via `auth.passwordResetLinkExpiry` in the site config. [#13999](https://github.com/sourcegraph/sourcegraph/issues/13999)\n- Campaign steps may now include environment variables from outside of the campaign spec using [array syntax](http://docs.sourcegraph.com/campaigns/references/campaign_spec_yaml_reference#environment-array). [#15822](https://github.com/sourcegraph/sourcegraph/issues/15822)\n- The total size of all Git repositories and the lines of code for indexed branches are displayed in the site admin overview. [#15125](https://github.com/sourcegraph/sourcegraph/issues/15125)\n- Extensions can now add decorations to files on the sidebar tree view and tree page through the experimental `FileDecoration` API. [#15833](https://github.com/sourcegraph/sourcegraph/pull/15833)\n- Extensions can now easily query the Sourcegraph GraphQL API through a dedicated API method. [#15566](https://github.com/sourcegraph/sourcegraph/pull/15566)\n- Individual changesets can now be downloaded as a diff. [#16098](https://github.com/sourcegraph/sourcegraph/issues/16098)\n- The campaigns preview page is much more detailed now, especially when updating existing campaigns. [#16240](https://github.com/sourcegraph/sourcegraph/pull/16240)\n- When a newer version of a campaign spec is uploaded, a message is now displayed when viewing the campaign or an outdated campaign spec. [#14532](https://github.com/sourcegraph/sourcegraph/issues/14532)\n- Changesets in a campaign can now be searched by title and repository name. [#15781](https://github.com/sourcegraph/sourcegraph/issues/15781)\n- Experimental: [`transformChanges` in campaign specs](https://docs.sourcegraph.com/campaigns/references/campaign_spec_yaml_reference#transformchanges) is now available as a feature preview to allow users to create multiple changesets in a single repository. [#16235](https://github.com/sourcegraph/sourcegraph/pull/16235)\n- The `gitUpdateInterval` site setting was added to allow custom git update intervals based on repository names. [#16765](https://github.com/sourcegraph/sourcegraph/pull/16765)\n- Various additions to syntax highlighting and hover tooltips in the search query bar (e.g., regular expressions). Can be disabled with `{ \"experimentalFeatures\": { \"enableSmartQuery\": false } }` in case of unlikely adverse effects. [#16742](https://github.com/sourcegraph/sourcegraph/pull/16742)\n- Search queries may now scope subexpressions across repositories and files, and also allow greater freedom for combining search filters. See the updated documentation on [search subexpressions](https://docs.sourcegraph.com/code_search/tutorials/search_subexpressions) to learn more. [#16866](https://github.com/sourcegraph/sourcegraph/pull/16866)", "### Changed", "- Search indexer tuned to wait longer before assuming a deadlock has occurred. Previously if the indexserver had many cores (40+) and indexed a monorepo it could give up. [#16110](https://github.com/sourcegraph/sourcegraph/pull/16110)\n- The total size of all Git repositories and the lines of code for indexed branches will be sent back in pings as part of critical telemetry. [#16188](https://github.com/sourcegraph/sourcegraph/pull/16188)\n- The `gitserver` container now has a dependency on Postgres. This does not require any additional configuration unless access to Postgres requires a sidecar proxy / firewall rules. [#16121](https://github.com/sourcegraph/sourcegraph/pull/16121)\n- Licensing is now enforced for campaigns: creating a campaign with more than five changesets requires a valid license. Please [contact Sourcegraph with any licensing questions](https://about.sourcegraph.com/contact/sales/). [#15715](https://github.com/sourcegraph/sourcegraph/issues/15715)", "### Fixed", "- Syntax highlighting on files with mixed extension case (e.g. `.CPP` vs `.cpp`) now works as expected. [#11327](https://github.com/sourcegraph/sourcegraph/issues/11327)\n- After applying a campaign, some GitLab MRs might have had outdated state shown in the UI until the next sync with the code host. [#16100](https://github.com/sourcegraph/sourcegraph/pull/16100)\n- The web app no longer sends stale text document content to extensions. [#14965](https://github.com/sourcegraph/sourcegraph/issues/14965)\n- The blob viewer now supports multiple decorations per line as intended. [#15063](https://github.com/sourcegraph/sourcegraph/issues/15063)\n- Repositories with plus signs in their name can now be navigated to as expected. [#15079](https://github.com/sourcegraph/sourcegraph/issues/15079)", "### Removed", "-", "## 3.22.1", "### Changed", "- Reduced memory and CPU required for updating the code intelligence commit graph [#16517](https://github.com/sourcegraph/sourcegraph/pull/16517)", "## 3.22.0", "### Added", "- GraphQL and TOML syntax highlighting is now back (special thanks to @rvantonder) [#13935](https://github.com/sourcegraph/sourcegraph/issues/13935)\n- Zig and DreamMaker syntax highlighting.\n- Campaigns now support publishing GitHub draft PRs and GitLab WIP MRs. [#7998](https://github.com/sourcegraph/sourcegraph/issues/7998)\n- `indexed-searcher`'s watchdog can be configured and has additional instrumentation. This is useful when diagnosing [zoekt-webserver is restarting due to watchdog](https://docs.sourcegraph.com/admin/observability/troubleshooting#scenario-zoekt-webserver-is-restarting-due-to-watchdog). [#15148](https://github.com/sourcegraph/sourcegraph/pull/15148)\n- Pings now contain Redis & Postgres server versions. [14405](https://github.com/sourcegraph/sourcegraph/14405)\n- Aggregated usage data of the search onboarding tour is now included in pings. The data tracked are: total number of views of the onboarding tour, total number of views of each step in the onboarding tour, total number of tours closed. [#15113](https://github.com/sourcegraph/sourcegraph/pull/15113)\n- Users can now specify credentials for code hosts to enable campaigns for non site-admin users. [#15506](https://github.com/sourcegraph/sourcegraph/pull/15506)\n- A `campaigns.restrictToAdmins` site configuration option has been added to prevent non site-admin users from using campaigns. [#15785](https://github.com/sourcegraph/sourcegraph/pull/15785)\n- Number of page views on campaign apply page, page views on campaign details page after create/update, closed campaigns, created campaign specs and changesets specs and the sum of changeset diff stats will be sent back in pings. [#15279](https://github.com/sourcegraph/sourcegraph/pull/15279)\n- Users can now explicitly set their primary email address. [#15683](https://github.com/sourcegraph/sourcegraph/pull/15683)\n- \"[Why code search is still needed for monorepos](https://docs.sourcegraph.com/adopt/code_search_in_monorepos)\" doc page", "### Changed", "- Improved contrast / visibility in comment syntax highlighting. [#14546](https://github.com/sourcegraph/sourcegraph/issues/14546)\n- Campaigns are no longer in beta. [#14900](https://github.com/sourcegraph/sourcegraph/pull/14900)\n- Campaigns now have a fancy new icon. [#14740](https://github.com/sourcegraph/sourcegraph/pull/14740)\n- Search queries with an unbalanced closing paren `)` are now invalid, since this likely indicates an error. Previously, patterns with dangling `)` were valid in some cases. Note that patterns with dangling `)` can still be searched, but should be quoted via `content:\"foo)\"`. [#15042](https://github.com/sourcegraph/sourcegraph/pull/15042)\n- Extension providers can now return AsyncIterables, enabling dynamic provider results without dependencies. [#15042](https://github.com/sourcegraph/sourcegraph/issues/15061)\n- Deprecated the `\"email.smtp\": { \"disableTLS\" }` site config option, this field has been replaced by `\"email.smtp\": { \"noVerifyTLS\" }`. [#15682](https://github.com/sourcegraph/sourcegraph/pull/15682)", "### Fixed", "- The `file:` added to the search field when navigating to a tree or file view will now behave correctly when the file path contains spaces. [#12296](https://github.com/sourcegraph/sourcegraph/issues/12296)\n- OAuth login now respects site configuration `experimentalFeatures: { \"tls.external\": {...} }` for custom certificates and skipping TLS verify. [#14144](https://github.com/sourcegraph/sourcegraph/issues/14144)\n- If the `HEAD` file in a cloned repo is absent or truncated, background cleanup activities will use a best-effort default to remedy the situation. [#14962](https://github.com/sourcegraph/sourcegraph/pull/14962)\n- Search input will always show suggestions. Previously we only showed suggestions for letters and some special characters. [#14982](https://github.com/sourcegraph/sourcegraph/pull/14982)\n- Fixed an issue where `not` keywords were not recognized inside expression groups, and treated incorrectly as patterns. [#15139](https://github.com/sourcegraph/sourcegraph/pull/15139)\n- Fixed an issue where hover pop-ups would not show on the first character of a valid hover range in search queries. [#15410](https://github.com/sourcegraph/sourcegraph/pull/15410)\n- Fixed an issue where submodules configured with a relative URL resulted in non-functional hyperlinks in the file tree UI. [#15286](https://github.com/sourcegraph/sourcegraph/issues/15286)\n- Pushing commits to public GitLab repositories with campaigns now works, since we use the configured token even if the repository is public. [#15536](https://github.com/sourcegraph/sourcegraph/pull/15536)\n- `.kts` is now highlighted properly as Kotlin code, fixed various other issues in Kotlin syntax highlighting.\n- Fixed an issue where the value of `content:` was treated literally when the regular expression toggle is active. [#15639](https://github.com/sourcegraph/sourcegraph/pull/15639)\n- Fixed an issue where non-site admins were prohibited from updating some of their other personal metadata when `auth.enableUsernameChanges` was `false`. [#15663](https://github.com/sourcegraph/sourcegraph/issues/15663)\n- Fixed the `url` fields of repositories and trees in GraphQL returning URLs that were not %-encoded (e.g. when the repository name contained spaces). [#15667](https://github.com/sourcegraph/sourcegraph/issues/15667)\n- Fixed \"Find references\" showing errors in the references panel in place of the syntax-highlighted code for repositories with spaces in their name. [#15618](https://github.com/sourcegraph/sourcegraph/issues/15618)\n- Fixed an issue where specifying the `repohasfile` filter did not return results as expected unless `repo` was specified. [#15894](https://github.com/sourcegraph/sourcegraph/pull/15894)\n- Fixed an issue causing user input in the search query field to be erased in some cases. [#15921](https://github.com/sourcegraph/sourcegraph/issues/15921).", "### Removed", "-", "## 3.21.2", ":warning: WARNING :warning: For users of single-image Sourcegraph instance, please delete the secret key file `/var/lib/sourcegraph/token` inside the container before attempting to upgrade to 3.21.x.", "### Fixed", "- Fix externalURLs alert logic [#14980](https://github.com/sourcegraph/sourcegraph/pull/14980)", "## 3.21.1", ":warning: WARNING :warning: For users of single-image Sourcegraph instance, please delete the secret key file `/var/lib/sourcegraph/token` inside the container before attempting to upgrade to 3.21.x.", "### Fixed", "- Fix alerting for native integration condition [#14775](https://github.com/sourcegraph/sourcegraph/pull/14775)\n- Fix query with large repo count hanging [#14944](https://github.com/sourcegraph/sourcegraph/pull/14944)\n- Fix server upgrade where codeintel database does not exist [#14953](https://github.com/sourcegraph/sourcegraph/pull/14953)\n- CVE-2019-18218 in postgres docker image [#14954](https://github.com/sourcegraph/sourcegraph/pull/14954)\n- Fix an issue where .git/HEAD in invalid [#14962](https://github.com/sourcegraph/sourcegraph/pull/14962)\n- Repository syncing will not happen more frequently than the repoListUpdateInterval config value [#14901](https://github.com/sourcegraph/sourcegraph/pull/14901) [#14983](https://github.com/sourcegraph/sourcegraph/pull/14983)", "## 3.21.0", ":warning: WARNING :warning: For users of single-image Sourcegraph instance, please delete the secret key file `/var/lib/sourcegraph/token` inside the container before attempting to upgrade to 3.21.x.", "### Added", "- The new GraphQL API query field `namespaceByName(name: String!)` makes it easier to look up the user or organization with the given name. Previously callers needed to try looking up the user and organization separately.\n- Changesets created by campaigns will now include a link back to the campaign in their body text. [#14033](https://github.com/sourcegraph/sourcegraph/issues/14033)\n- Users can now preview commits that are going to be created in their repositories in the campaign preview UI. [#14181](https://github.com/sourcegraph/sourcegraph/pull/14181)\n- If emails are configured, the user will be sent an email when important account information is changed. This currently encompasses changing/resetting the password, adding/removing emails, and adding/removing access tokens. [#14320](https://github.com/sourcegraph/sourcegraph/pull/14320)\n- A subset of changesets can now be published by setting the `published` flag in campaign specs [to an array](https://docs.sourcegraph.com/@main/campaigns/campaign_spec_yaml_reference#publishing-only-specific-changesets), which allows only specific changesets within a campaign to be published based on the repository name. [#13476](https://github.com/sourcegraph/sourcegraph/pull/13476)\n- Homepage panels are now enabled by default. [#14287](https://github.com/sourcegraph/sourcegraph/issues/14287)\n- The most recent ping data is now available to site admins via the Site-admin > Pings page. [#13956](https://github.com/sourcegraph/sourcegraph/issues/13956)\n- Homepage panel engagement metrics will be sent back in pings. [#14589](https://github.com/sourcegraph/sourcegraph/pull/14589)\n- Homepage now has a footer with links to different extensibility features. [#14638](https://github.com/sourcegraph/sourcegraph/issues/14638)\n- Added an onboarding tour of Sourcegraph for new users. It can be enabled in user settings with `experimentalFeatures.showOnboardingTour` [#14636](https://github.com/sourcegraph/sourcegraph/pull/14636)\n- Added an onboarding tour of Sourcegraph for new users. [#14636](https://github.com/sourcegraph/sourcegraph/pull/14636)\n- Repository GraphQL queries now support an `after` parameter that permits cursor-based pagination. [#13715](https://github.com/sourcegraph/sourcegraph/issues/13715)\n- Searches in the Recent Searches panel and other places are now syntax highlighted. [#14443](https://github.com/sourcegraph/sourcegraph/issues/14443)", "### Changed", "- Interactive search mode is now disabled by default because the new plain text search input is smarter. To reenable it, add `{ \"experimentalFeatures\": { \"splitSearchModes\": true } }` in user settings.\n- The extension registry has been redesigned to make it easier to find non-default Sourcegraph extensions.\n- Tokens and similar sensitive information included in the userinfo portion of remote repository URLs will no longer be visible on the Mirroring settings page. [#14153](https://github.com/sourcegraph/sourcegraph/pull/14153)\n- The sign in and sign up forms have been redesigned with better input validation.\n- Kubernetes admins mounting [configuration files](https://docs.sourcegraph.com/admin/config/advanced_config_file#kubernetes-configmap) are encouraged to change how the ConfigMap is mounted. See the new documentation. Previously our documentation suggested using subPath. However, this lead to Kubernetes not automatically updating the files on configuration change. [#14297](https://github.com/sourcegraph/sourcegraph/pull/14297)\n- The precise code intel bundle manager will now expire any converted LSIF data that is older than `PRECISE_CODE_INTEL_MAX_DATA_AGE` (30 days by default) that is also not visible from the tip of the default branch.\n- `SRC_LOG_LEVEL=warn` is now the default in Docker Compose and Kubernetes deployments, reducing the amount of uninformative log spam. [#14458](https://github.com/sourcegraph/sourcegraph/pull/14458)\n- Permissions data that were stored in deprecated binary format are abandoned. Downgrade from 3.21 to 3.20 is OK, but to 3.19 or prior versions might experience missing/incomplete state of permissions for a short period of time. [#13740](https://github.com/sourcegraph/sourcegraph/issues/13740)\n- The query builder page is now disabled by default. To reenable it, add `{ \"experimentalFeatures\": { \"showQueryBuilder\": true } }` in user settings.\n- The GraphQL `updateUser` mutation now returns the updated user (instead of an empty response).", "### Fixed", "- Git clone URLs now validate their format correctly. [#14313](https://github.com/sourcegraph/sourcegraph/pull/14313)\n- Usernames set in Slack `observability.alerts` now apply correctly. [#14079](https://github.com/sourcegraph/sourcegraph/pull/14079)\n- Path segments in breadcrumbs get truncated correctly again on small screen sizes instead of inflating the header bar. [#14097](https://github.com/sourcegraph/sourcegraph/pull/14097)\n- GitLab pipelines are now parsed correctly and show their current status in campaign changesets. [#14129](https://github.com/sourcegraph/sourcegraph/pull/14129)\n- Fixed an issue where specifying any repogroups would effectively search all repositories for all repogroups. [#14190](https://github.com/sourcegraph/sourcegraph/pull/14190)\n- Changesets that were previously closed after being detached from a campaign are now reopened when being reattached. [#14099](https://github.com/sourcegraph/sourcegraph/pull/14099)\n- Previously large files that match the site configuration [search.largeFiles](https://docs.sourcegraph.com/admin/config/site_config#search-largeFiles) would not be indexed if they contained a large number of unique trigrams. We now index those files as well. Note: files matching the glob still need to be valid utf-8. [#12443](https://github.com/sourcegraph/sourcegraph/issues/12443)\n- Git tags without a `creatordate` value will no longer break tag search within a repository. [#5453](https://github.com/sourcegraph/sourcegraph/issues/5453)\n- Campaigns pages now work properly on small viewports. [#14292](https://github.com/sourcegraph/sourcegraph/pull/14292)\n- Fix an issue with viewing repositories that have spaces in the repository name [#2867](https://github.com/sourcegraph/sourcegraph/issues/2867)", "### Removed", "- Syntax highlighting for GraphQL, INI, TOML, and Perforce files has been removed [due to incompatible/absent licenses](https://github.com/sourcegraph/sourcegraph/issues/13933). We plan to [add it back in the future](https://github.com/sourcegraph/sourcegraph/issues?q=is%3Aissue+is%3Aopen+add+syntax+highlighting+for+develop+a+).\n- Search scope pages (`/search/scope/:id`) were removed.\n- User-defined search scopes are no longer shown below the search bar on the homepage. Use the [`quicklinks`](https://docs.sourcegraph.com/user/personalization/quick_links) setting instead to display links there.\n- The explore page (`/explore`) was removed.\n- The sign out page was removed.\n- The unused GraphQL types `DiffSearchResult` and `DeploymentConfiguration` were removed.\n- The deprecated GraphQL mutation `updateAllMirrorRepositories`.\n- The deprecated GraphQL field `Site.noRepositoriesEnabled`.\n- Total counts of users by product area have been removed from pings.\n- Aggregate daily, weekly, and monthly latencies (in ms) of code intelligence events (e.g., hover tooltips) have been removed from pings.", "## 3.20.1", "### Fixed", "- gomod: rollback go-diff to v0.5.3 (v0.6.0 causes panic in certain cases) [#13973](https://github.com/sourcegraph/sourcegraph/pull/13973).\n- Fixed an issue causing the scoped query in the search field to be erased when viewing files. [#13954](https://github.com/sourcegraph/sourcegraph/pull/13954).", "## 3.20.0", "### Added", "- Site admins can now force a specific user to re-authenticate on their next request or visit. [#13647](https://github.com/sourcegraph/sourcegraph/pull/13647)\n- Sourcegraph now watches its [configuration files](https://docs.sourcegraph.com/admin/config/advanced_config_file) (when using external files) and automatically applies the changes to Sourcegraph's configuration when they change. For example, this allows Sourcegraph to detect when a Kubernetes ConfigMap changes. [#13646](https://github.com/sourcegraph/sourcegraph/pull/13646)\n- To define repository groups (`search.repositoryGroups` in global, org, or user settings), you can now specify regular expressions in addition to single repository names. [#13730](https://github.com/sourcegraph/sourcegraph/pull/13730)\n- The new site configuration property `search.limits` configures the maximum search timeout and the maximum number of repositories to search for various types of searches. [#13448](https://github.com/sourcegraph/sourcegraph/pull/13448)\n- Files and directories can now be excluded from search by adding the file `.sourcegraph/ignore` to the root directory of a repository. Each line in the _ignore_ file is interpreted as a globbing pattern. [#13690](https://github.com/sourcegraph/sourcegraph/pull/13690)\n- Structural search syntax now allows regular expressions in patterns. Also, `...` can now be used in place of `:[_]`. See the [documentation](https://docs.sourcegraph.com/@main/code_search/reference/structural) for example syntax. [#13809](https://github.com/sourcegraph/sourcegraph/pull/13809)\n- The total size of all Git repositories and the lines of code for indexed branches will be sent back in pings. [#13764](https://github.com/sourcegraph/sourcegraph/pull/13764)\n- Experimental: A new homepage UI for Sourcegraph Server shows the user their recent searches, repositories, files, and saved searches. It can be enabled with `experimentalFeatures.showEnterpriseHomePanels`. [#13407](https://github.com/sourcegraph/sourcegraph/issues/13407)", "### Changed", "- Campaigns are enabled by default for all users. Site admins may view and create campaigns; everyone else may only view campaigns. The new site configuration property `campaigns.enabled` can be used to disable campaigns for all users. The properties `campaigns.readAccess`, `automation.readAccess.enabled`, and `\"experimentalFeatures\": { \"automation\": \"enabled\" }}` are deprecated and no longer have any effect.\n- Diff and commit searches are limited to 10,000 repositories (if `before:` or `after:` filters are used), or 50 repositories (if no time filters are used). You can configure this limit in the site configuration property `search.limits`. [#13386](https://github.com/sourcegraph/sourcegraph/pull/13386)\n- The site configuration `maxReposToSearch` has been deprecated in favor of the property `maxRepos` on `search.limits`. [#13439](https://github.com/sourcegraph/sourcegraph/pull/13439)\n- Search queries are now processed by a new parser that will always be enabled going forward. There should be no material difference in behavior. In case of adverse effects, the previous parser can be reenabled by setting `\"search.migrateParser\": false` in settings. [#13435](https://github.com/sourcegraph/sourcegraph/pull/13435)\n- It is now possible to search for file content that excludes a term using the `NOT` operator. [#12412](https://github.com/sourcegraph/sourcegraph/pull/12412)\n- `NOT` is available as an alternative syntax of `-` on supported keywords `repo`, `file`, `content`, `lang`, and `repohasfile`. [#12412](https://github.com/sourcegraph/sourcegraph/pull/12412)\n- Negated content search is now also supported for unindexed repositories. Previously it was only supported for indexed repositories [#13359](https://github.com/sourcegraph/sourcegraph/pull/13359).\n- The experimental feature flag `andOrQuery` is deprecated. [#13435](https://github.com/sourcegraph/sourcegraph/pull/13435)\n- After a user's password changes, they will be signed out on all devices and must sign in again. [#13647](https://github.com/sourcegraph/sourcegraph/pull/13647)\n- `rev:` is available as alternative syntax of `@` for searching revisions instead of the default branch [#13133](https://github.com/sourcegraph/sourcegraph/pull/13133)\n- Campaign URLs have changed to use the campaign name instead of an opaque ID. The old URLs no longer work. [#13368](https://github.com/sourcegraph/sourcegraph/pull/13368)\n- A new `external_service_repos` join table was added. The migration required to make this change may take a few minutes.", "### Fixed", "- User satisfaction/NPS surveys will now correctly provide a range from 0–10, rather than 0–9. [#13163](https://github.com/sourcegraph/sourcegraph/pull/13163)\n- Fixed a bug where we returned repositories with invalid revisions in the search results. Now, if a user specifies an invalid revision, we show an alert. [#13271](https://github.com/sourcegraph/sourcegraph/pull/13271)\n- Previously it wasn't possible to search for certain patterns containing `:` because they would not be considered valid filters. We made these checks less strict. [#10920](https://github.com/sourcegraph/sourcegraph/pull/10920)\n- When a user signs out of their account, all of their sessions will be invalidated, not just the session where they signed out. [#13647](https://github.com/sourcegraph/sourcegraph/pull/13647)\n- URL information will no longer be leaked by the HTTP referer header. This prevents the user's password reset code from being leaked. [#13804](https://github.com/sourcegraph/sourcegraph/pull/13804)\n- GitLab OAuth2 user authentication now respects `tls.external` site setting. [#13814](https://github.com/sourcegraph/sourcegraph/pull/13814)", "### Removed", "- The smartSearchField feature is now always enabled. The `experimentalFeatures.smartSearchField` settings option has been removed.", "## 3.19.2", "### Fixed", "- search: always limit commit and diff to less than 10,000 repos [a97f81b0f7](https://github.com/sourcegraph/sourcegraph/commit/a97f81b0f79535253bd7eae6c30d5c91d48da5ca)\n- search: configurable limits on commit/diff search [1c22d8ce1](https://github.com/sourcegraph/sourcegraph/commit/1c22d8ce13c149b3fa3a7a26f8cb96adc89fc556)\n- search: add site configuration for maxTimeout [d8d61b43c0f](https://github.com/sourcegraph/sourcegraph/commit/d8d61b43c0f0d229d46236f2f128ca0f93455172)", "## 3.19.1", "### Fixed", "- migrations: revert migration causing deadlocks in some deployments [#13194](https://github.com/sourcegraph/sourcegraph/pull/13194)", "## 3.19.0", "### Added", "- Emails can be now be sent to SMTP servers with self-signed certificates, using `email.smtp.disableTLS`. [#12243](https://github.com/sourcegraph/sourcegraph/pull/12243)\n- Saved search emails now include a link to the user's saved searches page. [#11651](https://github.com/sourcegraph/sourcegraph/pull/11651)\n- Campaigns can now be synced using GitLab webhooks. [#12139](https://github.com/sourcegraph/sourcegraph/pull/12139)\n- Configured `observability.alerts` can now be tested using a GraphQL endpoint, `triggerObservabilityTestAlert`. [#12532](https://github.com/sourcegraph/sourcegraph/pull/12532)\n- The Sourcegraph CLI can now serve local repositories for Sourcegraph to clone. This was previously in a command called `src-expose`. See [serving local repositories](https://docs.sourcegraph.com/admin/external_service/src_serve_git) in our documentation to find out more. [#12363](https://github.com/sourcegraph/sourcegraph/issues/12363)\n- The count of retained, churned, resurrected, new and deleted users will be sent back in pings. [#12136](https://github.com/sourcegraph/sourcegraph/pull/12136)\n- Saved search usage will be sent back in pings. [#12956](https://github.com/sourcegraph/sourcegraph/pull/12956)\n- Any request with `?trace=1` as a URL query parameter will enable Jaeger tracing (if Jaeger is enabled). [#12291](https://github.com/sourcegraph/sourcegraph/pull/12291)\n- Password reset emails will now be automatically sent to users created by a site admin if email sending is configured and password reset is enabled. Previously, site admins needed to manually send the user this password reset link. [#12803](https://github.com/sourcegraph/sourcegraph/pull/12803)\n- Syntax highlighting for `and` and `or` search operators. [#12694](https://github.com/sourcegraph/sourcegraph/pull/12694)\n- It is now possible to search for file content that excludes a term using the `NOT` operator. Negating pattern syntax requires setting `\"search.migrateParser\": true` in settings and is currently only supported for literal and regexp queries on indexed repositories. [#12412](https://github.com/sourcegraph/sourcegraph/pull/12412)\n- `NOT` is available as an alternative syntax of `-` on supported keywords `repo`, `file`, `content`, `lang`, and `repohasfile`. `NOT` requires setting `\"search.migrateParser\": true` option in settings. [#12520](https://github.com/sourcegraph/sourcegraph/pull/12520)", "### Changed", "- Repository permissions are now always checked and updated asynchronously ([background permissions syncing](https://docs.sourcegraph.com/admin/repo/permissions#background-permissions-syncing)) instead of blocking each operation. The site config option `permissions.backgroundSync` (which enabled this behavior in previous versions) is now a no-op and is deprecated.\n- [Background permissions syncing](https://docs.sourcegraph.com/admin/repo/permissions#background-permissions-syncing) (`permissions.backgroundSync`) has become the only option for mirroring repository permissions from code hosts. All relevant site configurations are deprecated.", "### Fixed", "- Fixed site admins are getting errors when visiting user settings page in OSS version. [#12313](https://github.com/sourcegraph/sourcegraph/pull/12313)\n- `github-proxy` now respects the environment variables `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` (or the lowercase versions thereof). Other services already respect these variables, but this was missed. If you need a proxy to access github.com set the environment variable for the github-proxy container. [#12377](https://github.com/sourcegraph/sourcegraph/issues/12377)\n- `sourcegraph-frontend` now respects the `tls.external` experimental setting as well as the proxy environment variables. In proxy environments this allows Sourcegraph to fetch extensions. [#12633](https://github.com/sourcegraph/sourcegraph/issues/12633)\n- Fixed a bug that would sometimes cause trailing parentheses to be removed from search queries upon page load. [#12960](https://github.com/sourcegraph/sourcegraph/issues/12690)\n- Indexed search will no longer stall if a specific index job stalls. Additionally at scale many corner cases causing indexing to stall have been fixed. [#12502](https://github.com/sourcegraph/sourcegraph/pull/12502)\n- Indexed search will quickly recover from rebalancing / roll outs. When a indexed search shard goes down, its repositories are re-indexed by other shards. This takes a while and during a rollout leads to effectively re-indexing all repositories. We now avoid indexing the redistributed repositories once a shard comes back online. [#12474](https://github.com/sourcegraph/sourcegraph/pull/12474)\n- Indexed search has many improvements to observability. More detailed Jaeger traces, detailed logging during startup and more prometheus metrics.\n- The site admin repository needs-index page is significantly faster. Previously on large instances it would usually timeout. Now it should load within a second. [#12513](https://github.com/sourcegraph/sourcegraph/pull/12513)\n- User password reset page now respects the value of site config `auth.minPasswordLength`. [#12971](https://github.com/sourcegraph/sourcegraph/pull/12971)\n- Fixed an issue where duplicate search results would show for queries with `or`-expressions. [#12531](https://github.com/sourcegraph/sourcegraph/pull/12531)\n- Faster indexed search queries over a large number of repositories. Searching 100k+ repositories is now ~400ms faster and uses much less memory. [#12546](https://github.com/sourcegraph/sourcegraph/pull/12546)", "### Removed", "- Deprecated site settings `lightstepAccessToken` and `lightstepProject` have been removed. We now only support sending traces to Jaeger. Configure Jaeger with `observability.tracing` site setting.\n- Removed `CloneInProgress` option from GraphQL Repositories API. [#12560](https://github.com/sourcegraph/sourcegraph/pull/12560)", "## 3.18.0", "### Added", "- To search across multiple revisions of the same repository, list multiple branch names (or other revspecs) separated by `:` in your query, as in `repo:myrepo@branch1:branch2:branch2`. To search all branches, use `repo:myrepo@*refs/heads/`. Previously this was only supported for diff and commit searches and only available via the experimental site setting `searchMultipleRevisionsPerRepository`.\n- The \"Add repositories\" page (/site-admin/external-services/new) now displays a dismissable notification explaining how and why we access code host data. [#11789](https://github.com/sourcegraph/sourcegraph/pull/11789).\n- New `observability.alerts` features:\n - Notifications now provide more details about relevant alerts.\n - Support for email and OpsGenie notifications has been added. Note that to receive email alerts, `email.address` and `email.smtp` must be configured.\n - Some notifiers now have new options:\n - PagerDuty notifiers: `severity` and `apiUrl`\n - Webhook notifiers: `bearerToken`\n - A new `disableSendResolved` option disables notifications for when alerts resolve themselves.\n- Recently firing critical alerts can now be displayed to admins via site alerts, use the flag `{ \"alerts.hideObservabilitySiteAlerts\": false }` to enable these alerts in user configuration.\n- Specific alerts can now be silenced using `observability.silenceAlerts`. [#12087](https://github.com/sourcegraph/sourcegraph/pull/12087)\n- Revisions listed in `experimentalFeatures.versionContext` will be indexed for faster searching. This is the first support towards indexing non-default branches. [#6728](https://github.com/sourcegraph/sourcegraph/issues/6728)\n- Revisions listed in `experimentalFeatures.versionContext` or `experimentalFeatures.search.index.branches` will be indexed for faster searching. This is the first support towards indexing non-default branches. [#6728](https://github.com/sourcegraph/sourcegraph/issues/6728)\n- Campaigns are now supported on GitLab.\n- Campaigns now support GitLab and allow users to create, update and track merge requests on GitLab instances.\n- Added a new section on the search homepage on Sourcegraph.com. It is currently feature flagged behind `experimentalFeatures.showRepogroupHomepage` in settings.\n- Added new repository group pages.", "### Changed", "- Some monitoring alerts now have more useful descriptions. [#11542](https://github.com/sourcegraph/sourcegraph/pull/11542)\n- Searching `fork:true` or `archived:true` has the same behaviour as searching `fork:yes` or `archived:yes` respectively. Previously it incorrectly had the same behaviour as `fork:only` and `archived:only` respectively. [#11740](https://github.com/sourcegraph/sourcegraph/pull/11740)\n- Configuration for `observability.alerts` has changed and notifications are now provided by Prometheus Alertmanager. [#11832](https://github.com/sourcegraph/sourcegraph/pull/11832)\n - Removed: `observability.alerts.id`.\n - Removed: Slack notifiers no longer accept `mentionUsers`, `mentionGroups`, `mentionChannel`, and `token` options.", "### Fixed", "- The single-container `sourcegraph/server` image now correctly reports its version.\n- An issue where repositories would not clone and index in some edge cases where the clones were deleted or not successful on gitserver. [#11602](https://github.com/sourcegraph/sourcegraph/pull/11602)\n- An issue where repositories previously deleted on gitserver would not immediately reclone on system startup. [#11684](https://github.com/sourcegraph/sourcegraph/issues/11684)\n- An issue where the sourcegraph/server Jaeger config was invalid. [#11661](https://github.com/sourcegraph/sourcegraph/pull/11661)\n- An issue where valid search queries were improperly hinted as being invalid in the search field. [#11688](https://github.com/sourcegraph/sourcegraph/pull/11688)\n- Reduce frontend memory spikes by limiting the number of goroutines launched by our GraphQL resolvers. [#11736](https://github.com/sourcegraph/sourcegraph/pull/11736)\n- Fixed a bug affecting Sourcegraph icon display in our Phabricator native integration [#11825](https://github.com/sourcegraph/sourcegraph/pull/11825).\n- Improve performance of site-admin repositories status page. [#11932](https://github.com/sourcegraph/sourcegraph/pull/11932)\n- An issue where search autocomplete for files didn't add the right path. [#12241](https://github.com/sourcegraph/sourcegraph/pull/12241)", "### Removed", "- Backwards compatibility for \"critical configuration\" (a type of configuration that was deprecated in December 2019) was removed. All critical configuration now belongs in site configuration.\n- Experimental feature setting `{ \"experimentalFeatures\": { \"searchMultipleRevisionsPerRepository\": true } }` will be removed in 3.19. It is now always on. Please remove references to it.\n- Removed \"Cloning\" tab in site-admin Repository Status page. [#12043](https://github.com/sourcegraph/sourcegraph/pull/12043)\n- The `blacklist` configuration option for Gitolite that was deprecated in 3.17 has been removed in 3.19. Use `exclude.pattern` instead. [#12345](https://github.com/sourcegraph/sourcegraph/pull/12345)", "## 3.17.3", "### Fixed", "- git: Command retrying made a copy that was never used [#11807](https://github.com/sourcegraph/sourcegraph/pull/11807)\n- frontend: Allow opt out of EnsureRevision when making a comparison query [#11811](https://github.com/sourcegraph/sourcegraph/pull/11811)\n- Fix Phabricator icon class [#11825](https://github.com/sourcegraph/sourcegraph/pull/11825)", "## 3.17.2", "### Fixed", "- An issue where repositories previously deleted on gitserver would not immediately reclone on system startup. [#11684](https://github.com/sourcegraph/sourcegraph/issues/11684)", "## 3.17.1", "### Added", "- Improved search indexing metrics", "### Changed", "- Some monitoring alerts now have more useful descriptions. [#11542](https://github.com/sourcegraph/sourcegraph/pull/11542)", "### Fixed", "- The single-container `sourcegraph/server` image now correctly reports its version.\n- An issue where repositories would not clone and index in some edge cases where the clones were deleted or not successful on gitserver. [#11602](https://github.com/sourcegraph/sourcegraph/pull/11602)\n- An issue where the sourcegraph/server Jaeger config was invalid. [#11661](https://github.com/sourcegraph/sourcegraph/pull/11661)", "## 3.17.0", "### Added", "- The search results page now shows a small UI notification if either repository forks or archives are excluded, when `fork` or `archived` options are not explicitly set. [#10624](https://github.com/sourcegraph/sourcegraph/pull/10624)\n- Prometheus metric `src_gitserver_repos_removed_disk_pressure` which is incremented everytime we remove a repository due to disk pressure. [#10900](https://github.com/sourcegraph/sourcegraph/pull/10900)\n- `gitolite.exclude` setting in [Gitolite external service config](https://docs.sourcegraph.com/admin/external_service/gitolite#configuration) now supports a regular expression via the `pattern` field. This is consistent with how we exclude in other external services. Additionally this is a replacement for the deprecated `blacklist` configuration. [#11403](https://github.com/sourcegraph/sourcegraph/pull/11403)\n- Notifications about Sourcegraph being out of date will now be shown to site admins and users (depending on how out-of-date it is).\n- Alerts are now configured using `observability.alerts` in the site configuration, instead of via the Grafana web UI. This does not yet support all Grafana notification channel types, and is not yet supported on `sourcegraph/server` ([#11473](https://github.com/sourcegraph/sourcegraph/issues/11473)). For more details, please refer to the [Sourcegraph alerting guide](https://docs.sourcegraph.com/admin/observability/alerting).\n- Experimental basic support for detecting if your Sourcegraph instance is over or under-provisioned has been added through a set of dashboards and warning-level alerts based on container utilization.\n- Query [operators](https://docs.sourcegraph.com/code_search/reference/queries#boolean-operators) `and` and `or` are now enabled by default in all search modes for searching file content. [#11521](https://github.com/sourcegraph/sourcegraph/pull/11521)", "### Changed", "- Repository search within a version context will link to the revision in the version context. [#10860](https://github.com/sourcegraph/sourcegraph/pull/10860)\n- Background permissions syncing becomes the default method to sync permissions from code hosts. Please [read our documentation for things to keep in mind before upgrading](https://docs.sourcegraph.com/admin/repo/permissions#background-permissions-syncing). [#10972](https://github.com/sourcegraph/sourcegraph/pull/10972)\n- The styling of the hover overlay was overhauled to never have badges or the close button overlap content while also always indicating whether the overlay is currently pinned. The styling on code hosts was also improved. [#10956](https://github.com/sourcegraph/sourcegraph/pull/10956)\n- Previously, it was required to quote most patterns in structural search. This is no longer a restriction and single and double quotes in structural search patterns are interpreted literally. Note: you may still use `content:\"structural-pattern\"` if the pattern without quotes conflicts with other syntax. [#11481](https://github.com/sourcegraph/sourcegraph/pull/11481)", "### Fixed", "- Dynamic repo search filters on branches which contain special characters are correctly escaped now. [#10810](https://github.com/sourcegraph/sourcegraph/pull/10810)\n- Forks and archived repositories at a specific commit are searched without the need to specify \"fork:yes\" or \"archived:yes\" in the query. [#10864](https://github.com/sourcegraph/sourcegraph/pull/10864)\n- The git history for binary files is now correctly shown. [#11034](https://github.com/sourcegraph/sourcegraph/pull/11034)\n- Links to AWS Code Commit repositories have been fixed after the URL schema has been changed. [#11019](https://github.com/sourcegraph/sourcegraph/pull/11019)\n- A link to view all repositories will now always appear on the Explore page. [#11113](https://github.com/sourcegraph/sourcegraph/pull/11113)\n- The Site-admin > Pings page no longer incorrectly indicates that pings are disabled when they aren't. [#11229](https://github.com/sourcegraph/sourcegraph/pull/11229)\n- Match counts are now accurately reported for indexed search. [#11242](https://github.com/sourcegraph/sourcegraph/pull/11242)\n- When background permissions syncing is enabled, it is now possible to only enforce permissions for repositories from selected code hosts (instead of enforcing permissions for repositories from all code hosts). [#11336](https://github.com/sourcegraph/sourcegraph/pull/11336)\n- When more than 200+ repository revisions in a search are unindexed (very rare), the remaining repositories are reported as missing instead of Sourcegraph issuing e.g. several thousand unindexed search requests which causes system slowness and ultimately times out - ensuring searches are still fast even if there are indexing issues on a deployment of Sourcegraph. This does not apply if `index:no` is present in the query.", "### Removed", "- Automatic syncing of Campaign webhooks for Bitbucket Server. [#10962](https://github.com/sourcegraph/sourcegraph/pull/10962)\n- The `blacklist` configuration option for Gitolite is DEPRECATED and will be removed in 3.19. Use `exclude.pattern` instead.", "## 3.16.2", "### Fixed", "- Search: fix indexed search match count [#7fc96](https://github.com/sourcegraph/sourcegraph/commit/7fc96d319f49f55da46a7649ccf261aa7e8327c3)\n- Sort detected languages properly [#e7750](https://github.com/sourcegraph/sourcegraph/commit/e77507d060a40355e7b86fb093d21a7149ea03ac)", "## 3.16.1", "### Fixed", "- Fix repo not found error for patches [#11021](https://github.com/sourcegraph/sourcegraph/pull/11021).\n- Show expired license screen [#10951](https://github.com/sourcegraph/sourcegraph/pull/10951).\n- Sourcegraph is now built with Go 1.14.3, fixing issues running Sourcegraph onUbuntu 19 and 20. [#10447](https://github.com/sourcegraph/sourcegraph/issues/10447)", "## 3.16.0", "### Added", "- Autocompletion for `repogroup` filters in search queries. [#10141](https://github.com/sourcegraph/sourcegraph/pull/10286)\n- If the experimental feature flag `codeInsights` is enabled, extensions can contribute content to directory pages through the experimental `ViewProvider` API. [#10236](https://github.com/sourcegraph/sourcegraph/pull/10236)\n - Directory pages are then represented as an experimental `DirectoryViewer` in the `visibleViewComponents` of the extension API. **Note: This may break extensions that were assuming `visibleViewComponents` were always `CodeEditor`s and did not check the `type` property.** Extensions checking the `type` property will continue to work. [#10236](https://github.com/sourcegraph/sourcegraph/pull/10236)\n- [Major syntax highlighting improvements](https://github.com/sourcegraph/syntect_server/pull/29), including:\n - 228 commits / 1 year of improvements to the syntax highlighter library Sourcegraph uses ([syntect](https://github.com/trishume/syntect)).\n - 432 commits / 1 year of improvements to the base syntax definitions for ~36 languages Sourcegraph uses ([sublimehq/Packages](https://github.com/sublimehq/Packages)).\n - 30 new file extensions/names now detected.\n - Likely fixes other major instability and language support issues. #9557\n - Added [Smarty](#2885), [Ethereum / Solidity / Vyper)](#2440), [Cuda](#5907), [COBOL](#10154), [vb.NET](#4901), and [ASP.NET](#4262) syntax highlighting.\n - Fixed OCaml syntax highlighting #3545\n - Bazel/Starlark support improved (.star, BUILD, and many more extensions now properly highlighted). #8123\n- New permissions page in both user and repository settings when background permissions syncing is enabled (`\"permissions.backgroundSync\": {\"enabled\": true}`). [#10473](https://github.com/sourcegraph/sourcegraph/pull/10473) [#10655](https://github.com/sourcegraph/sourcegraph/pull/10655)\n- A new dropdown for choosing version contexts appears on the left of the query input when version contexts are specified in `experimentalFeatures.versionContext` in site configuration. Version contexts allow you to scope your search to specific sets of repos at revisions.\n- Campaign changeset usage counts including changesets created, added and merged will be sent back in pings. [#10591](https://github.com/sourcegraph/sourcegraph/pull/10591)\n- Diff views now feature syntax highlighting and can be properly copy-pasted. [#10437](https://github.com/sourcegraph/sourcegraph/pull/10437)\n- Admins can now download an anonymized usage statistics ZIP archive in the **Site admin > Usage stats**. Opting to share this archive with the Sourcegraph team helps us make the product even better. [#10475](https://github.com/sourcegraph/sourcegraph/pull/10475)\n- Extension API: There is now a field `versionContext` and subscribable `versionContextChanges` in `Workspace` to allow extensions to respect the instance's version context.\n- The smart search field, providing syntax highlighting, hover tooltips, and validation on filters in search queries, is now activated by default. It can be disabled by setting `{ \"experimentalFeatures\": { \"smartSearchField\": false } }` in global settings.", "### Changed", "- The `userID` and `orgID` fields in the SavedSearch type in the GraphQL API have been replaced with a `namespace` field. To get the ID of the user or org that owns the saved search, use `namespace.id`. [#5327](https://github.com/sourcegraph/sourcegraph/pull/5327)\n- Tree pages now redirect to blob pages if the path is not a tree and vice versa. [#10193](https://github.com/sourcegraph/sourcegraph/pull/10193)\n- Files and directories that are not found now return a 404 status code. [#10193](https://github.com/sourcegraph/sourcegraph/pull/10193)\n- The site admin flag `disableNonCriticalTelemetry` now allows Sourcegraph admins to disable most anonymous telemetry. Visit https://docs.sourcegraph.com/admin/pings to learn more. [#10402](https://github.com/sourcegraph/sourcegraph/pull/10402)", "### Fixed", "- In the OSS version of Sourcegraph, authorization providers are properly initialized and GraphQL APIs are no longer blocked. [#3487](https://github.com/sourcegraph/sourcegraph/issues/3487)\n- Previously, GitLab repository paths containing certain characters could not be excluded (slashes and periods in parts of the paths). These characters are now allowed, so the repository paths can be excluded. [#10096](https://github.com/sourcegraph/sourcegraph/issues/10096)\n- Symbols for indexed commits in languages Haskell, JSONNet, Kotlin, Scala, Swift, Thrift, and TypeScript will show up again. Previously our symbol indexer would not know how to extract symbols for those languages even though our unindexed symbol service did. [#10357](https://github.com/sourcegraph/sourcegraph/issues/10357)\n- When periodically re-cloning a repository it will still be available. [#10663](https://github.com/sourcegraph/sourcegraph/pull/10663)", "### Removed", "- The deprecated feature discussions has been removed. [#9649](https://github.com/sourcegraph/sourcegraph/issues/9649)", "## 3.15.2", "### Fixed", "- Fix repo not found error for patches [#11021](https://github.com/sourcegraph/sourcegraph/pull/11021).\n- Show expired license screen [#10951](https://github.com/sourcegraph/sourcegraph/pull/10951).", "## 3.15.1", "### Fixed", "- A potential security vulnerability with in the authentication workflow has been fixed. [#10167](https://github.com/sourcegraph/sourcegraph/pull/10167)\n- An issue where `sourcegraph/postgres-11.4:3.15.0` was incorrectly an older version of the image incompatible with non-root Kubernetes deployments. `sourcegraph/postgres-11.4:3.15.1` now matches the same image version found in Sourcegraph 3.14.3 (`20-04-07_56b20163`).\n- An issue that caused the search result type tabs to be overlapped in Safari. [#10191](https://github.com/sourcegraph/sourcegraph/pull/10191)", "## 3.15.0", "### Added", "- Users and site administrators can now view a log of their actions/events in the user settings. [#9141](https://github.com/sourcegraph/sourcegraph/pull/9141)\n- With the new `visibility:` filter search results can now be filtered based on a repository's visibility (possible filter values: `any`, `public` or `private`). [#8344](https://github.com/sourcegraph/sourcegraph/issues/8344)\n- [`sourcegraph/git-extras`](https://sourcegraph.com/extensions/sourcegraph/git-extras) is now enabled by default on new instances [#3501](https://github.com/sourcegraph/sourcegraph/issues/3501)\n- The Sourcegraph Docker image will now copy `/etc/sourcegraph/gitconfig` to `$HOME/.gitconfig`. This is a convenience similiar to what we provide for [repositories that need HTTP(S) or SSH authentication](https://docs.sourcegraph.com/admin/repo/auth). [#658](https://github.com/sourcegraph/sourcegraph/issues/658)\n- Permissions background syncing is now supported for GitHub via site configuration `\"permissions.backgroundSync\": {\"enabled\": true}`. [#8890](https://github.com/sourcegraph/sourcegraph/issues/8890)\n- Search: Adding `stable:true` to a query ensures a deterministic search result order. This is an experimental parameter. It applies only to file contents, and is limited to at max 5,000 results (consider using [the paginated search API](https://docs.sourcegraph.com/api/graphql/search#sourcegraph-3-9-experimental-paginated-search) if you need more than that.). [#9681](https://github.com/sourcegraph/sourcegraph/pull/9681).\n- After completing the Sourcegraph user feedback survey, a button may appear for tweeting this feedback at [@sourcegraph](https://twitter.com/sourcegraph). [#9728](https://github.com/sourcegraph/sourcegraph/pull/9728)\n- `git fetch` and `git clone` now inherit the parent process environment variables. This allows site admins to set `HTTPS_PROXY` or [git http configurations](https://git-scm.com/docs/git-config/2.26.0#Documentation/git-config.txt-httpproxy) via environment variables. For cluster environments site admins should set this on the gitserver container. [#250](https://github.com/sourcegraph/sourcegraph/issues/250)\n- Experimental: Search for file contents using `and`- and `or`-expressions in queries. Enabled via the global settings value `{\"experimentalFeatures\": {\"andOrQuery\": \"enabled\"}}`. [#8567](https://github.com/sourcegraph/sourcegraph/issues/8567)\n- Always include forks or archived repositories in searches via the global/org/user settings with `\"search.includeForks\": true` or `\"search.includeArchived\": true` respectively. [#9927](https://github.com/sourcegraph/sourcegraph/issues/9927)\n- observability (debugging): It is now possible to log all Search and GraphQL requests slower than N milliseconds, using the new site configuration options `observability.logSlowGraphQLRequests` and `observability.logSlowSearches`.\n- observability (monitoring): **More metrics monitored and alerted on, more legible dashboards**\n - Dashboard panels now show an orange/red background color when the defined warning/critical alert threshold has been met, making it even easier to see on a dashboard what is in a bad state.\n - Symbols: failing `symbols` -> `frontend-internal` requests are now monitored. [#9732](https://github.com/sourcegraph/sourcegraph/issues/9732)\n - Frontend dasbhoard: Search error types are now broken into distinct panels for improved visibility/legibility.\n - **IMPORTANT**: If you have previously configured alerting on any of these panels or on \"hard search errors\", you will need to reconfigure it after upgrading.\n - Frontend dasbhoard: Search error and latency are now broken down by type: Browser requests, search-based code intel requests, and API requests.\n- observability (debugging): **Distributed tracing is a powerful tool for investigating performance issues.** The following changes have been made with the goal of making it easier to use distributed tracing with Sourcegraph:", " - The site configuration field `\"observability.tracing\": { \"sampling\": \"...\" }` allows a site admin to control which requests generate tracing data.\n - `\"all\"` will trace all requests.\n - `\"selective\"` (recommended) will trace all requests initiated from an end-user URL with `?trace=1`. Non-end-user-initiated requests can set a HTTP header `X-Sourcegraph-Should-Trace: true`. This is the recommended setting, as `\"all\"` can generate large amounts of tracing data that may cause network and memory resource contention in the Sourcegraph instance.\n - `\"none\"` (default) turns off tracing.\n - Jaeger is now the officially supported distributed tracer. The following is the recommended site configuration to connect Sourcegraph to a Jaeger agent (which must be deployed on the same host and listening on the default ports):", " ```\n \"observability.tracing\": {\n \"sampling\": \"selective\"\n }\n ```", " - Jaeger is now included in the Sourcegraph deployment configuration by default if you are using Kubernetes, Docker Compose, or the pure Docker cluster deployment model. (It is not yet included in the single Docker container distribution.) It will be included as part of upgrading to 3.15 in these deployment models, unless disabled.\n - The site configuration field, `useJaeger`, is deprecated in favor of `observability.tracing`.\n - Support for configuring Lightstep as a distributed tracer is deprecated and will be removed in a subsequent release. Instances that use Lightstep with Sourcegraph are encouraged to migrate to Jaeger (directions for running Jaeger alongside Sourcegraph are included in the installation instructions).", "### Changed", "- Multiple backwards-incompatible changes in the parts of the GraphQL API related to Campaigns [#9106](https://github.com/sourcegraph/sourcegraph/issues/9106):\n - `CampaignPlan.status` has been removed, since we don't need it anymore after moving execution of campaigns to src CLI in [#8008](https://github.com/sourcegraph/sourcegraph/pull/8008).\n - `CampaignPlan` has been renamed to `PatchSet`.\n - `ChangesetPlan`/`ChangesetPlanConnection` has been renamed to `Patch`/`PatchConnection`.\n - `CampaignPlanPatch` has been renamed to `PatchInput`.\n - `Campaign.plan` has been renamed to `Campaign.patchSet`.\n - `Campaign.changesetPlans` has been renamed to `campaign.changesetPlan`.\n - `createCampaignPlanFromPatches` mutation has been renamed to `createPatchSetFromPatches`.\n- Removed the scoped search field on tree pages. When browsing code, the global search query will now get scoped to the current tree or file. [#9225](https://github.com/sourcegraph/sourcegraph/pull/9225)\n- Instances without a license key that exceed the published user limit will now display a notice to all users.", "### Fixed", "- `.*` in the filter pattern were ignored and led to missing search results. [#9152](https://github.com/sourcegraph/sourcegraph/pull/9152)\n- The Phabricator integration no longer makes duplicate requests to Phabricator's API on diff views. [#8849](https://github.com/sourcegraph/sourcegraph/issues/8849)\n- Changesets on repositories that aren't available on the instance anymore are now hidden instead of failing. [#9656](https://github.com/sourcegraph/sourcegraph/pull/9656)\n- observability (monitoring):\n - **Dashboard and alerting bug fixes**\n - Syntect Server dashboard: \"Worker timeouts\" can no longer appear to go negative. [#9523](https://github.com/sourcegraph/sourcegraph/issues/9523)\n - Symbols dashboard: \"Store fetch queue size\" can no longer appear to go negative. [#9731](https://github.com/sourcegraph/sourcegraph/issues/9731)\n - Syntect Server dashboard: \"Worker timeouts\" no longer incorrectly shows multiple values. [#9524](https://github.com/sourcegraph/sourcegraph/issues/9524)\n - Searcher dashboard: \"Search errors on unindexed repositories\" no longer includes cancelled search requests (which are expected).\n - Fixed an issue where NaN could leak into the `alert_count` metric. [#9832](https://github.com/sourcegraph/sourcegraph/issues/9832)\n - Gitserver: \"resolve_revision_duration_slow\" alert is no longer flaky / non-deterministic. [#9751](https://github.com/sourcegraph/sourcegraph/issues/9751)\n - Git Server dashboard: there is now a panel to show concurrent command executions to match the defined alerts. [#9354](https://github.com/sourcegraph/sourcegraph/issues/9354)\n - Git Server dashboard: adjusted the critical disk space alert to 15% so it can now fire. [#9351](https://github.com/sourcegraph/sourcegraph/issues/9351)\n - **Dashboard visiblity and legibility improvements**\n - all: \"frontend internal errors\" are now broken down just by route, which makes reading the graph easier. [#9668](https://github.com/sourcegraph/sourcegraph/issues/9668)\n - Frontend dashboard: panels no longer show misleading duplicate labels. [#9660](https://github.com/sourcegraph/sourcegraph/issues/9660)\n - Syntect Server dashboard: panels are no longer compacted, for improved visibility. [#9525](https://github.com/sourcegraph/sourcegraph/issues/9525)\n - Frontend dashboard: panels are no longer compacted, for improved visibility. [#9356](https://github.com/sourcegraph/sourcegraph/issues/9356)\n - Searcher dashboard: \"Search errors on unindexed repositories\" is now broken down by code instead of instance for improved readability. [#9670](https://github.com/sourcegraph/sourcegraph/issues/9670)\n - Symbols dashboard: metrics are now aggregated instead of per-instance, for improved visibility. [#9730](https://github.com/sourcegraph/sourcegraph/issues/9730)\n - Firing alerts are now correctly sorted at the top of dashboards by default. [#9766](https://github.com/sourcegraph/sourcegraph/issues/9766)\n - Panels at the bottom of the home dashboard no longer appear clipped / cut off. [#9768](https://github.com/sourcegraph/sourcegraph/issues/9768)\n - Git Server dashboard: disk usage now shown in percentages to match the alerts that can fire. [#9352](https://github.com/sourcegraph/sourcegraph/issues/9352)\n - Git Server dashboard: the 'echo command duration test' panel now properly displays units in seconds. [#7628](https://github.com/sourcegraph/sourcegraph/issues/7628)\n - Dashboard panels showing firing alerts no longer over-count firing alerts due to the number of service replicas. [#9353](https://github.com/sourcegraph/sourcegraph/issues/9353)", "### Removed", "- The experimental feature discussions is marked as deprecated. GraphQL and configuration fields related to it will be removed in 3.16. [#9649](https://github.com/sourcegraph/sourcegraph/issues/9649)", "## 3.14.4", "### Fixed", "- A potential security vulnerability with in the authentication workflow has been fixed. [#10167](https://github.com/sourcegraph/sourcegraph/pull/10167)", "## 3.14.3", "### Fixed", "- phabricator: Duplicate requests to phabricator API from sourcegraph extensions. [#8849](https://github.com/sourcegraph/sourcegraph/issues/8849)", "## 3.14.2", "### Fixed", "- campaigns: Ignore changesets where repo does not exist anymore. [#9656](https://github.com/sourcegraph/sourcegraph/pull/9656)", "## 3.14.1", "### Added", "- monitoring: new Permissions dashboard to show stats of repository permissions.", "### Changed", "- Site-Admin/Instrumentation in the Kubernetes cluster deployment now includes indexed-search.", "## 3.14.0", "### Added", "- Site-Admin/Instrumentation is now available in the Kubernetes cluster deployment [8805](https://github.com/sourcegraph/sourcegraph/pull/8805).\n- Extensions can now specify a `baseUri` in the `DocumentFilter` when registering providers.\n- Admins can now exclude GitHub forks and/or archived repositories from the set of repositories being mirrored in Sourcegraph with the `\"exclude\": [{\"forks\": true}]` or `\"exclude\": [{\"archived\": true}]` GitHub external service configuration. [#8974](https://github.com/sourcegraph/sourcegraph/pull/8974)\n- Campaign changesets can be filtered by State, Review State and Check State. [#8848](https://github.com/sourcegraph/sourcegraph/pull/8848)\n- Counts of users of and searches conducted with interactive and plain text search modes will be sent back in pings, aggregated daily, weekly, and monthly.\n- Aggregated counts of daily, weekly, and monthly active users of search will be sent back in pings.\n- Counts of number of searches conducted using each filter will be sent back in pings, aggregated daily, weekly, and monthly.\n- Counts of number of users conducting searches containing each filter will be sent back in pings, aggregated daily, weekly, and monthly.\n- Added more entries (Bash, Erlang, Julia, OCaml, Scala) to the list of suggested languages for the `lang:` filter.\n- Permissions background sync is now supported for GitLab and Bitbucket Server via site configuration `\"permissions.backgroundSync\": {\"enabled\": true}`.\n- Indexed search exports more prometheus metrics and debug logs to aid debugging performance issues. [#9111](https://github.com/sourcegraph/sourcegraph/issues/9111)\n- monitoring: the Frontend dashboard now shows in excellent detail how search is behaving overall and at a glance.\n- monitoring: added alerts for when hard search errors (both timeouts and general errors) are high.\n- monitoring: added alerts for when partial search timeouts are high.\n- monitoring: added alerts for when search 90th and 99th percentile request duration is high.\n- monitoring: added alerts for when users are being shown an abnormally large amount of search alert user suggestions and no results.\n- monitoring: added alerts for when the internal indexed and unindexed search services are returning bad responses.\n- monitoring: added alerts for when gitserver may be under heavy load due to many concurrent command executions or under-provisioning.", "### Changed", "- The \"automation\" feature was renamed to \"campaigns\".\n - `campaigns.readAccess.enabled` replaces the deprecated site configuration property `automation.readAccess.enabled`.\n - The experimental feature flag was not renamed (because it will go away soon) and remains `{\"experimentalFeatures\": {\"automation\": \"enabled\"}}`.\n- The [Kubernetes deployment](https://github.com/sourcegraph/deploy-sourcegraph) for **existing** installations requires a\n [migration step](https://github.com/sourcegraph/deploy-sourcegraph/blob/master/docs/migrate.md) when upgrading\n past commit [821032e2ee45f21f701](https://github.com/sourcegraph/deploy-sourcegraph/commit/821032e2ee45f21f701caac624e4f090c59fd259) or when upgrading to 3.14.\n New installations starting with the mentioned commit or with 3.14 do not need this migration step.\n- Aggregated search latencies (in ms) of search queries are now included in [pings](https://docs.sourcegraph.com/admin/pings).\n- The [Kubernetes deployment](https://github.com/sourcegraph/deploy-sourcegraph) frontend role has added services as a resource to watch/listen/get.\n This change does not affect the newly-introduced, restricted Kubernetes config files.\n- Archived repositories are excluded from search by default. Adding `archived:yes` includes archived repositories.\n- Forked repositories are excluded from search by default. Adding `fork:yes` includes forked repositories.\n- CSRF and session cookies now set `SameSite=None` when Sourcegraph is running behind HTTPS and `SameSite=Lax` when Sourcegraph is running behind HTTP in order to comply with a [recent IETF proposal](https://web.dev/samesite-cookies-explained/#samesitenone-must-be-secure). As a side effect, the Sourcegraph browser extension and GitLab/Bitbucket native integrations can only connect to private instances that have HTTPS configured. If your private instance is only running behind HTTP, please configure your instance to use HTTPS in order to continue using these.\n- The Bitbucket Server rate limit that Sourcegraph self-imposes has been raised from 120 req/min to 480 req/min to account for Sourcegraph instances that make use of Sourcegraphs' Bitbucket Server repository permissions and campaigns at the same time (which require a larger number of API requests against Bitbucket Server). The new number is based on Sourcegraph consuming roughly 8% the average API request rate of a large customers' Bitbucket Server instance. [#9048](https://github.com/sourcegraph/sourcegraph/pull/9048/files)\n- If a single, unambiguous commit SHA is used in a search query (e.g., `repo@c98f56`) and a search index exists at this commit (i.e., it is the `HEAD` commit), then the query is searched using the index. Prior to this change, unindexed search was performed for any query containing an `@commit` specifier.", "### Fixed", "- Zoekt's watchdog ensures the service is down upto 3 times before exiting. The watchdog would misfire on startup on resource constrained systems, with the retries this should make a false positive far less likely. [#7867](https://github.com/sourcegraph/sourcegraph/issues/7867)\n- A regression in repo-updater was fixed that lead to every repository's git clone being updated every time the list of repositories was synced from the code host. [#8501](https://github.com/sourcegraph/sourcegraph/issues/8501)\n- The default timeout of indexed search has been increased. Previously indexed search would always return within 3s. This lead to broken behaviour on new instances which had yet to tune resource allocations. [#8720](https://github.com/sourcegraph/sourcegraph/pull/8720)\n- Bitbucket Server older than 5.13 failed to sync since Sourcegraph 3.12. This was due to us querying for the `archived` label, but Bitbucket Server 5.13 does not support labels. [#8883](https://github.com/sourcegraph/sourcegraph/issues/8883)\n- monitoring: firing alerts are now ordered at the top of the list in dashboards by default for better visibility.\n- monitoring: fixed an issue where some alerts would fail to report in for the \"Total alerts defined\" panel in the overview dashboard.", "### Removed", "- The v3.11 migration to merge critical and site configuration has been removed. If you are still making use of the deprecated `CRITICAL_CONFIG_FILE`, your instance may not start up. See the [migration notes for Sourcegraph 3.11](https://docs.sourcegraph.com/admin/migration/3_11) for more information.", "## 3.13.2", "### Fixed", "- The default timeout of indexed search has been increased. Previously indexed search would always return within 3s. This lead to broken behaviour on new instances which had yet to tune resource allocations. [#8720](https://github.com/sourcegraph/sourcegraph/pull/8720)\n- Bitbucket Server older than 5.13 failed to sync since Sourcegraph 3.12. This was due to us querying for the `archived` label, but Bitbucket Server 5.13 does not support labels. [#8883](https://github.com/sourcegraph/sourcegraph/issues/8883)\n- A regression in repo-updater was fixed that lead to every repository's git clone being updated every time the list of repositories was synced from the code host. [#8501](https://github.com/sourcegraph/sourcegraph/issues/8501)", "## 3.13.1", "### Fixed", "- To reduce the chance of users running into \"502 Bad Gateway\" errors an internal timeout has been increased from 60 seconds to 10 minutes so that long running requests are cut short by the proxy in front of `sourcegraph-frontend` and correctly reported as \"504 Gateway Timeout\". [#8606](https://github.com/sourcegraph/sourcegraph/pull/8606)\n- Sourcegraph instances that are not connected to the internet will no longer display errors when users submit NPS survey responses (the responses will continue to be stored locally). Rather, an error will be printed to the frontend logs. [#8598](https://github.com/sourcegraph/sourcegraph/issues/8598)\n- Showing `head>` in the search results if the first line of the file is shown [#8619](https://github.com/sourcegraph/sourcegraph/issues/8619)", "## 3.13.0", "### Added", "- Experimental: Added new field `experimentalFeatures.customGitFetch` that allows defining custom git fetch commands for code hosts and repositories with special settings. [#8435](https://github.com/sourcegraph/sourcegraph/pull/8435)\n- Experimental: the search query input now provides syntax highlighting, hover tooltips, and diagnostics on filters in search queries. Requires the global settings value `{ \"experimentalFeatures\": { \"smartSearchField\": true } }`.\n- Added a setting `search.hideSuggestions`, which when set to `true`, will hide search suggestions in the search bar. [#8059](https://github.com/sourcegraph/sourcegraph/pull/8059)\n- Experimental: A tool, [src-expose](https://docs.sourcegraph.com/admin/external_service/other#experimental-src-expose), can be used to import code from any code host.\n- Experimental: Added new field `certificates` as in `{ \"experimentalFeatures\" { \"tls.external\": { \"certificates\": [\"<CERT>\"] } } }`. This allows you to add certificates to trust when communicating with a code host (via API or git+http). We expect this to be useful for adding internal certificate authorities/self-signed certificates. [#71](https://github.com/sourcegraph/sourcegraph/issues/71)\n- Added a setting `auth.minPasswordLength`, which when set, causes a minimum password length to be enforced when users sign up or change passwords. [#7521](https://github.com/sourcegraph/sourcegraph/issues/7521)\n- GitHub labels associated with code change campaigns are now displayed. [#8115](https://github.com/sourcegraph/sourcegraph/pull/8115)\n- GitHub labels associated with campaigns are now displayed. [#8115](https://github.com/sourcegraph/sourcegraph/pull/8115)\n- When creating a campaign, users can now specify the branch name that will be used on code host. This is also a breaking change for users of the GraphQL API since the `branch` attribute is now required in `CreateCampaignInput` when a `plan` is also specified. [#7646](https://github.com/sourcegraph/sourcegraph/issues/7646)\n- Added an optional `content:` parameter for specifying a search pattern. This parameter overrides any other search patterns in a query. Useful for unambiguously specifying what to search for when search strings clash with other query syntax. [#6490](https://github.com/sourcegraph/sourcegraph/issues/6490)\n- Interactive search mode, which helps users construct queries using UI elements, is now made available to users by default. A dropdown to the left of the search bar allows users to toggle between interactive and plain text modes. The option to use interactive search mode can be disabled by adding `{ \"experimentalFeatures\": { \"splitSearchModes\": false } }` in global settings. [#8461](https://github.com/sourcegraph/sourcegraph/pull/8461)\n- Our [upgrade policy](https://docs.sourcegraph.com/#upgrading-sourcegraph) is now enforced by the `sourcegraph-frontend` on startup to prevent admins from mistakenly jumping too many versions. [#8157](https://github.com/sourcegraph/sourcegraph/pull/8157) [#7702](https://github.com/sourcegraph/sourcegraph/issues/7702)\n- Repositories with bad object packs or bad objects are automatically repaired. We now detect suspect output of git commands to mark a repository for repair. [#6676](https://github.com/sourcegraph/sourcegraph/issues/6676)\n- Hover tooltips for Scala and Perl files now have syntax highlighting. [#8456](https://github.com/sourcegraph/sourcegraph/pull/8456) [#8307](https://github.com/sourcegraph/sourcegraph/issues/8307)", "### Changed", "- `experimentalFeatures.splitSearchModes` was removed as a site configuration option. It should be set in global/org/user settings.\n- Sourcegraph now waits for `90s` instead of `5s` for Redis to be available before quitting. This duration is configurable with the new `SRC_REDIS_WAIT_FOR` environment variable.\n- Code intelligence usage statistics will be sent back via pings by default. Aggregated event counts can be disabled via the site admin flag `disableNonCriticalTelemetry`.\n- The Sourcegraph Docker image optimized its use of Redis to make start-up significantly faster in certain scenarios (e.g when container restarts were frequent). ([#3300](https://github.com/sourcegraph/sourcegraph/issues/3300), [#2904](https://github.com/sourcegraph/sourcegraph/issues/2904))\n- Upgrading Sourcegraph is officially supported for one minor version increment (e.g., 3.12 -> 3.13). Previously, upgrades from 2 minor versions previous were supported. Please reach out to support@sourcegraph.com if you would like assistance upgrading from a much older version of Sourcegraph.\n- The GraphQL mutation `previewCampaignPlan` has been renamed to `createCampaignPlan`. This mutation is part of campaigns, which is still in beta and behind a feature flag and thus subject to possible breaking changes while we still work on it.\n- The GraphQL mutation `previewCampaignPlan` has been renamed to `createCampaignPlan`. This mutation is part of the campaigns feature, which is still in beta and behind a feature flag and thus subject to possible breaking changes while we still work on it.\n- The GraphQL field `CampaignPlan.changesets` has been deprecated and will be removed in 3.15. A new field called `CampaignPlan.changesetPlans` has been introduced to make the naming more consistent with the `Campaign.changesetPlans` field. Please use that instead. [#7966](https://github.com/sourcegraph/sourcegraph/pull/7966)\n- Long lines (>2000 bytes) are no longer highlighted, in order to prevent performance issues in browser rendering. [#6489](https://github.com/sourcegraph/sourcegraph/issues/6489)\n- No longer requires `read:org` permissions for GitHub OAuth if `allowOrgs` is not enabled in the site configuration. [#8163](https://github.com/sourcegraph/sourcegraph/issues/8163)\n- [Documentation](https://github.com/sourcegraph/deploy-sourcegraph/blob/master/configure/jaeger/README.md) in github.com/sourcegraph/deploy-sourcegraph for deploying Jaeger in Kubernetes clusters running Sourcegraph has been updated to use the [Jaeger Operator](https://www.jaegertracing.io/docs/1.16/operator/), the recommended standard way of deploying Jaeger in a Kubernetes cluster. We recommend existing customers that use Jaeger adopt this new method of deployment. Please reach out to support@sourcegraph.com if you'd like assistance updating.", "### Fixed", "- The syntax highlighter (syntect-server) no longer fails when run in environments without IPv6 support. [#8463](https://github.com/sourcegraph/sourcegraph/pull/8463)\n- After adding/removing a gitserver replica the admin interface will correctly report that repositories that need to move replicas as cloning. [#7970](https://github.com/sourcegraph/sourcegraph/issues/7970)\n- Show download button for images. [#7924](https://github.com/sourcegraph/sourcegraph/issues/7924)\n- gitserver backoffs trying to re-clone repositories if they fail to clone. In the case of large monorepos that failed this lead to gitserver constantly cloning them and using many resources. [#7804](https://github.com/sourcegraph/sourcegraph/issues/7804)\n- It is now possible to escape spaces using `\\` in the search queries when using regexp. [#7604](https://github.com/sourcegraph/sourcegraph/issues/7604)\n- Clicking filter chips containing whitespace is now correctly quoted in the web UI. [#6498](https://github.com/sourcegraph/sourcegraph/issues/6498)\n- **Monitoring:** Fixed an issue with the **Frontend** -> **Search responses by status** panel which caused search response types to not be aggregated as expected. [#7627](https://github.com/sourcegraph/sourcegraph/issues/7627)\n- **Monitoring:** Fixed an issue with the **Replacer**, **Repo Updater**, and **Searcher** dashboards would incorrectly report on a metric from the unrelated query-runner service. [#7531](https://github.com/sourcegraph/sourcegraph/issues/7531)\n- Deterministic ordering of results from indexed search. Previously when refreshing a page with many results some results may come and go.\n- Spread out periodic git reclones. Previously we would reclone all git repositories every 45 days. We now add in a jitter of 12 days to spread out the load for larger installations. [#8259](https://github.com/sourcegraph/sourcegraph/issues/8259)\n- Fixed an issue with missing commit information in graphql search results. [#8343](https://github.com/sourcegraph/sourcegraph/pull/8343)", "### Removed", "- All repository fields related to `enabled` and `disabled` have been removed from the GraphQL API. These fields have been deprecated since 3.4. [#3971](https://github.com/sourcegraph/sourcegraph/pull/3971)\n- The deprecated extension API `Hover.__backcompatContents` was removed.", "## 3.12.10", "This release backports the fixes released in `3.13.2` for customers still on `3.12`.", "### Fixed", "- The default timeout of indexed search has been increased. Previously indexed search would always return within 3s. This lead to broken behaviour on new instances which had yet to tune resource allocations. [#8720](https://github.com/sourcegraph/sourcegraph/pull/8720)\n- Bitbucket Server older than 5.13 failed to sync since Sourcegraph 3.12. This was due to us querying for the `archived` label, but Bitbucket Server 5.13 does not support labels. [#8883](https://github.com/sourcegraph/sourcegraph/issues/8883)\n- A regression in repo-updater was fixed that lead to every repository's git clone being updated every time the list of repositories was synced from the code host. [#8501](https://github.com/sourcegraph/sourcegraph/issues/8501)", "## 3.12.9", "This is `3.12.8` release with internal infrastructure fixes to publish the docker images.", "## 3.12.8", "### Fixed", "- Extension API showInputBox and other Window methods now work on search results pages [#8519](https://github.com/sourcegraph/sourcegraph/issues/8519)\n- Extension error notification styling is clearer [#8521](https://github.com/sourcegraph/sourcegraph/issues/8521)", "## 3.12.7", "### Fixed", "- Campaigns now gracefully handle GitHub review dismissals when rendering the burndown chart.", "## 3.12.6", "### Changed", "- When GitLab permissions are turned on using GitLab OAuth authentication, GitLab project visibility is fetched in batches, which is generally more efficient than fetching them individually. The `minBatchingThreshold` and `maxBatchRequests` fields of the `authorization.identityProvider` object in the GitLab repositories configuration control when such batch fetching is used. [#8171](https://github.com/sourcegraph/sourcegraph/pull/8171)", "## 3.12.5", "### Fixed", "- Fixed an internal race condition in our Docker build process. The previous patch version 3.12.4 contained an lsif-server version that was newer than expected. The affected artifacts have since been removed from the Docker registry.", "## 3.12.4", "### Added", "- New optional `apiURL` configuration option for Bitbucket Cloud code host connection [#8082](https://github.com/sourcegraph/sourcegraph/pull/8082)", "## 3.12.3", "### Fixed", "- Fixed an issue in `sourcegraph/*` Docker images where data folders were either not created or had incorrect permissions - preventing the use of Docker volumes. [#7991](https://github.com/sourcegraph/sourcegraph/pull/7991)", "## 3.12.2", "### Added", "- Experimental: The site configuration field `campaigns.readAccess.enabled` allows site-admins to give read-only access for code change campaigns to non-site-admins. This is a setting for the experimental feature campaigns and will only have an effect when campaigns are enabled under `experimentalFeatures`. [#8013](https://github.com/sourcegraph/sourcegraph/issues/8013)", "### Fixed", "- A regression in 3.12.0 which caused [find-leaked-credentials campaigns](https://docs.sourcegraph.com/user/campaigns#finding-leaked-credentials) to not return any results for private repositories. [#7914](https://github.com/sourcegraph/sourcegraph/issues/7914)\n- Experimental: The site configuration field `campaigns.readAccess.enabled` allows site-admins to give read-only access for campaigns to non-site-admins. This is a setting for the experimental campaigns feature and will only have an effect when campaigns is enabled under `experimentalFeatures`. [#8013](https://github.com/sourcegraph/sourcegraph/issues/8013)", "### Fixed", "- A regression in 3.12.0 which caused find-leaked-credentials campaigns to not return any results for private repositories. [#7914](https://github.com/sourcegraph/sourcegraph/issues/7914)\n- A regression in 3.12.0 which removed the horizontal bar between search result matches.\n- Manual campaigns were wrongly displayed as being in draft mode. [#8009](https://github.com/sourcegraph/sourcegraph/issues/8009)\n- Manual campaigns could be published and create the wrong changesets on code hosts, even though the campaign was never in draft mode (see line above). [#8012](https://github.com/sourcegraph/sourcegraph/pull/8012)\n- A regression in 3.12.0 which caused manual campaigns to not properly update the UI after adding a changeset. [#8023](https://github.com/sourcegraph/sourcegraph/pull/8023)\n- Minor improvements to manual campaign form fields. [#8033](https://github.com/sourcegraph/sourcegraph/pull/8033)", "## 3.12.1", "### Fixed", "- The ephemeral `/site-config.json` escape-hatch config file has moved to `$HOME/site-config.json`, to support non-root container environments. [#7873](https://github.com/sourcegraph/sourcegraph/issues/7873)\n- Fixed an issue where repository permissions would sometimes not be cached, due to improper Redis nil value handling. [#7912](https://github.com/sourcegraph/sourcegraph/issues/7912)", "## 3.12.0", "### Added", "- Bitbucket Server repositories with the label `archived` can be excluded from search with `archived:no` [syntax](https://docs.sourcegraph.com/code_search/reference/queries). [#5494](https://github.com/sourcegraph/sourcegraph/issues/5494)\n- Add button to download file in code view. [#5478](https://github.com/sourcegraph/sourcegraph/issues/5478)\n- The new `allowOrgs` site config setting in GitHub `auth.providers` enables admins to restrict GitHub logins to members of specific GitHub organizations. [#4195](https://github.com/sourcegraph/sourcegraph/issues/4195)\n- Support case field in repository search. [#7671](https://github.com/sourcegraph/sourcegraph/issues/7671)\n- Skip LFS content when cloning git repositories. [#7322](https://github.com/sourcegraph/sourcegraph/issues/7322)\n- Hover tooltips and _Find Reference_ results now display a badge to indicate when a result is search-based. These indicators can be disabled by adding `{ \"experimentalFeatures\": { \"showBadgeAttachments\": false } }` in global settings.\n- Campaigns can now be created as drafts, which can be shared and updated without creating changesets (pull requests) on code hosts. When ready, a draft can then be published, either completely or changeset by changeset, to create changesets on the code host. [#7659](https://github.com/sourcegraph/sourcegraph/pull/7659)\n- Experimental: feature flag `BitbucketServerFastPerm` can be enabled to speed up fetching ACL data from Bitbucket Server instances. This requires [Bitbucket Server Sourcegraph plugin](https://github.com/sourcegraph/bitbucket-server-plugin) to be installed.\n- Experimental: A site configuration field `{ \"experimentalFeatures\" { \"tls.external\": { \"insecureSkipVerify\": true } } }` which allows you to configure SSL/TLS settings for Sourcegraph contacting your code hosts. Currently just supports turning off TLS/SSL verification. [#71](https://github.com/sourcegraph/sourcegraph/issues/71)\n- Experimental: To search across multiple revisions of the same repository, list multiple branch names (or other revspecs) separated by `:` in your query, as in `repo:myrepo@branch1:branch2:branch2`. To search all branches, use `repo:myrepo@*refs/heads/`. Requires the site configuration value `{ \"experimentalFeatures\": { \"searchMultipleRevisionsPerRepository\": true } }`. Previously this was only supported for diff and commit searches.\n- Experimental: interactive search mode, which helps users construct queries using UI elements. Requires the site configuration value `{ \"experimentalFeatures\": { \"splitSearchModes\": true } }`. The existing plain text search format is still available via the dropdown menu on the left of the search bar.\n- A case sensitivity toggle now appears in the search bar.\n- Add explicit repository permissions support with site configuration field `{ \"permissions.userMapping\" { \"enabled\": true, \"bindID\": \"email\" } }`.", "### Changed", "- The \"Files\" tab in the search results page has been renamed to \"Filenames\" for clarity.\n- The search query builder now lives on its own page at `/search/query-builder`. The home search page has a link to it.\n- User passwords when using builtin auth are limited to 256 characters. Existing passwords longer than 256 characters will continue to work.\n- GraphQL API: Campaign.changesetCreationStatus has been renamed to Campaign.status to be aligned with CampaignPlan. [#7654](https://github.com/sourcegraph/sourcegraph/pull/7654)\n- When using GitHub as an authentication provider, `read:org` scope is now required. This is used to support the new `allowOrgs` site config setting in the GitHub `auth.providers` configuration, which enables site admins to restrict GitHub logins to members of a specific GitHub organization. This for example allows having a Sourcegraph instance with GitHub sign in configured be exposed to the public internet without allowing everyone with a GitHub account access to your Sourcegraph instance.", "### Fixed", "- The experimental search pagination API no longer times out when large repositories are encountered. [#6384](https://github.com/sourcegraph/sourcegraph/issues/6384)\n- We resolve relative symbolic links from the directory of the symlink, rather than the root of the repository. [#6034](https://github.com/sourcegraph/sourcegraph/issues/6034)\n- Show errors on repository settings page when repo-updater is down. [#3593](https://github.com/sourcegraph/sourcegraph/issues/3593)\n- Remove benign warning that verifying config took more than 10s when updating or saving an external service. [#7176](https://github.com/sourcegraph/sourcegraph/issues/7176)\n- repohasfile search filter works again (regressed in 3.10). [#7380](https://github.com/sourcegraph/sourcegraph/issues/7380)\n- Structural search can now run on very large repositories containing any number of files. [#7133](https://github.com/sourcegraph/sourcegraph/issues/7133)", "### Removed", "- The deprecated GraphQL mutation `setAllRepositoriesEnabled` has been removed. [#7478](https://github.com/sourcegraph/sourcegraph/pull/7478)\n- The deprecated GraphQL mutation `deleteRepository` has been removed. [#7483](https://github.com/sourcegraph/sourcegraph/pull/7483)", "## 3.11.4", "### Fixed", "- The `/.auth/saml/metadata` endpoint has been fixed. Previously it panicked if no encryption key was set.\n- The version updating logic has been fixed for `sourcegraph/server`. Users running `sourcegraph/server:3.11.1` will need to manually modify their `docker run` command to use `sourcegraph/server:3.11.4` or higher. [#7442](https://github.com/sourcegraph/sourcegraph/issues/7442)", "## 3.11.1", "### Fixed", "- The syncing process for newly created campaign changesets has been fixed again after they have erroneously been marked as deleted in the database. [#7522](https://github.com/sourcegraph/sourcegraph/pull/7522)\n- The syncing process for newly created changesets (in campaigns) has been fixed again after they have erroneously been marked as deleted in the database. [#7522](https://github.com/sourcegraph/sourcegraph/pull/7522)", "## 3.11.0", "**Important:** If you use `SITE_CONFIG_FILE` or `CRITICAL_CONFIG_FILE`, please be sure to follow the steps in: [migration notes for Sourcegraph v3.11+](https://docs.sourcegraph.com/admin/migration/3_11.md) after upgrading.", "### Added", "- Language statistics by commit are available via the API. [#6737](https://github.com/sourcegraph/sourcegraph/pull/6737)\n- Added a new page that shows [language statistics for the results of a search query](https://docs.sourcegraph.com/user/search#statistics).\n- Global settings can be configured from a local file using the environment variable `GLOBAL_SETTINGS_FILE`.\n- High-level health metrics and dashboards have been added to Sourcegraph's monitoring (found under the **Site admin** -> **Monitoring** area). [#7216](https://github.com/sourcegraph/sourcegraph/pull/7216)\n- Logging for GraphQL API requests not issued by Sourcegraph is now much more verbose, allowing for easier debugging of problematic queries and where they originate from. [#5706](https://github.com/sourcegraph/sourcegraph/issues/5706)\n- A new campaign type finds and removes leaked NPM credentials. [#6893](https://github.com/sourcegraph/sourcegraph/pull/6893)\n- Campaigns can now be retried to create failed changesets due to ephemeral errors (e.g. network problems when creating a pull request on GitHub). [#6718](https://github.com/sourcegraph/sourcegraph/issues/6718)\n- The initial release of [structural code search](https://docs.sourcegraph.com/code_search/reference/structural).", "### Changed", "- `repohascommitafter:` search filter uses a more efficient git command to determine inclusion. [#6739](https://github.com/sourcegraph/sourcegraph/pull/6739)\n- `NODE_NAME` can be specified instead of `HOSTNAME` for zoekt-indexserver. `HOSTNAME` was a confusing configuration to use in [Pure-Docker Sourcegraph deployments](https://github.com/sourcegraph/deploy-sourcegraph-docker). [#6846](https://github.com/sourcegraph/sourcegraph/issues/6846)\n- The feedback toast now requests feedback every 60 days of usage (was previously only once on the 3rd day of use). [#7165](https://github.com/sourcegraph/sourcegraph/pull/7165)\n- The lsif-server container now only has a dependency on Postgres, whereas before it also relied on Redis. [#6880](https://github.com/sourcegraph/sourcegraph/pull/6880)\n- Renamed the GraphQL API `LanguageStatistics` fields to `name`, `totalBytes`, and `totalLines` (previously the field names started with an uppercase letter, which was inconsistent).\n- Detecting a file's language uses a more accurate but slower algorithm. To revert to the old (faster and less accurate) algorithm, set the `USE_ENHANCED_LANGUAGE_DETECTION` env var to the string `false` (on the `sourcegraph/server` container, or if using the cluster deployment, on the `sourcegraph-frontend` pod).\n- Diff and commit searches that make use of `before:` and `after:` filters to narrow their search area are now no longer subject to the 50-repository limit. This allows for creating saved searches on more than 50 repositories as before. [#7215](https://github.com/sourcegraph/sourcegraph/issues/7215)", "### Fixed", "- Changes to external service configurations are reflected much faster. [#6058](https://github.com/sourcegraph/sourcegraph/issues/6058)\n- Deleting an external service will not show warnings for the non-existent service. [#5617](https://github.com/sourcegraph/sourcegraph/issues/5617)\n- Suggested search filter chips are quoted if necessary. [#6498](https://github.com/sourcegraph/sourcegraph/issues/6498)\n- Remove potential panic in gitserver if heavily loaded. [#6710](https://github.com/sourcegraph/sourcegraph/issues/6710)\n- Multiple fixes to make the preview and creation of campaigns more robust and a smoother user experience. [#6682](https://github.com/sourcegraph/sourcegraph/pull/6682) [#6625](https://github.com/sourcegraph/sourcegraph/issues/6625) [#6658](https://github.com/sourcegraph/sourcegraph/issues/6658) [#7088](https://github.com/sourcegraph/sourcegraph/issues/7088) [#6766](https://github.com/sourcegraph/sourcegraph/issues/6766) [#6717](https://github.com/sourcegraph/sourcegraph/issues/6717) [#6659](https://github.com/sourcegraph/sourcegraph/issues/6659)\n- Repositories referenced in campaigns that are removed in an external service configuration change won't lead to problems with the syncing process anymore. [#7015](https://github.com/sourcegraph/sourcegraph/pull/7015)\n- The Searcher dashboard (and the `src_graphql_search_response` Prometheus metric) now properly account for search alerts instead of them being incorrectly added to the `timeout` category. [#7214](https://github.com/sourcegraph/sourcegraph/issues/7214)\n- In the experimental search pagination API, the `cloning`, `missing`, and other repository fields now return a well-defined set of results. [#6000](https://github.com/sourcegraph/sourcegraph/issues/6000)", "### Removed", "- The management console has been removed. All critical configuration previously stored in the management console will be automatically migrated to your site configuration. For more information about this change, or if you use `SITE_CONFIG_FILE` / `CRITICAL_CONFIG_FILE`, please see the [migration notes for Sourcegraph v3.11+](https://docs.sourcegraph.com/admin/migration/3_11.md).", "## 3.10.4", "### Fixed", "- An issue where diff/commit searches that would run over more than 50 repositories would incorrectly display a timeout error instead of the correct error suggesting users scope their query to less repositories. [#7090](https://github.com/sourcegraph/sourcegraph/issues/7090)", "## 3.10.3", "### Fixed", "- A critical regression in 3.10.2 which caused diff, commit, and repository searches to timeout. [#7090](https://github.com/sourcegraph/sourcegraph/issues/7090)\n- A critical regression in 3.10.2 which caused \"No results\" to appear frequently on pages with search results. [#7095](https://github.com/sourcegraph/sourcegraph/pull/7095)\n- An issue where the built-in Grafana Searcher dashboard would show duplicate success/error metrics. [#7078](https://github.com/sourcegraph/sourcegraph/pull/7078)", "## 3.10.2", "### Added", "- Site admins can now use the built-in Grafana Searcher dashboard to observe how many search requests are successful, or resulting in errors or timeouts. [#6756](https://github.com/sourcegraph/sourcegraph/issues/6756)", "### Fixed", "- When searches timeout, a consistent UI with clear actions like a button to increase the timeout is now returned. [#6754](https://github.com/sourcegraph/sourcegraph/issues/6754)\n- To reduce the chance of search timeouts in some cases, the default indexed search timeout has been raised from 1.5s to 3s. [#6754](https://github.com/sourcegraph/sourcegraph/issues/6754)\n- We now correctly inform users of the limitations of diff/commit search. If a diff/commit search would run over more than 50 repositories, users will be shown an error suggesting they scope their search to less repositories using the `repo:` filter. Global diff/commit search support is being tracked in [#6826](https://github.com/sourcegraph/sourcegraph/issues/6826). [#5519](https://github.com/sourcegraph/sourcegraph/issues/5519)", "## 3.10.1", "### Added", "- Syntax highlighting for Starlark (Bazel) files. [#6827](https://github.com/sourcegraph/sourcegraph/issues/6827)", "### Fixed", "- The experimental search pagination API no longer times out when large repositories are encountered. [#6384](https://github.com/sourcegraph/sourcegraph/issues/6384) [#6383](https://github.com/sourcegraph/sourcegraph/issues/6383)\n- In single-container deployments, the builtin `postgres_exporter` now correctly respects externally configured databases. This previously caused PostgreSQL metrics to not show up in Grafana when an external DB was in use. [#6735](https://github.com/sourcegraph/sourcegraph/issues/6735)", "## 3.10.0", "### Added", "- Indexed Search supports horizontally scaling. Instances with large number of repositories can update the `replica` field of the `indexed-search` StatefulSet. See [configure indexed-search replica count](https://github.com/sourcegraph/deploy-sourcegraph/blob/master/docs/configure.md#configure-indexed-search-replica-count). [#5725](https://github.com/sourcegraph/sourcegraph/issues/5725)\n- Bitbucket Cloud external service supports `exclude` config option. [#6035](https://github.com/sourcegraph/sourcegraph/issues/6035)\n- `sourcegraph/server` Docker deployments now support the environment variable `IGNORE_PROCESS_DEATH`. If set to true the container will keep running, even if a subprocess has died. This is useful when manually fixing problems in the container which the container refuses to start. For example a bad database migration.\n- Search input now offers filter type suggestions [#6105](https://github.com/sourcegraph/sourcegraph/pull/6105).\n- The keyboard shortcut <kbd>Ctrl</kbd>+<kbd>Space</kbd> in the search input shows a list of available filter types.\n- Sourcegraph Kubernetes cluster site admins can configure PostgreSQL by specifying `postgresql.conf` via ConfigMap. [sourcegraph/deploy-sourcegraph#447](https://github.com/sourcegraph/deploy-sourcegraph/pull/447)", "### Changed", "- **Required Kubernetes Migration:** The [Kubernetes deployment](https://github.com/sourcegraph/deploy-sourcegraph) manifest for indexed-search services has changed from a Normal Service to a Headless Service. This is to enable Sourcegraph to individually resolve indexed-search pods. Services are immutable, so please follow the [migration guide](https://github.com/sourcegraph/deploy-sourcegraph/blob/master/docs/migrate.md#310).\n- Fields of type `String` in our GraphQL API that contain [JSONC](https://komkom.github.io/) now have the custom scalar type `JSONCString`. [#6209](https://github.com/sourcegraph/sourcegraph/pull/6209)\n- `ZOEKT_HOST` environment variable has been deprecated. Please use `INDEXED_SEARCH_SERVERS` instead. `ZOEKT_HOST` will be removed in 3.12.\n- Directory names on the repository tree page are now shown in bold to improve readability.\n- Added support for Bitbucket Server pull request activity to the [campaign](https://about.sourcegraph.com/product/code-change-management/) burndown chart. When used, this feature leads to more requests being sent to Bitbucket Server, since Sourcegraph needs to keep track of how a pull request's state changes over time. With [the instance scoped webhooks](https://docs.google.com/document/d/1I3Aq1WSUh42BP8KvKr6AlmuCfo8tXYtJu40WzdNT6go/edit) in our [Bitbucket Server plugin](https://github.com/sourcegraph/bitbucket-server-plugin/pull/10) as well as up-coming [heuristical syncing changes](#6389), this additional load will be significantly reduced in the future.\n- Added support for Bitbucket Server pull request activity to the campaign burndown chart. When used, this feature leads to more requests being sent to Bitbucket Server, since Sourcegraph needs to keep track of how a pull request's state changes over time. With [the instance scoped webhooks](https://docs.google.com/document/d/1I3Aq1WSUh42BP8KvKr6AlmuCfo8tXYtJu40WzdNT6go/edit) in our [Bitbucket Server plugin](https://github.com/sourcegraph/bitbucket-server-plugin/pull/10) as well as up-coming [heuristical syncing changes](#6389), this additional load will be significantly reduced in the future.", "### Fixed", "- Support hyphens in Bitbucket Cloud team names. [#6154](https://github.com/sourcegraph/sourcegraph/issues/6154)\n- Server will run `redis-check-aof --fix` on startup to fix corrupted AOF files. [#651](https://github.com/sourcegraph/sourcegraph/issues/651)\n- Authorization provider configuration errors in external services will be shown as site alerts. [#6061](https://github.com/sourcegraph/sourcegraph/issues/6061)", "### Removed", "## 3.9.4", "### Changed", "- The experimental search pagination API's `PageInfo` object now returns a `String` instead of an `ID` for its `endCursor`, and likewise for the `after` search field. Experimental paginated search API users may need to update their usages to replace `ID` cursor types with `String` ones.", "### Fixed", "- The experimental search pagination API no longer omits a single repository worth of results at the end of the result set. [#6286](https://github.com/sourcegraph/sourcegraph/issues/6286)\n- The experimental search pagination API no longer produces search cursors that can get \"stuck\". [#6287](https://github.com/sourcegraph/sourcegraph/issues/6287)\n- In literal search mode, searching for quoted strings now works as expected. [#6255](https://github.com/sourcegraph/sourcegraph/issues/6255)\n- In literal search mode, quoted field values now work as expected. [#6271](https://github.com/sourcegraph/sourcegraph/pull/6271)\n- `type:path` search queries now correctly work in indexed search again. [#6220](https://github.com/sourcegraph/sourcegraph/issues/6220)", "## 3.9.3", "### Changed", "- Sourcegraph is now built using Go 1.13.3 [#6200](https://github.com/sourcegraph/sourcegraph/pull/6200).", "## 3.9.2", "### Fixed", "- URI-decode the username, password, and pathname when constructing Postgres connection paramers in lsif-server [#6174](https://github.com/sourcegraph/sourcegraph/pull/6174). Fixes a crashing lsif-server process for users with passwords containing special characters.", "## 3.9.1", "### Changed", "- Reverted [#6094](https://github.com/sourcegraph/sourcegraph/pull/6094) because it introduced a minor security hole involving only Grafana.\n [#6075](https://github.com/sourcegraph/sourcegraph/issues/6075) will be fixed with a different approach.", "## 3.9.0", "### Added", "- Our external service syncing model will stream in new repositories to Sourcegraph. Previously we could only add a repository to our database and clone it once we had synced all information from all external services (to detect deletions and renames). Now adding a repository to an external service configuration should be reflected much sooner, even on large instances. [#5145](https://github.com/sourcegraph/sourcegraph/issues/5145)\n- There is now an easy way for site admins to view and export settings and configuration when reporting a bug. The page for doing so is at /site-admin/report-bug, linked to from the site admin side panel under \"Report a bug\".\n- An experimental search pagination API to enable better programmatic consumption of search results is now available to try. For more details and known limitations see [the documentation](https://docs.sourcegraph.com/api/graphql/search).\n- Search queries can now be interpreted literally.\n - There is now a dot-star icon in the search input bar to toggle the pattern type of a query between regexp and literal.\n - There is a new `search.defaultPatternType` setting to configure the default pattern type, regexp or literal, for searches.\n - There is a new `patternType:` search token which overrides the `search.defaultPatternType` setting, and the active state of the dot-star icon in determining the pattern type of the query.\n - Old URLs without a patternType URL parameter will be redirected to the same URL with\n patternType=regexp appended to preserve intended behavior.\n- Added support for GitHub organization webhooks to enable faster updates of metadata used by [campaigns](https://about.sourcegraph.com/product/code-change-management/), such as pull requests or issue comments. See the [GitHub webhook documentation](https://docs.sourcegraph.com/admin/external_service/github#webhooks) for instructions on how to enable webhooks.\n- Added support for GitHub organization webhooks to enable faster updates of changeset metadata used by campaigns. See the [GitHub webhook documentation](https://docs.sourcegraph.com/admin/external_service/github#webhooks) for instructions on how to enable webhooks.\n- Added burndown chart to visualize progress of campaigns.\n- Added ability to edit campaign titles and descriptions.", "### Changed", "- **Recommended Kubernetes Migration:** The [Kubernetes deployment](https://github.com/sourcegraph/deploy-sourcegraph) manifest for indexed-search pods has changed from a Deployment to a StatefulSet. This is to enable future work on horizontally scaling indexed search. To retain your existing indexes there is a [migration guide](https://github.com/sourcegraph/deploy-sourcegraph/blob/master/docs/migrate.md#39).\n- Allow single trailing hyphen in usernames and org names [#5680](https://github.com/sourcegraph/sourcegraph/pull/5680)\n- Indexed search won't spam the logs on startup if the frontend API is not yet available. [zoekt#30](https://github.com/sourcegraph/zoekt/pull/30), [#5866](https://github.com/sourcegraph/sourcegraph/pull/5866)\n- Search query fields are now case insensitive. For example `repoHasFile:` will now be recognized, not just `repohasfile:`. [#5168](https://github.com/sourcegraph/sourcegraph/issues/5168)\n- Search queries are now interpreted literally by default, rather than as regular expressions. [#5899](https://github.com/sourcegraph/sourcegraph/pull/5899)\n- The `search` GraphQL API field now takes a two new optional parameters: `version` and `patternType`. `version` determines the search syntax version to use, and `patternType` determines the pattern type to use for the query. `version` defaults to \"V1\", which is regular expression searches by default, if not explicitly passed in. `patternType` overrides the pattern type determined by version.\n- Saved searches have been updated to support the new patternType filter. All existing saved searches have been updated to append `patternType:regexp` to the end of queries to ensure deterministic results regardless of the patternType configurations on an instance. All new saved searches are required to have a `patternType:` field in the query.\n- Allow text selection in search result headers (to allow for e.g. copying filenames)", "### Fixed", "- Web app: Fix paths with special characters (#6050)\n- Fixed an issue that rendered the search filter `repohascommitafter` unusable in the presence of an empty repository. [#5149](https://github.com/sourcegraph/sourcegraph/issues/5149)\n- An issue where `externalURL` not being configured in the management console could go unnoticed. [#3899](https://github.com/sourcegraph/sourcegraph/issues/3899)\n- Listing branches and refs now falls back to a fast path if there are a large number of branches. Previously we would time out. [#4581](https://github.com/sourcegraph/sourcegraph/issues/4581)\n- Sourcegraph will now ignore the ambiguous ref HEAD if a repository contains it. [#5291](https://github.com/sourcegraph/sourcegraph/issues/5291)", "### Removed", "## 3.8.2", "### Fixed", "- Sourcegraph cluster deployments now run a more stable syntax highlighting server which can self-recover from rarer failure cases such as getting stuck at high CPU usage when highlighting some specific files. [#5406](https://github.com/sourcegraph/sourcegraph/issues/5406) This will be ported to single-container deployments [at a later date](https://github.com/sourcegraph/sourcegraph/issues/5841).", "## 3.8.1", "### Added", "- Add `nameTransformations` setting to GitLab external service to help transform repository name that shows up in the Sourcegraph UI.", "## 3.8.0", "### Added", "- A toggle button for browser extension to quickly enable/disable the core functionality without actually enable/disable the entire extension in the browser extension manager.\n- Tabs to easily toggle between the different search result types on the search results page.", "### Changed", "- A `hardTTL` setting was added to the [Bitbucket Server `authorization` config](https://docs.sourcegraph.com/admin/external_service/bitbucketserver#configuration). This setting specifies a duration after which a user's cached permissions must be updated before any user action is authorized. This contrasts with the already existing `ttl` setting which defines a duration after which a user's cached permissions will get updated in the background, but the previously cached (and now stale) permissions are used to authorize any user action occuring before the update concludes. If your previous `ttl` value is larger than the default of the new `hardTTL` setting (i.e. **3 days**), you must change the `ttl` to be smaller or, `hardTTL` to be larger.", "### Fixed", "### Removed", "- The `statusIndicator` feature flag has been removed from the site configuration's `experimentalFeatures` section. The status indicator has been enabled by default since 3.6.0 and you can now safely remove the feature flag from your configuration.\n- Public usage is now only available on Sourcegraph.com. Because many core features rely on persisted user settings, anonymous usage leads to a degraded experience for most users. As a result, for self-hosted private instances it is preferable for all users to have accounts. But on sourcegraph.com, users will continue to have to opt-in to accounts, despite the degraded UX.", "## 3.7.2", "### Added", "- A [migration guide for Sourcegraph v3.7+](https://docs.sourcegraph.com/admin/migration/3_7.md).", "### Fixed", "- Fixed an issue where some repositories with very long symbol names would fail to index after v3.7.\n- We now retain one prior search index version after an upgrade, meaning upgrading AND downgrading from v3.6.2 <-> v3.7.2 is now 100% seamless and involves no downtime or negated search performance while repositories reindex. Please refer to the [v3.7+ migration guide](https://docs.sourcegraph.com/admin/migration/3_7.md) for details.", "## 3.7.1", "### Fixed", "- When re-indexing repositories, we now continue to serve from the old index in the meantime. Thus, you can upgrade to 3.7.1 without downtime.\n- Indexed symbol search is now faster, as we've fixed a performance issue that occurred when many repositories without any symbols existed.\n- Indexed symbol search now uses less disk space when upgrading directly to v3.7.1 as we properly remove old indexes.", "## 3.7.0", "### Added", "- Indexed search now supports symbol queries. This feature will require re-indexing all repositories. This will increase the disk and memory usage of indexed search by roughly 10%. You can disable the feature with the configuration `search.index.symbols.enabled`. [#3534](https://github.com/sourcegraph/sourcegraph/issues/3534)\n- Multi-line search now works for non-indexed search. [#4518](https://github.com/sourcegraph/sourcegraph/issues/4518)\n- When using `SITE_CONFIG_FILE` and `EXTSVC_CONFIG_FILE`, you [may now also specify e.g. `SITE_CONFIG_ALLOW_EDITS=true`](https://docs.sourcegraph.com/admin/config/advanced_config_file) to allow edits to be made to the config in the application which will be overwritten on the next process restart. [#4912](https://github.com/sourcegraph/sourcegraph/issues/4912)", "### Changed", "- In the [GitHub external service config](https://docs.sourcegraph.com/admin/external_service/github#configuration) it's now possible to specify `orgs` without specifying `repositoryQuery` or `repos` too.\n- Out-of-the-box TypeScript code intelligence is much better with an updated ctags version with a built-in TypeScript parser.\n- Sourcegraph uses Git protocol version 2 for increased efficiency and performance when fetching data from compatible code hosts.\n- Searches with `repohasfile:` are faster at finding repository matches. [#4833](https://github.com/sourcegraph/sourcegraph/issues/4833).\n- Zoekt now runs with GOGC=50 by default, helping to reduce the memory consumption of Sourcegraph. [#3792](https://github.com/sourcegraph/sourcegraph/issues/3792)\n- Upgraded the version of Go in use, which improves security for publicly accessible Sourcegraph instances.", "### Fixed", "- Disk cleanup in gitserver is now done in terms of percentages to fix [#5059](https://github.com/sourcegraph/sourcegraph/issues/5059).\n- Search results now correctly show highlighting of matches with runes like 'İ' that lowercase to runes with a different number of bytes in UTF-8 [#4791](https://github.com/sourcegraph/sourcegraph/issues/4791).\n- Fixed an issue where search would sometimes crash with a panic due to a nil pointer. [#5246](https://github.com/sourcegraph/sourcegraph/issues/5246)", "### Removed", "## 3.6.2", "### Fixed", "- Fixed Phabricator external services so they won't stop the syncing process for repositories when Phabricator doesn't return clone URLs. [#5101](https://github.com/sourcegraph/sourcegraph/pull/5101)", "## 3.6.1", "### Added", "- New site config option `branding.brandName` configures the brand name to display in the Sourcegraph \\<title\\> element.\n- `repositoryPathPattern` option added to the \"Other\" external service type for repository name customization.", "## 3.6.0", "### Added", "- The `github.exclude` setting in [GitHub external service config](https://docs.sourcegraph.com/admin/external_service/github#configuration) additionally allows you to specify regular expressions with `{\"pattern\": \"regex\"}`.\n- A new [`quicklinks` setting](https://docs.sourcegraph.com/user/personalization/quick_links) allows adding links to be displayed on the homepage and search page for all users (or users in an organization).\n- Compatibility with the [Sourcegraph for Bitbucket Server](https://github.com/sourcegraph/bitbucket-server-plugin) plugin.\n- Support for [Bitbucket Cloud](https://bitbucket.org) as an external service.", "### Changed", "- Updating or creating an external service will no longer block until the service is synced.\n- The GraphQL fields `Repository.createdAt` and `Repository.updatedAt` are deprecated and will be removed in 3.8. Now `createdAt` is always the current time and updatedAt is always null.\n- In the [GitHub external service config](https://docs.sourcegraph.com/admin/external_service/github#configuration) and [Bitbucket Server external service config](https://docs.sourcegraph.com/admin/external_service/bitbucket_server#permissions) `repositoryQuery` is now only required if `repos` is not set.\n- Log messages from query-runner when saved searches fail now include the raw query as part of the message.\n- The status indicator in the navigation bar is now enabled by default\n- Usernames and org names can now contain the `.` character. [#4674](https://github.com/sourcegraph/sourcegraph/issues/4674)", "### Fixed", "- Commit searches now correctly highlight unicode characters, for example 加. [#4512](https://github.com/sourcegraph/sourcegraph/issues/4512)\n- Symbol searches now show the number of symbol matches rather than the number of file matches found. [#4578](https://github.com/sourcegraph/sourcegraph/issues/4578)\n- Symbol searches with truncated results now show a `+` on the results page to signal that some results have been omitted. [#4579](https://github.com/sourcegraph/sourcegraph/issues/4579)", "## 3.5.4", "### Fixed", "- Fixed Phabricator external services so they won't stop the syncing process for repositories when Phabricator doesn't return clone URLs. [#5101](https://github.com/sourcegraph/sourcegraph/pull/5101)", "## 3.5.2", "### Changed", "- Usernames and org names can now contain the `.` character. [#4674](https://github.com/sourcegraph/sourcegraph/issues/4674)", "### Added", "- Syntax highlighting requests that fail are now logged and traced. A new Prometheus metric `src_syntax_highlighting_requests` allows monitoring and alerting. [#4877](https://github.com/sourcegraph/sourcegraph/issues/4877).\n- Sourcegraph's SAML authentication now supports RSA PKCS#1 v1.5. [#4869](https://github.com/sourcegraph/sourcegraph/pull/4869)", "### Fixed", "- Increased nginx proxy buffer size to fix issue where login failed when SAML AuthnRequest was too large. [#4849](https://github.com/sourcegraph/sourcegraph/pull/4849)\n- A regression in 3.3.8 where `\"corsOrigin\": \"*\"` was improperly forbidden. [#4424](https://github.com/sourcegraph/sourcegraph/issues/4424)", "## 3.5.1", "### Added", "- A new [`quicklinks` setting](https://docs.sourcegraph.com/user/personalization/quick_links) allows adding links to be displayed on the homepage and search page for all users (or users in an organization).\n- Site admins can prevent the icon in the top-left corner of the screen from spinning on hovers by setting `\"branding\": { \"disableSymbolSpin\": true }` in their site configuration.", "### Fixed", "- Fix `repository.language` GraphQL field (previously returned empty for most repositories).", "## 3.5.0", "### Added", "- Indexed search now supports matching consecutive literal newlines, with queries like e.g. `foo\\nbar.*` to search over multiple lines. [#4138](https://github.com/sourcegraph/sourcegraph/issues/4138)\n- The `orgs` setting in [GitHub external service config](https://docs.sourcegraph.com/admin/external_service/github) allows admins to select all repositories from the specified organizations to be synced.\n- A new experimental search filter `repohascommitafter:\"30 days ago\"` allows users to exclude stale repositories that don't contain commits (to the branch being searched over) past a specified date from their search query.\n- The `authorization` setting in the [Bitbucket Server external service config](https://docs.sourcegraph.com/admin/external_service/bitbucket_server#permissions) enables Sourcegraph to enforce the repository permissions defined in Bitbucket Server.\n- A new, experimental status indicator in the navigation bar allows admins to quickly see whether the configured repositories are up to date or how many are currently being updated in the background. You can enable the status indicator with the following site configuration: `\"experimentalFeatures\": { \"statusIndicator\": \"enabled\" }`.\n- A new search filter `repohasfile` allows users to filter results to just repositories containing a matching file. For example `ubuntu file:Dockerfile repohasfile:\\.py$` would find Dockerfiles mentioning Ubuntu in repositories that contain Python files. [#4501](https://github.com/sourcegraph/sourcegraph/pull/4501)", "### Changed", "- The saved searches UI has changed. There is now a Saved searches page in the user and organizations settings area. A saved search appears in the settings area of the user or organization it is associated with.", "### Removed", "### Fixed", "- Fixed repository search patterns which contain `.*`. Previously our optimizer would ignore `.*`, which in some cases would lead to our repository search excluding some repositories from the results.\n- Fixed an issue where the Phabricator native integration would be broken on recent Phabricator versions. This fix depends on v1.2 of the [Phabricator extension](https://github.com/sourcegraph/phabricator-extension).\n- Fixed an issue where the \"Empty repository\" banner would be shown on a repository page when starting to clone a repository.\n- Prevent data inconsistency on cached archives due to restarts. [#4366](https://github.com/sourcegraph/sourcegraph/pull/4366)\n- On the /extensions page, the UI is now less ambiguous when an extension has not been activated. [#4446](https://github.com/sourcegraph/sourcegraph/issues/4446)", "## 3.4.5", "### Fixed", "- Fixed an issue where syntax highlighting taking too long would result in errors or wait long amounts of time without properly falling back to plaintext rendering after a few seconds. [#4267](https://github.com/sourcegraph/sourcegraph/issues/4267) [#4268](https://github.com/sourcegraph/sourcegraph/issues/4268) (this fix was intended to be in 3.4.3, but was in fact left out by accident)\n- Fixed an issue with `sourcegraph/server` Docker deployments where syntax highlighting could produce `server closed idle connection` errors. [#4269](https://github.com/sourcegraph/sourcegraph/issues/4269) (this fix was intended to be in 3.4.3, but was in fact left out by accident)\n- Fix `repository.language` GraphQL field (previously returned empty for most repositories).", "## 3.4.4", "### Fixed", "- Fixed an out of bounds error in the GraphQL repository query. [#4426](https://github.com/sourcegraph/sourcegraph/issues/4426)", "## 3.4.3", "### Fixed", "- Improved performance of the /site-admin/repositories page significantly (prevents timeouts). [#4063](https://github.com/sourcegraph/sourcegraph/issues/4063)\n- Fixed an issue where Gitolite repositories would be inaccessible to non-admin users after upgrading to 3.3.0+ from an older version. [#4263](https://github.com/sourcegraph/sourcegraph/issues/4263)\n- Repository names are now treated as case-sensitive, fixing an issue where users saw `pq: duplicate key value violates unique constraint \\\"repo_name_unique\\\"` [#4283](https://github.com/sourcegraph/sourcegraph/issues/4283)\n- Repositories containing submodules not on Sourcegraph will now load without error [#2947](https://github.com/sourcegraph/sourcegraph/issues/2947)\n- HTTP metrics in Prometheus/Grafana now distinguish between different types of GraphQL requests.", "## 3.4.2", "### Fixed", "- Fixed incorrect wording in site-admin onboarding. [#4127](https://github.com/sourcegraph/sourcegraph/issues/4127)", "## 3.4.1", "### Added", "- You may now specify `DISABLE_CONFIG_UPDATES=true` on the management console to prevent updates to the critical configuration. This is useful when loading critical config via a file using `CRITICAL_CONFIG_FILE` on the frontend.", "### Changed", "- When `EXTSVC_CONFIG_FILE` or `SITE_CONFIG_FILE` are specified, updates to external services and the site config are now prevented.\n- Site admins will now see a warning if creating or updating an external service was successful but the process could not complete entirely due to an ephemeral error (such as GitHub API search queries running into timeouts and returning incomplete results).", "### Removed", "### Fixed", "- Fixed an issue where `EXTSVC_CONFIG_FILE` being specified would incorrectly cause a panic.\n- Fixed an issue where user/org/global settings from old Sourcegraph versions (2.x) could incorrectly be null, leading to various errors.\n- Fixed an issue where an ephemeral infrastructure error (`tar/archive: invalid tar header`) would fail a search.", "## 3.4.0", "### Added", "- When `repositoryPathPattern` is configured, paths from the full long name will redirect to the configured name. Extensions will function with the configured name. `repositoryPathPattern` allows administrators to configure \"nice names\". For example `sourcegraph.example.com/github.com/foo/bar` can configured to be `sourcegraph.example.com/gh/foo/bar` with `\"repositoryPathPattern\": \"gh/{nameWithOwner}\"`. (#462)\n- Admins can now turn off site alerts for patch version release updates using the `alerts.showPatchUpdates` setting. Alerts will still be shown for major and minor version updates.\n- The new `gitolite.exclude` setting in [Gitolite external service config](https://docs.sourcegraph.com/admin/external_service/gitolite#configuration) allows you to exclude specific repositories by their Gitolite name so that they won't be mirrored. Upon upgrading, previously \"disabled\" repositories will be automatically migrated to this exclusion list.\n- The new `aws_codecommit.exclude` setting in [AWS CodeCommit external service config](https://docs.sourcegraph.com/admin/external_service/aws_codecommit#configuration) allows you to exclude specific repositories by their AWS name or ID so that they won't be synced. Upon upgrading, previously \"disabled\" repositories will be automatically migrated to this exclusion list.\n- Added a new, _required_ `aws_codecommit.gitCredentials` setting to the [AWS CodeCommit external service config](https://docs.sourcegraph.com/admin/external_service/aws_codecommit#configuration). These Git credentials are required to create long-lived authenticated clone URLs for AWS CodeCommit repositories. For more information about Git credentials, see the AWS CodeCommit documentation: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_ssh-keys.html#git-credentials-code-commit. For detailed instructions on how to create the credentials in IAM, see this page: https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-gc.html\n- Added support for specifying a URL formatted `gitolite.host` setting in [Gitolite external service config](https://docs.sourcegraph.com/admin/external_service/gitolite#configuration) (e.g. `ssh://git@gitolite.example.org:2222/`), in addition to the already supported SCP like format (e.g `git@gitolite.example.org`)\n- Added support for overriding critical, site, and external service configurations via files. Specify `CRITICAL_CONFIG_FILE=critical.json`, `SITE_CONFIG_FILE=site.json`, and/or `EXTSVC_CONFIG_FILE=extsvc.json` on the `frontend` container to do this.", "### Changed", "- Kinds of external services in use are now included in [server pings](https://docs.sourcegraph.com/admin/pings).\n- Bitbucket Server: An actual Bitbucket icon is now used for the jump-to-bitbucket action on repository pages instead of the previously generic icon.\n- Default config for GitHub, GitHub Enterprise, GitLab, Bitbucket Server, and AWS Code Commit external services has been revised to make it easier for first time admins.", "### Removed", "- Fields related to Repository enablement have been deprecated. Mutations are now NOOPs, and for repositories returned the value is always true for Enabled. The enabled field and mutations will be removed in 3.6. Mutations: `setRepositoryEnabled`, `setAllRepositoriesEnabled`, `updateAllMirrorRepositories`, `deleteRepository`. Query parameters: `repositories.enabled`, `repositories.disabled`. Field: `Repository.enabled`.\n- Global saved searches are now deprecated. Any existing global saved searches have been assigned to the Sourcegraph instance's first site admin's user account.\n- The `search.savedQueries` configuration option is now deprecated. Existing entries remain in user and org settings for backward compatibility, but are unused as saved searches are now stored in the database.", "### Fixed", "- Fixed a bug where submitting a saved query without selecting the location would fail for non-site admins (#3628).\n- Fixed settings editors only having a few pixels height.\n- Fixed a bug where browser extension and code review integration usage stats were not being captured on the site-admin Usage Stats page.\n- Fixed an issue where in some rare cases PostgreSQL starting up slowly could incorrectly trigger a panic in the `frontend` service.\n- Fixed an issue where the management console password would incorrectly reset to a new secure one after a user account was created.\n- Fixed a bug where gitserver would leak file descriptors when performing common operations.\n- Substantially improved the performance of updating Bitbucket Server external service configurations on instances with thousands of repositories, going from e.g. several minutes to about a minute for ~20k repositories (#4037).\n- Fully resolved the search performance regression in v3.2.0, restoring performance of search back to the same levels it was before changes made in v3.2.0.\n- Fix a bug where using a repo search filter with the prefix `github.com` only searched for repos whose name starts with `github.com`, even though no `^` was specified in the search filter. (#4103)\n- Fixed an issue where files that fail syntax highlighting would incorrectly render an error instead of gracefully falling back to their plaintext form.", "## 3.3.9", "### Added", "- Syntax highlighting requests that fail are now logged and traced. A new Prometheus metric `src_syntax_highlighting_requests` allows monitoring and alerting. [#4877](https://github.com/sourcegraph/sourcegraph/issues/4877).", "## 3.3.8", "### Fixed", "- Fully resolved the search performance regression in v3.2.0, restoring performance of search back to the same levels it was before changes made in v3.2.0.\n- Fixed an issue where files that fail syntax highlighting would incorrectly render an error instead of gracefully falling back to their plaintext form.\n- Fixed an issue introduced in v3.3 where Sourcegraph would under specific circumstances incorrectly have to re-clone and re-index repositories from Bitbucket Server and AWS CodeCommit.", "## 3.3.7", "### Added", "- The `bitbucketserver.exclude` setting in [Bitbucket Server external service config](https://docs.sourcegraph.com/admin/external_service/bitbucketserver#configuration) additionally allows you to exclude repositories matched by a regular expression (so that they won't be synced).", "### Changed", "### Removed", "### Fixed", "- Fixed a major indexed search performance regression that occurred in v3.2.0. (#3685)\n- Fixed an issue where Sourcegraph would fail to update repositories on some instances (`pq: duplicate key value violates unique constraint \"repo_external_service_unique_idx\"`) (#3680)\n- Fixed an issue where Sourcegraph would not exclude unavailable Bitbucket Server repositories. (#3772)", "## 3.3.6", "## Changed", "- All 24 language extensions are enabled by default.", "## 3.3.5", "## Changed", "- Indexed search is now enabled by default for new Docker deployments. (#3540)", "### Removed", "- Removed smart-casing behavior from search.", "### Fixed", "- Removes corrupted archives in the searcher cache and tries to populate the cache again instead of returning an error.\n- Fixed a bug where search scopes would not get merged, and only the lowest-level list of search scopes would appear.\n- Fixed an issue where repo-updater was slower in performing its work which could sometimes cause other performance issues. https://github.com/sourcegraph/sourcegraph/pull/3633", "## 3.3.4", "### Fixed", "- Fixed bundling of the Phabricator integration assets in the Sourcegraph docker image.", "## 3.3.3", "### Fixed", "- Fixed bug that prevented \"Find references\" action from being completed in the activation checklist.", "## 3.3.2", "### Fixed", "- Fixed an issue where the default `bitbucketserver.repositoryQuery` would not be created on migration from older Sourcegraph versions. https://github.com/sourcegraph/sourcegraph/issues/3591\n- Fixed an issue where Sourcegraph would add deleted repositories to the external service configuration. https://github.com/sourcegraph/sourcegraph/issues/3588\n- Fixed an issue where a repo-updater migration would hit code host rate limits. https://github.com/sourcegraph/sourcegraph/issues/3582\n- The required `bitbucketserver.username` field of a [Bitbucket Server external service configuration](https://docs.sourcegraph.com/admin/external_service/bitbucketserver#configuration), if unset or empty, is automatically migrated to match the user part of the `url` (if defined). https://github.com/sourcegraph/sourcegraph/issues/3592\n- Fixed a panic that would occur in indexed search / the frontend when a search error ocurred. https://github.com/sourcegraph/sourcegraph/issues/3579\n- Fixed an issue where the repo-updater service could become deadlocked while performing a migration. https://github.com/sourcegraph/sourcegraph/issues/3590", "## 3.3.1", "### Fixed", "- Fixed a bug that prevented external service configurations specifying client certificates from working (#3523)", "## 3.3.0", "### Added", "- In search queries, treat `foo(` as `foo\\(` and `bar[` as `bar\\[` rather than failing with an error message.\n- Enterprise admins can now customize the appearance of the homepage and search icon.\n- A new settings property `notices` allows showing custom informational messages on the homepage and at the top of each page. The `motd` property is deprecated and its value is automatically migrated to the new `notices` property.\n- The new `gitlab.exclude` setting in [GitLab external service config](https://docs.sourcegraph.com/admin/external_service/gitlab#configuration) allows you to exclude specific repositories matched by `gitlab.projectQuery` and `gitlab.projects` (so that they won't be synced). Upon upgrading, previously \"disabled\" repositories will be automatically migrated to this exclusion list.\n- The new `gitlab.projects` setting in [GitLab external service config](https://docs.sourcegraph.com/admin/external_service/gitlab#configuration) allows you to select specific repositories to be synced.\n- The new `bitbucketserver.exclude` setting in [Bitbucket Server external service config](https://docs.sourcegraph.com/admin/external_service/bitbucketserver#configuration) allows you to exclude specific repositories matched by `bitbucketserver.repositoryQuery` and `bitbucketserver.repos` (so that they won't be synced). Upon upgrading, previously \"disabled\" repositories will be automatically migrated to this exclusion list.\n- The new `bitbucketserver.repos` setting in [Bitbucket Server external service config](https://docs.sourcegraph.com/admin/external_service/bitbucketserver#configuration) allows you to select specific repositories to be synced.\n- The new required `bitbucketserver.repositoryQuery` setting in [Bitbucket Server external service configuration](https://docs.sourcegraph.com/admin/external_service/bitbucketserver#configuration) allows you to use Bitbucket API repository search queries to select repos to be synced. Existing configurations will be migrate to have it set to `[\"?visibility=public\", \"?visibility=private\"]` which is equivalent to the previous implicit behaviour that this setting supersedes.\n- \"Quick configure\" buttons for common actions have been added to the config editor for all external services.\n- \"Quick configure\" buttons for common actions have been added to the management console.\n- Site-admins now receive an alert every day for the seven days before their license key expires.\n- The user menu (in global nav) now lists the user's organizations.\n- All users on an instance now see a non-dismissable alert when when there's no license key in use and the limit of free user accounts is exceeded.\n- All users will see a dismissible warning about limited search performance and accuracy on when using the sourcegraph/server Docker image with more than 100 repositories enabled.", "### Changed", "- Indexed searches that time out more consistently report a timeout instead of erroneously saying \"No results.\"\n- The symbols sidebar now only shows symbols defined in the current file or directory.\n- The dynamic filters on search results pages will now display `lang:` instead of `file:` filters for language/file-extension filter suggestions.\n- The default `github.repositoryQuery` of a [GitHub external service configuration](https://docs.sourcegraph.com/admin/external_service/github#configuration) has been changed to `[\"none\"]`. Existing configurations that had this field unset will be migrated to have the previous default explicitly set (`[\"affiliated\", \"public\"]`).\n- The default `gitlab.projectQuery` of a [GitLab external service configuration](https://docs.sourcegraph.com/admin/external_service/gitlab#configuration) has been changed to `[\"none\"]`. Existing configurations that had this field unset will be migrated to have the previous default explicitly set (`[\"?membership=true\"]`).\n- The default value of `maxReposToSearch` is now unlimited (was 500).\n- The default `github.repositoryQuery` of a [GitHub external service configuration](https://docs.sourcegraph.com/admin/external_service/github#configuration) has been changed to `[\"none\"]` and is now a required field. Existing configurations that had this field unset will be migrated to have the previous default explicitly set (`[\"affiliated\", \"public\"]`).\n- The default `gitlab.projectQuery` of a [GitLab external service configuration](https://docs.sourcegraph.com/admin/external_service/gitlab#configuration) has been changed to `[\"none\"]` and is now a required field. Existing configurations that had this field unset will be migrated to have the previous default explicitly set (`[\"?membership=true\"]`).\n- The `bitbucketserver.username` field of a [Bitbucket Server external service configuration](https://docs.sourcegraph.com/admin/external_service/bitbucketserver#configuration) is now **required**. This field is necessary to authenticate with the Bitbucket Server API with either `password` or `token`.\n- The settings and account pages for users and organizations are now combined into a single tab.", "### Removed", "- Removed the option to show saved searches on the Sourcegraph homepage.", "### Fixed", "- Fixed an issue where the site-admin repositories page `Cloning`, `Not Cloned`, `Needs Index` tabs were very slow on instances with thousands of repositories.\n- Fixed an issue where failing to syntax highlight a single file would take down the entire syntax highlighting service.", "## 3.2.6", "### Fixed", "- Fully resolved the search performance regression in v3.2.0, restoring performance of search back to the same levels it was before changes made in v3.2.0.", "## 3.2.5", "### Fixed", "- Fixed a major indexed search performance regression that occurred in v3.2.0. (#3685)", "## 3.2.4", "### Fixed", "- Fixed bundling of the Phabricator integration assets in the Sourcegraph docker image.", "## 3.2.3", "### Fixed", "- Fixed https://github.com/sourcegraph/sourcegraph/issues/3336.\n- Clearer error message when a repository sync fails due to the inability to clone a repository.\n- Rewrite '@' character in Gitolite repository names to '-', which permits them to be viewable in the UI.", "## 3.2.2", "### Changed", "- When using an external Zoekt instance (specified via the `ZOEKT_HOST` environment variable), sourcegraph/server no longer spins up a redundant internal Zoekt instance.", "## 3.2.1", "### Fixed", "- Jaeger tracing, once enabled, can now be configured via standard [environment variables](https://github.com/jaegertracing/jaeger-client-go/blob/v2.14.0/README.md#environment-variables).\n- Fixed an issue where some search and zoekt errors would not be logged.", "## 3.2.0", "### Added", "- Sourcegraph can now automatically use the system's theme.\n To enable, open the user menu in the top right and make sure the theme dropdown is set to \"System\".\n This is currently supported on macOS Mojave with Safari Technology Preview 68 and later.\n- The `github.exclude` setting was added to the [GitHub external service config](https://docs.sourcegraph.com/admin/external_service/github#configuration) to allow excluding repositories yielded by `github.repos` or `github.repositoryQuery` from being synced.", "### Changed", "- Symbols search is much faster now. After the initial indexing, you can expect code intelligence to be nearly instant no matter the size of your repository.\n- Massively reduced the number of code host API requests Sourcegraph performs, which caused rate limiting issues such as slow search result loading to appear.\n- The [`corsOrigin`](https://docs.sourcegraph.com/admin/config/site_config) site config property is no longer needed for integration with GitHub, GitLab, etc., via the [Sourcegraph browser extension](https://docs.sourcegraph.com/integration/browser_extension). Only the [Phabricator extension](https://github.com/sourcegraph/phabricator-extension) requires it.", "### Fixed", "- Fixed a bug where adding a search scope that adds a `repogroup` filter would cause invalid queries if `repogroup:sample` was already part of the query.\n- An issue where errors during displaying search results would not be displayed.", "### Removed", "- The `\"updateScheduler2\"` experiment is now the default and it's no longer possible to configure.", "## 3.1.2", "### Added", "- The `search.contextLines` setting was added to allow configuration of the number of lines of context to be displayed around search results.", "### Changed", "- Massively reduced the number of code host API requests Sourcegraph performs, which caused rate limiting issues such as slow search result loading to appear.\n- Improved logging in various situations where Sourcegraph would potentially hit code host API rate limits.", "### Fixed", "- Fixed an issue where search results loading slowly would display a `Cannot read property \"lastChild\" of undefined` error.", "## 3.1.1", "### Added", "- Query builder toggle (open/closed) state is now retained.", "### Fixed", "- Fixed an issue where single-term values entered into the \"Exact match\" field in the query builder were not getting wrapped in quotes.", "## 3.1.0", "### Added", "- Added Docker-specific help text when running the Sourcegraph docker image in an environment with an sufficient open file descriptor limit.\n- Added syntax highlighting for Kotlin and Dart.\n- Added a management console environment variable to disable HTTPS, see [the docs](https://docs.sourcegraph.com/admin/management_console.md#can-i-disable-https-on-the-management-console) for more information.\n- Added `auth.disableUsernameChanges` to critical configuration to prevent users from changing their usernames.\n- Site admins can query a user by email address or username from the GraphQL API.\n- Added a search query builder to the main search page. Click \"Use search query builder\" to open the query builder, which is a form with separate inputs for commonly used search keywords.", "### Changed", "- File match search results now show full repository name if there are results from mirrors on different code hosts (e.g. github.com/sourcegraph/sourcegraph and gitlab.com/sourcegraph/sourcegraph)\n- Search queries now use \"smart case\" by default. Searches are case insensitive unless you use uppercase letters. To explicitly set the case, you can still use the `case` field (e.g. `case:yes`, `case:no`). To explicitly set smart case, use `case:auto`.", "### Fixed", "- Fixed an issue where the management console would improperly regenerate the TLS cert/key unless `CUSTOM_TLS=true` was set. See the documentation for [how to use your own TLS certificate with the management console](https://docs.sourcegraph.com/admin/management_console.md#how-can-i-use-my-own-tls-certificates-with-the-management-console).", "## 3.0.1", "### Added", "- Symbol search now supports Elixir, Haskell, Kotlin, Scala, and Swift", "### Changed", "- Significantly optimized how file search suggestions are provided when using indexed search (cluster deployments).\n- Both the `sourcegraph/server` image and the [Kubernetes deployment](https://github.com/sourcegraph/deploy-sourcegraph) manifests ship with Postgres `11.1`. For maximum compatibility, however, the minimum supported version remains `9.6`. The upgrade procedure is mostly automated for existing deployments. Please refer to [this page](https://docs.sourcegraph.com/admin/postgres) for detailed instructions.", "### Removed", "- The deprecated `auth.disableAccessTokens` site config property was removed. Use `auth.accessTokens` instead.\n- The `disableBrowserExtension` site config property was removed. [Configure nginx](https://docs.sourcegraph.com/admin/nginx) instead to block clients (if needed).", "## 3.0.0", "See the changelog entries for 3.0.0 beta releases and our [3.0](https://docs.sourcegraph.com/admin/migration/3_0.md) upgrade guide if you are upgrading from 2.x.", "## 3.0.0-beta.4", "### Added", "- Basic code intelligence for the top 10 programming languages works out of the box without any configuration. [TypeScript/JavaScript](https://sourcegraph.com/extensions/sourcegraph/typescript), [Python](https://sourcegraph.com/extensions/sourcegraph/python), [Java](https://sourcegraph.com/extensions/sourcegraph/java), [Go](https://sourcegraph.com/extensions/sourcegraph/go), [C/C++](https://sourcegraph.com/extensions/sourcegraph/cpp), [Ruby](https://sourcegraph.com/extensions/sourcegraph/ruby), [PHP](https://sourcegraph.com/extensions/sourcegraph/php), [C#](https://sourcegraph.com/extensions/sourcegraph/csharp), [Shell](https://sourcegraph.com/extensions/sourcegraph/shell), and [Scala](https://sourcegraph.com/extensions/sourcegraph/scala) are enabled by default, and you can find more in the [extension registry](https://sourcegraph.com/extensions?query=category%3A\"Programming+languages\").", "## 3.0.0-beta.3", "- Fixed an issue where the site admin is redirected to the start page instead of being redirected to the repositories overview page after deleting a repo.", "## 3.0.0-beta", "### Added", "- Repositories can now be queried by a git clone URL through the GraphQL API.\n- A new Explore area is linked from the top navigation bar (when the `localStorage.explore=true;location.reload()` feature flag is enabled).\n- Authentication via GitHub is now supported. To enable, add an item to the `auth.providers` list with `type: \"github\"`. By default, GitHub identities must be linked to an existing Sourcegraph user account. To enable new account creation via GitHub, use the `allowSignup` option in the `GitHubConnection` config.\n- Authentication via GitLab is now supported. To enable, add an item to the `auth.providers` list with `type: \"gitlab\"`.\n- GitHub repository permissions are supported if authentication via GitHub is enabled. See the\n documentation for the `authorization` field of the `GitHubConnection` configuration.\n- The repository settings mirroring page now shows when a repo is next scheduled for an update (requires experiment `\"updateScheduler2\": \"enabled\"`).\n- Configured repositories are periodically scheduled for updates using a new algorithm. You can disable the new algorithm with the following site configuration: `\"experimentalFeatures\": { \"updateScheduler2\": \"disabled\" }`. If you do so, please file a public issue to describe why you needed to disable it.\n- When using HTTP header authentication, [`stripUsernameHeaderPrefix`](https://docs.sourcegraph.com/admin/auth/#username-header-prefixes) field lets an admin specify a prefix to strip from the HTTP auth header when converting the header value to a username.\n- Sourcegraph extensions whose package.json contains `\"wip\": true` are considered [work-in-progress extensions](https://docs.sourcegraph.com/extensions/authoring/publishing#wip-extensions) and are indicated as such to avoid users accidentally using them.\n- Information about user survey submissions and a chart showing weekly active users is now displayed on the site admin Overview page.\n- A new GraphQL API field `UserEmail.isPrimary` was added that indicates whether an email is the user's primary email.\n- The filters bar in the search results page can now display filters from extensions.\n- Extensions' `activate` functions now receive a `sourcegraph.ExtensionContext` parameter (i.e., `export function activate(ctx: sourcegraph.ExtensionContext): void { ... }`) to support deactivation and running multiple extensions in the same process.\n- Users can now request an Enterprise trial license from the site init page.\n- When searching, a filter button `case:yes` will now appear when relevant. This helps discovery and makes it easier to use our case-sensitive search syntax.\n- Extensions can now report progress in the UI through the `withProgress()` extension API.\n- When calling `editor.setDecorations()`, extensions must now provide an instance of `TextDocumentDecorationType` as first argument. This helps gracefully displaying decorations from several extensions.", "### Changed", "- The Postgres database backing Sourcegraph has been upgraded from 9.4 to 11.1. Existing Sourcegraph users must conduct an [upgrade procedure](https://docs.sourcegraph.com/admin/postgres_upgrade)\n- Code host configuration has moved out of the site config JSON into the \"External services\" area of the site admin web UI. Sourcegraph instances will automatically perform a one time migration of existing data in the site config JSON. After the migration these keys can be safely deleted from the site config JSON: `awsCodeCommit`, `bitbucketServer`, `github`, `gitlab`, `gitolite`, and `phabricator`.\n- Site and user usage statistics are now visible to all users. Previously only site admins (and users, for their own usage statistics) could view this information. The information consists of aggregate counts of actions such as searches, page views, etc.\n- The Git blame information shown at the end of a line is now provided by the [Git extras extension](https://sourcegraph.com/extensions/sourcegraph/git-extras). You must add that extension to continue using this feature.\n- The `appURL` site configuration option was renamed to `externalURL`.\n- The repository and directory pages now show all entries together instead of showing files and (sub)directories separately.\n- Extensions no longer can specify titles (in the `title` property in the `package.json` extension manifest). Their extension ID (such as `alice/myextension`) is used.", "### Fixed", "- Fixed an issue where the site admin License page showed a count of current users, rather than the max number of users over the life of the license.\n- Fixed number formatting issues on site admin Overview and Survey Response pages.\n- Fixed resolving of git clone URLs with `git+` prefix through the GraphQL API\n- Fixed an issue where the graphql Repositories endpoint would order by a field which was not indexed. Times on Sourcegraph.com went from 10s to 200ms.\n- Fixed an issue where whitespace was not handled properly in environment variable lists (`SYMBOLS_URL`, `SEARCHER_URL`).\n- Fixed an issue where clicking inside the repository popover or clicking \"Show more\" would dismiss the popover.", "### Removed", "- The `siteID` site configuration option was removed because it is no longer needed. If you previously specified this in site configuration, a new, random site ID will be generated upon server startup. You can safely remove the existing `siteID` value from your site configuration after upgrading.\n- The **Info** panel was removed. The information it presented can be viewed in the hover.\n- The top-level `repos.list` site configuration was removed in favour of each code-host's equivalent options,\n now configured via the new _External Services UI_ available at `/site-admin/external-services`. Equivalent options in code hosts configuration:\n - GitHub via [`github.repos`](https://docs.sourcegraph.com/admin/site_config/all#repos-array)\n - Gitlab via [`gitlab.projectQuery`](https://docs.sourcegraph.com/admin/site_config/all#projectquery-array)\n - Phabricator via [`phabricator.repos`](https://docs.sourcegraph.com/admin/site_config/all#phabricator-array)\n - [Other external services](https://docs.sourcegraph.com/admin/repo/add_from_other_external_services)\n- Removed the `httpStrictTransportSecurity` site configuration option. Use [nginx configuration](https://docs.sourcegraph.com/admin/nginx) for this instead.\n- Removed the `tls.letsencrypt` site configuration option. Use [nginx configuration](https://docs.sourcegraph.com/admin/nginx) for this instead.\n- Removed the `tls.cert` and `tls.key` site configuration options. Use [nginx configuration](https://docs.sourcegraph.com/admin/nginx) for this instead.\n- Removed the `httpToHttpsRedirect` and `experimentalFeatures.canonicalURLRedireect` site configuration options. Use [nginx configuration](https://docs.sourcegraph.com/admin/nginx) for these instead.\n- Sourcegraph no longer requires access to `/var/run/docker.sock`.", "## 2.13.6", "### Added", "- The `/-/editor` endpoint now accepts a `hostname_patterns` URL parameter, which specifies a JSON\n object mapping from hostname to repository name pattern. This serves as a hint to Sourcegraph when\n resolving git clone URLs to repository names. The name pattern is the same style as is used in\n code host configurations. The default value is `{hostname}/{path}`.", "## 2.13.5", "### Fixed", "- Fixed another issue where Sourcegraph would try to fetch more than the allowed number of repositories from AWS CodeCommit.", "## 2.13.4", "### Changed", "- The default for `experimentalFeatures.canonicalURLRedirect` in site config was changed back to `disabled` (to avoid [#807](https://github.com/sourcegraph/sourcegraph/issues/807)).", "## 2.13.3", "### Fixed", "- Fixed an issue that would cause the frontend health check endpoint `/healthz` to not respond. This only impacts Kubernetes deployments.\n- Fixed a CORS policy issue that caused requests to be rejected when they come from origins not in our [manifest.json](https://sourcegraph.com/github.com/sourcegraph/sourcegraph/-/blob/browser/src/extension/manifest.spec.json#L72) (i.e. requested via optional permissions by the user).\n- Fixed an issue that prevented `repositoryQuery` from working correctly on GitHub enterprise instances.", "## 2.13.2", "### Fixed", "- Fixed an issue where Sourcegraph would try to fetch more than the allowed number of repositories from AWS CodeCommit.", "## 2.13.1", "### Changed", "- The timeout when running `git ls-remote` to determine if a remote url is cloneable has been increased from 5s to 30s.\n- Git commands now use [version 2 of the Git wire protocol](https://opensource.googleblog.com/2018/05/introducing-git-protocol-version-2.html), which should speed up certain operations (e.g. `git ls-remote`, `git fetch`) when communicating with a v2 enabled server.", "## 2.13.0", "### Added", "- A new site config option `search.index.enabled` allows toggling on indexed search.\n- Search now uses [Sourcegraph extensions](https://docs.sourcegraph.com/extensions) that register `queryTransformer`s.\n- GitLab repository permissions are now supported. To enable this, you will need to set the `authz`\n field in the `GitLabConnection` configuration object and ensure that the access token set in the\n `token` field has both `sudo` and `api` scope.", "### Changed", "- When the `DEPLOY_TYPE` environment variable is incorrectly specified, Sourcegraph now shuts down and logs an error message.\n- The `experimentalFeatures.canonicalURLRedirect` site config property now defaults to `enabled`. Set it to `disabled` to disable redirection to the `appURL` from other hosts.\n- Updating `maxReposToSearch` site config no longer requires a server restart to take effect.\n- The update check page no longer shows an error if you are using an insiders build. Insiders builds will now notify site administrators that updates are available 40 days after the release date of the installed build.\n- The `github.repositoryQuery` site config property now accepts arbitrary GitHub repository searches.", "### Fixed", "- The user account sidebar \"Password\" link (to the change-password form) is now shown correctly.\n- Fixed an issue where GitHub rate limits were underutilized if the remaining\n rate limit dropped below 150.\n- Fixed an issue where GraphQL field `elapsedMilliseconds` returned invalid value on empty searches\n- Editor extensions now properly search the selection as a literal string, instead of incorrectly using regexp.\n- Fixed a bug where editing and deleting global saved searches was not possible.\n- In index search, if the search regex produces multiline matches, search results are still processed per line and highlighted correctly.\n- Go-To-GitHub and Go-To-GitLab buttons now link to the right branch, line and commit range.\n- Go-to-GitHub button links to default branch when no rev is given.\n- The close button in the panel header stays located on the top.\n- The Phabricator icon is now displayed correctly.\n- The view mode button in the BlobPage now shows the correct view mode to switch to.", "### Removed", "- The experimental feature flag to disable the new repo update scheduler has been removed.\n- The `experimentalFeatures.configVars` feature flag was removed.\n- The `experimentalFeatures.multipleAuthProviders` feature flag was removed because the feature is now always enabled.\n- The following deprecated auth provider configuration properties were removed: `auth.provider`, `auth.saml`, `auth.openIDConnect`, `auth.userIdentityHTTPHeader`, and `auth.allowSignup`. Use `auth.providers` for all auth provider configuration. (If you were still using the deprecated properties and had no `auth.providers` set, all access to your instance will be rejected until you manually set `auth.providers`.)\n- The deprecated site configuration properties `search.scopes` and `settings` were removed. Define search scopes and settings in global settings in the site admin area instead of in site configuration.\n- The `pendingContents` property has been removed from our GraphQL schema.\n- The **Explore** page was replaced with a **Repositories** search link in the top navigation bar.", "## 2.12.3", "### Fixed", "- Fixed an error that prevented users without emails from submitting satisfaction surveys.", "## 2.12.2", "### Fixed", "- Fixed an issue where private GitHub Enterprise repositories were not fetched.", "## 2.12.1", "### Fixed", "- We use GitHub's REST API to query affliated repositories. This API has wider support on older GitHub enterprise versions.\n- Fixed an issue that prevented users without email addresses from signing in (https://github.com/sourcegraph/sourcegraph/issues/426).", "## 2.12.0", "### Changed", "- Reduced the size of in-memory data structured used for storing search results. This should reduce the backend memory usage of large result sets.\n- Code intelligence is now provided by [Sourcegraph extensions](https://docs.sourcegraph.com/extensions). The extension for each language in the site configuration `langservers` property is automatically enabled.\n- Support for multiple authentication providers is now enabled by default. To disable it, set the `experimentalFeatures.multipleAuthProviders` site config option to `\"disabled\"`. This only applies to Sourcegraph Enterprise.\n- When using the `http-header` auth provider, valid auth cookies (from other auth providers that are currently configured or were previously configured) are now respected and will be used for authentication. These auth cookies also take precedence over the `http-header` auth. Previously, the `http-header` auth took precedence.\n- Bitbucket Server username configuration is now used to clone repositories if the Bitbucket Server API does not set a username.\n- Code discussions: On Sourcegraph.com / when `discussions.abuseProtection` is enabled in the site config, rate limits to thread creation, comment creation, and @mentions are now applied.", "### Added", "- Search syntax for filtering archived repositories. `archived:no` will exclude archived repositories from search results, `archived:only` will search over archived repositories only. This applies for GitHub and GitLab repositories.\n- A Bitbucket Server option to exclude personal repositories in the event that you decide to give an admin-level Bitbucket access token to Sourcegraph and do not want to create a bot account. See https://docs.sourcegraph.com/integration/bitbucket_server#excluding-personal-repositories for more information.\n- Site admins can now see when users of their Sourcegraph instance last used it via a code host integration (e.g. Sourcegraph browser extensions). Visit the site admin Analytics page (e.g. https://sourcegraph.example.com/site-admin/analytics) to view this information.\n- A new site config option `extensions.allowRemoteExtensions` lets you explicitly specify the remote extensions (from, e.g., Sourcegraph.com) that are allowed.\n- Pings now include a total count of user accounts.", "### Fixed", "- Files with the gitattribute `export-ignore` are no longer excluded for language analysis and search.\n- \"Discard changes?\" confirmation popup doesn't pop up every single time you try to navigate to a new page after editting something in the site settings page anymore.\n- Fixed an issue where Git repository URLs would sometimes be logged, potentially containing e.g. basic auth tokens.\n- Fixed date formatting on the site admin Analytics page.\n- File names of binary and large files are included in search results.", "### Removed", "- The deprecated environment variables `SRC_SESSION_STORE_REDIS` and `REDIS_MASTER_ENDPOINT` are no longer used to configure alternative redis endpoints. For more information, see \"[using external services with Sourcegraph](https://docs.sourcegraph.com/admin/external_services)\".", "## 2.11.1", "### Added", "- A new site config option `git.cloneURLToRepositoryName` specifies manual mapping from Git clone URLs to Sourcegraph repository names. This is useful, for example, for Git submodules that have local clone URLs.", "### Fixed", "- Slack notifications for saved searches have been fixed.", "## 2.11.0", "### Changed", "### Added", "- Support for ACME \"tls-alpn-01\" challenges to obtain LetsEncrypt certificates. Previously Sourcegraph only supported ACME \"http-01\" challenges which required port 80 to be accessible.\n- gitserver periodically removes stale lock files that git can leave behind.\n- Commits with empty trees no longer return 404.\n- Clients (browser/editor extensions) can now query configuration details from the `ClientConfiguration` GraphQL API.\n- The config field `auth.accessTokens.allow` allows or restricts use of access tokens. It can be set to one of three values: \"all-users-create\" (the default), \"none\" (all access tokens are disabled), and \"site-admin-create\" (access tokens are enabled, but only site admins can create new access tokens). The field `auth.disableAccessTokens` is now deprecated in favor of this new field.\n- A webhook endpoint now exists to trigger repository updates. For example, `curl -XPOST -H 'Authorization: token $ACCESS_TOKEN' $SOURCEGRAPH_ORIGIN/.api/repos/$REPO_URI/-/refresh`.\n- Git submodules entries in the file tree now link to the submodule repository.", "### Fixed", "- An issue / edge case where the Code Intelligence management admin page would incorrectly show language servers as `Running` when they had been removed from Docker.\n- Log level is respected in lsp-proxy logs.\n- Fixed an error where text searches could be routed to a faulty search worker.\n- Gitolite integration should correctly detect names which Gitolite would consider to be patterns, and not treat them as repositories.\n- repo-updater backs off fetches on a repo that's failing to fetch.\n- Attempts to add a repo with an empty string for the name are checked for and ignored.\n- Fixed an issue where non-site-admin authenticated users could modify global settings (not site configuration), other organizations' settings, and other users' settings.\n- Search results are rendered more eagerly, resulting in fewer blank file previews\n- An issue where automatic code intelligence would fail to connect to the underlying `lsp` network, leading to `dial tcp: lookup lang on 0.0.0.0:53: no such host` errors.\n- More useful error messages from lsp-proxy when a language server can't get a requested revision of a repository.\n- Creation of a new user with the same name as an existing organization (and vice versa) is prevented.", "### Removed", "## 2.10.5", "### Fixed", "- Slack notifications for saved searches have been fixed.", "## 2.10.4", "### Fixed", "- Fixed an issue that caused the frontend to return a HTTP 500 and log an error message like:\n ```\n lvl=eror msg=\"ui HTTP handler error response\" method=GET status_code=500 error=\"Post http://127.0.0.1:3182/repo-lookup: context canceled\"\n ```", "## 2.10.3", "### Fixed", "- The SAML AuthnRequest signature when using HTTP redirect binding is now computed using a URL query string with correct ordering of parameters. Previously, the ordering was incorrect and caused errors when the IdP was configured to check the signature in the AuthnRequest.", "## 2.10.2", "### Fixed", "- SAML IdP-initiated login previously failed with the IdP set a RelayState value. This now works.", "## 2.10.1", "### Changed", "- Most `experimentalFeatures` in the site configuration now respond to configuration changes live, without requiring a server restart. As usual, you will be prompted for a restart after saving your configuration changes if one is required.\n- Gravatar image avatars are no longer displayed for committers.", "## 2.10.0", "### Changed", "- In the file tree, if a directory that contains only a single directory is expanded, its child directory is now expanded automatically.", "### Fixed", "- Fixed an issue where `sourcegraph/server` would not start code intelligence containers properly when the `sourcegraph/server` container was shut down non-gracefully.\n- Fixed an issue where the file tree would return an error when navigating between repositories.", "## 2.9.4", "### Changed", "- Repo-updater has a new and improved scheduler for periodic repo fetches. If you have problems with it, you can revert to the old behavior by adding `\"experimentalFeatures\": { \"updateScheduler\": \"disabled\" }` to your `config.json`.\n- A once-off migration will run changing the layout of cloned repos on disk. This should only affect installations created January 2018 or before. There should be no user visible changes.\n- Experimental feature flag \"updateScheduler\" enables a smarter and less spammy algorithm for automatic repository updates.\n- It is no longer possible to disable code intelligence by unsetting the LSP_PROXY environment variable. Instead, code intelligence can be disabled per language on the site admin page (e.g. https://sourcegraph.example.com/site-admin/code-intelligence).\n- Bitbucket API requests made by Sourcegraph are now under a self-enforced API rate limit (since Bitbucket Server does not have a concept of rate limiting yet). This will reduce any chance of Sourcegraph slowing down or causing trouble for Bitbucket Server instances connected to it. The limits are: 7,200 total requests/hr, with a bucket size / maximum burst size of 500 requests.\n- Global, org, and user settings are now validated against the schema, so invalid settings will be shown in the settings editor with a red squiggly line.\n- The `http-header` auth provider now supports being used with other auth providers (still only when `experimentalFeatures.multipleAuthProviders` is `true`).\n- Periodic fetches of Gitolite-hosted repositories are now handled internally by repo-updater.", "### Added", "- The `log.sentry.dsn` field in the site config makes Sourcegraph log application errors to a Sentry instance.\n- Two new repository page hotkeys were added: <kbd>r</kbd> to open the repositories menu and <kbd>v</kbd> to open the revision selector.\n- Repositories are periodically (~45 days) recloned from the codehost. The codehost can be relied on to give an efficient packing. This is an alternative to running a memory and CPU intensive git gc and git prune.\n- The `auth.sessionExpiry` field sets the session expiration age in seconds (defaults to 90 days).", "### Fixed", "- Fixed a bug in the API console that caused it to display as a blank page in some cases.\n- Fixed cases where GitHub rate limit wasn't being respected.\n- Fixed a bug where scrolling in references, history, etc. file panels was not possible in Firefox.\n- Fixed cases where gitserver directory structure migration could fail/crash.\n- Fixed \"Generate access token\" link on user settings page. Previously, this link would 404.\n- Fixed a bug where the search query was not updated in the search bar when searching from the homepage.\n- Fixed a possible crash in github-proxy.\n- Fixed a bug where file matching for diff search was case sensitive by default.", "### Removed", "- `SOURCEGRAPH_CONFIG` environment variable has been removed. Site configuration is always read from and written to disk. You can configure the location by providing `SOURCEGRAPH_CONFIG_FILE`. The default path is `/etc/sourcegraph/config.json`.", "## 2.9.3", "### Changed", "- The search results page will merge duplicated lines of context.\n- The following deprecated site configuration properties have been removed: `github[].preemptivelyClone`, `gitOriginMap`, `phabricatorURL`, `githubPersonalAccessToken`, `githubEnterpriseURL`, `githubEnterpriseCert`, and `githubEnterpriseAccessToken`.\n- The `settings` field in the site config file is deprecated and will not be supported in a future release. Site admins should move those settings (if any) to global settings (in the site admin UI). Global settings are preferred to site config file settings because the former can be applied without needing to restart/redeploy the Sourcegraph server or cluster.", "### Fixed", "- Fixed a goroutine leak which occurs when search requests are canceled.\n- Console output should have fewer spurious line breaks.\n- Fixed an issue where it was not possible to override the `StrictHostKeyChecking` SSH option in the SSH configuration.\n- Cross-repository code intelligence indexing for non-Go languages is now working again (originally broken in 2.9.2).", "## 2.9.1", "### Fixed", "- Fixed an issue where saving an organization's configuration would hang indefinitely.", "## 2.9.0", "### Changed", "- Hover tooltips were rewritten to fix a couple of issues and are now much more robust, received a new design and show more information.\n- The `max:` search flag was renamed to `count:` in 2.8.8, but for backward compatibility `max:` has been added back as a deprecated alias for `count:`.\n- Drastically improved the performance / load time of the Code Intelligence site admin page.", "### Added", "- The site admin code intelligence page now displays an error or reason whenever language servers are unable to be managed from the UI or Sourcegraph API.\n- The ability to directly specify the root import path of a repository via `.sourcegraph/config.json` in the repo root, instead of relying on the heuristics of the Go language server to detect it.", "### Fixed", "- Configuring Bitbucket Server now correctly suppresses the the toast message \"Configure repositories and code hosts to add to Sourcegraph.\"\n- A bug where canonical import path comments would not be detected by the Go language server's heuristics under `cmd/` folders.\n- Fixed an issue where a repository would only be refreshed on demand by certain user actions (such as a page reload) and would otherwise not be updated when expected.\n- If a code host returned a repository-not-found or unauthorized error (to `repo-updater`) for a repository that previously was known to Sourcegraph, then in some cases a misleading \"Empty repository\" screen was shown. Now the repository is displayed as though it still existed, using cached data; site admins must explicitly delete repositories on Sourcegraph after they have been deleted on the code host.\n- Improved handling of GitHub API rate limit exhaustion cases. Cached repository metadata and Git data will be used to provide full functionality during this time, and log messages are more informative. Previously, in some cases, repositories would become inaccessible.\n- Fixed an issue where indexed search would sometimes not indicate that there were more results to show for a given file.\n- Fixed an issue where the code intelligence admin page would never finish loading language servers.", "## 2.9.0-pre0", "### Changed", "- Search scopes have been consolidated into the \"Filters\" bar on the search results page.\n- Usernames and organization names of up to 255 characters are allowed. Previously the max length was 38.", "### Fixed", "- The target commit ID of a Git tag object (i.e., not lightweight Git tag refs) is now dereferenced correctly. Previously the tag object's OID was given.\n- Fixed an issue where AWS Code Commit would hit the rate limit.\n- Fixed an issue where dismissing the search suggestions dropdown did not unfocus previously highlighted suggestions.\n- Fixed an issue where search suggestions would appear twice.\n- Indexed searches now return partial results if they timeout.\n- Git repositories with files whose paths contain `.git` path components are now usable (via indexed and non-indexed search and code intelligence). These corrupt repositories are rare and generally were created by converting some other VCS repository to Git (the Git CLI will forbid creation of such paths).\n- Various diff search performance improvements and bug fixes.\n- New Phabricator extension versions would used cached stylesheets instead of the upgraded version.\n- Fixed an issue where hovers would show an error for Rust and C/C++ files.", "### Added", "- The `sourcegraph/server` container now emits the most recent log message when redis terminates to make it easier to debug why redis stopped.\n- Organization invites (which allow users to invite other users to join organizations) are significantly improved. A new accept-invitation page was added.\n- The new help popover allows users to easily file issues in the Sourcegraph public issue tracker and view documentation.\n- An issue where Java files would be highlighted incorrectly if they contained JavaDoc blocks with an uneven number of opening/closing `*`s.", "### Removed", "- The `secretKey` site configuration value is no longer needed. It was only used for generating tokens for inviting a user to an organization. The invitation is now stored in the database associated with the recipient, so a secret token is no longer needed.\n- The `experimentalFeatures.searchTimeoutParameter` site configuration value has been removed. It defaulted to `enabled` in 2.8 and it is no longer possible to disable.", "### Added", "- Syntax highlighting for:\n - TOML files (including Go `Gopkg.lock` and Rust `Cargo.lock` files).\n - Rust files.\n - GraphQL files.\n - Protobuf files.\n - `.editorconfig` files.", "## 2.8.9", "### Changed", "- The \"invite user\" site admin page was moved to a sub-page of the users page (`/site-admin/users/new`).\n- It is now possible for a site admin to create a new user without providing an email address.", "### Fixed", "- Checks for whether a repo is cloned will no longer exhaust open file pools over time.", "### Added", "- The Phabricator extension shows code intelligence status and supports enabling / disabling code intelligence for files.", "## 2.8.8", "### Changed", "- Queries for repositories (in the explore, site admin repositories, and repository header dropdown) are matched on case-insensitive substrings, not using fuzzy matching logic.\n- HTTP Authorization headers with an unrecognized scheme are ignored; they no longer cause the HTTP request to be rejected with HTTP 401 Unauthorized and an \"Invalid Authorization header.\" error.\n- Renamed the `max` search flag to `count`. Searches that specify `count:` will fetch at least that number of results, or the full result set.\n- Bumped `lsp-proxy`'s `initialize` timeout to 3 minutes for every language.\n- Search results are now sorted by repository and file name.\n- More easily accessible \"Show more\" button at the top of the search results page.\n- Results from user satisfaction surveys are now always hosted locally and visible to admins. The `\"experimentalFeatures\": { \"hostSurveysLocally\" }` config option has been deprecated.\n- If the OpenID Connect authentication provider reports that a user's email address is not verified, the authentication attempt will fail.", "### Fixed", "- Fixed an issue where the search results page would not update its title.\n- The session cookie name is now `sgs` (not `sg-session`) so that Sourcegraph 2.7 and Sourcegraph 2.8 can be run side-by-side temporarily during a rolling update without clearing each other's session cookies.\n- Fixed the default hostnames of the C# and R language servers\n- Fixed an issue where deleting an organization prevented the creation of organizations with the name of the deleted organization.\n- Non-UTF8 encoded files (e.g. ISO-8859-1/Latin1, UTF16, etc) are now displayed as text properly rather than being detected as binary files.\n- Improved error message when lsp-proxy's initalize timeout occurs\n- Fixed compatibility issues and added [instructions for using Microsoft ADFS 2.1 and 3.0 for SAML authentication](https://docs.sourcegraph.com/admin/auth/saml_with_microsoft_adfs).\n- Fixed an issue where external accounts associated with deleted user accounts would still be returned by the GraphQL API. This caused the site admin external accounts page to fail to render in some cases.\n- Significantly reduced the number of code host requests for non github.com or gitlab.com repositories.", "### Added", "- The repository revisions popover now shows the target commit's last-committed/authored date for branches and tags.\n- Setting the env var `INSECURE_SAML_LOG_TRACES=1` on the server (or the `sourcegraph-frontend` pod in Kubernetes) causes all SAML requests and responses to be logged, which helps with debugging SAML.\n- Site admins can now view user satisfaction surveys grouped by user, in addition to chronological order, and aggregate summary values (including the average score and the net promoter score over the last 30 days) are now displayed.\n- The site admin overview page displays the site ID, the primary admin email, and premium feature usage information.\n- Added Haskell as an experimental language server on the code intelligence admin page.", "## 2.8.0", "### Changed", "- `gitMaxConcurrentClones` now also limits the concurrency of updates to repos in addition to the initial clone.\n- In the GraphQL API, `site.users` has been renamed to `users`, `site.orgs` has been renamed to `organizations`, and `site.repositories` has been renamed to `repositories`.\n- An authentication provider must be set in site configuration (see [authentication provider documentation](https://docs.sourcegraph.com/admin/auth)). Previously the server defaulted to builtin auth if none was set.\n- If a process dies inside the Sourcegraph container the whole container will shut down. We suggest operators configure a [Docker Restart Policy](https://docs.docker.com/config/containers/start-containers-automatically/#restart-policy-details) or a [Kubernetes Restart Policy](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy). Previously the container would operate in a degraded mode if a process died.\n- Changes to the `auth.public` site config are applied immediately in `sourcegraph/server` (no restart needed).\n- The new search timeout behavior is now enabled by default. Set `\"experimentalFeatures\": {\"searchTimeoutParameter\": \"disabled\"}` in site config to disable it.\n- Search includes files up to 1MB (previous limit was 512KB for unindexed search and 128KB for indexed search).\n- Usernames and email addresses reported by OpenID Connect and SAML auth providers are now trusted, and users will sign into existing Sourcegraph accounts that match on the auth provider's reported username or email.\n- The repository sidebar file tree is much, much faster on massive repositories (200,000+ files)\n- The SAML authentication provider was significantly improved. Users who were signed in using SAML previously will need to reauthenticate via SAML next time they visit Sourcegraph.\n- The SAML `serviceProviderCertificate` and `serviceProviderPrivateKey` site config properties are now optional.", "### Fixed", "- Fixed an issue where Index Search status page failed to render.\n- User data on the site admin Analytics page is now paginated, filterable by a user's recent activity, and searchable.\n- The link to the root of a repository in the repository header now preserves the revision you're currently viewing.\n- When using the `http-header` auth provider, signin/signup/signout links are now hidden.\n- Repository paths beginning with `go/` are no longer reservered by Sourcegraph.\n- Interpret `X-Forwarded-Proto` HTTP header when `httpToHttpsRedirect` is set to `load-balanced`.\n- Deleting a user account no longer prevents the creation of a new user account with the same username and/or association with authentication provider account (SAML/OpenID/etc.)\n- It is now possible for a user to verify an email address that was previously associated with now-deleted user account.\n- Diff searches over empty repositories no longer fail (this was not an issue for Sourcegraph cluster deployments).\n- Stray `tmp_pack_*` files from interrupted fetches should now go away.\n- When multiple `repo:` tokens match the same repo, process @revspec requirements from all of them, not just the first one in the search.", "### Removed", "- The `ssoUserHeader` site config property (deprecated since January 2018) has been removed. The functionality was moved to the `http-header` authentication provider.\n- The experiment flag `showMissingReposEnabled`, which defaulted to enabled, has been removed so it is no longer possible to disable this feature.\n- Event-level telemetry has been completely removed from self-hosted Sourcegraph instances. As a result, the `disableTelemetry` site configuration option has been deprecated. The new site-admin Pings page clarifies the only high-level telemetry being sent to Sourcegraph.com.\n- The deprecated `adminUsernames` site config property (deprecated since January 2018) has been removed because it is no longer necessary. Site admins can designate other users as site admins in the site admin area, and the first user to sign into a new instance always becomes a site admin (even when using an external authentication provider).", "### Added", "- The new repository contributors page (linked from the repository homepage) displays the top Git commit authors in a repository, with filtering options.\n- Custom language servers in the site config may now specify a `metadata` property containing things like homepage/docs/issues URLs for the language server project, as well as whether or not the language server should be considered experimental (not ready for prime-time). This `metadata` will be displayed in the UI to better communicate the status of a language server project.\n- Access tokens now have scopes (which define the set of operations they permit). All access tokens still provide full control of all resources associated with the user account (the `user:all` scope, which is now explicitly displayed).\n- The new access token scope `site-admin:sudo` allows the holder to perform any action as any other user. Only site admins may create this token.\n- Links to Sourcegraph's changelog have been added to the site admin Updates page and update alert.\n- If the site configuration is invalid or uses deprecated properties, a global alert will be shown to all site admins.\n- There is now a code intelligence status indicator when viewing files. It contains information about the capabailities of the language server that is providing code intelligence for the file.\n- Java code intelligence can now be enabled for repositories that aren't automatically supported using a\n `javaconfig.json` file. For Gradle plugins, this file can be generated using\n the [Javaconfig Gradle plugin](https://docs.sourcegraph.com/extensions/language_servers/java#gradle-execution).\n- The new `auth.providers` site config is an array of authentication provider objects. Currently only 1 auth provider is supported. The singular `auth.provider` is deprecated.\n- Users authenticated with OpenID Connect are now able to sign out of Sourcegraph (if the provider supports token revocation or the end-session endpoint).\n- Users can now specify the number of days, weeks, and months of site activity to query through the GraphQL API.\n- Added 14 new experimental language servers on the code intelligence admin page.\n- Added `httpStrictTransportSecurity` site configuration option to customize the Strict-Transport-Security HTTP header. It defaults to `max-age=31536000` (one year).\n- Added `nameIDFormat` in the `saml` auth provider to set the SAML NameID format. The default changed from transient to persistent.\n- (This feature has been removed.) Experimental env var expansion in site config JSON: set `SOURCEGRAPH_EXPAND_CONFIG_VARS=1` to replace `${var}` or `$var` (based on environment variables) in any string value in site config JSON (except for JSON object property names).\n- The new (optional) SAML `serviceProviderIssuer` site config property (in an `auth.providers` array entry with `{\"type\":\"saml\", ...}`) allows customizing the SAML Service Provider issuer name.\n- The site admin area now has an \"Auth\" section that shows the enabled authentication provider(s) and users' external accounts.", "## 2.7.6", "### Fixed", "- If a user's account is deleted, session cookies for that user are no longer considered valid.", "## 2.7.5", "### Changed", "- When deploying Sourcegraph to Kubernetes, RBAC is now used by default. Most Kubernetes clusters require it. See the Kubernetes installation instructions for more information (including disabling if needed).\n- Increased git ssh connection timeout to 30s from 7s.\n- The Phabricator integration no longer requires staging areas, but using them is still recommended because it improves performance.", "### Fixed", "- Fixed an issue where language servers that were not enabled would display the \"Restart\" button in the Code Intelligence management panel.\n- Fixed an issue where the \"Update\" button in the Code Intelligence management panel would be displayed inconsistently.\n- Fixed an issue where toggling a dynamic search scope would not also remove `@rev` (if specified)\n- Fixed an issue where where modes that can only be determined by the full filename (not just the file extension) of a path weren't supported (Dockerfiles are the first example of this).\n- Fixed an issue where the GraphiQL console failed when variables are specified.\n- Indexed search no longer maintains its own git clones. For Kubernetes cluster deployments, this significantly reduces disk size requirements for the indexed-search pod.\n- Fixed an issue where language server Docker containers would not be automatically restarted if they crashed (`sourcegraph/server` only).\n- Fixed an issue where if the first user on a site authenticated via SSO, the site would remain stuck in uninitialized mode.", "### Added", "- More detailed progress information is displayed on pages that are waiting for repositories to clone.\n- Admins can now see charts with daily, weekly, and monthly unique user counts by visiting the site-admin Analytics page.\n- Admins can now host and see results from Sourcegraph user satisfaction surveys locally by setting the `\"experimentalFeatures\": { \"hostSurveysLocally\": \"enabled\"}` site config option. This feature will be enabled for all instances once stable.\n- Access tokens are now supported for all authentication providers (including OpenID Connect and SAML, which were previously not supported).\n- The new `motd` setting (in global, organization, and user settings) displays specified messages at the top of all pages.\n- Site admins may now view all access tokens site-wide (for all users) and revoke tokens from the new access tokens page in the site admin area.", "## 2.7.0", "### Changed", "- Missing repositories no longer appear as search results. Instead, a count of repositories that were not found is displayed above the search results. Hovering over the count will reveal the names of the missing repositories.\n- \"Show more\" on the search results page will now reveal results that have already been fetched (if such results exist) without needing to do a new query.\n- The bottom panel (on a file) now shows more tabs, including docstrings, multiple definitions, references (as before), external references grouped by repository, implementations (if supported by the language server), and file history.\n- The repository sidebar file tree is much faster on massive repositories (200,000+ files)", "### Fixed", "- Searches no longer block if the index is unavailable (e.g. after the index pod restarts). Instead, it respects the normal search timeout and reports the situation to the user if the index is not yet available.\n- Repository results are no longer returned for filters that are not supported (e.g. if `file:` is part of the search query)\n- Fixed an issue where file tree elements may be scrolled out of view on page load.\n- Fixed an issue that caused \"Could not ensure repository updated\" log messages when trying to update a large number of repositories from gitolite.\n- When using an HTTP authentication proxy (`\"auth.provider\": \"http-header\"`), usernames are now properly normalized (special characters including `.` replaced with `-`). This fixes an issue preventing users from signing in if their username contained these special characters.\n- Fixed an issue where the site-admin Updates page would incorrectly report that update checking was turned off when `telemetryDisabled` was set, even as it continued to report new updates.\n- `repo:` filters that match multiple repositories and contain a revision specifier now correctly return partial results even if some of the matching repositories don't have a matching revision.\n- Removed hardcoded list of supported languages for code intelligence. Any language can work now and support is determined from the server response.\n- Fixed an issue where modifying `config.json` on disk would not correctly mark the server as needing a restart.\n- Fixed an issue where certain diff searches (with very sparse matches in a repository's history) would incorrectly report no results found.\n- Fixed an issue where the `langservers` field in the site-configuration didn't require both the `language` and `address` field to be specified for each entry", "### Added", "- Users (and site admins) may now create and manage access tokens to authenticate API clients. The site config `auth.disableAccessTokens` (renamed to `auth.accessTokens` in 2.11) disables this new feature. Access tokens are currently only supported when using the `builtin` and `http-header` authentication providers (not OpenID Connect or SAML).\n- User and site admin management capabilities for user email addresses are improved.\n- The user and organization management UI has been greatly improved. Site admins may now administer all organizations (even those they aren't a member of) and may edit profile info and configuration for all users.\n- If SSO is enabled (via OpenID Connect or SAML) and the SSO system provides user avatar images and/or display names, those are now used by Sourcegraph.\n- Enable new search timeout behavior by setting `\"experimentalFeatures\": { \"searchTimeoutParameter\": \"enabled\"}` in your site config.\n - Adds a new `timeout:` parameter to customize the timeout for searches. It defaults to 10s and may not be set higher than 1m.\n - The value of the `timeout:` parameter is a string that can be parsed by [time.Duration](https://golang.org/pkg/time/#ParseDuration) (e.g. \"100ms\", \"2s\").\n - When `timeout:` is not provided, search optimizes for retuning results as soon as possible and will include slower kinds of results (e.g. symbols) only if they are found quickly.\n - When `timeout:` is provided, all result kinds are given the full timeout to complete.\n- A new user settings tokens page was added that allows users to obtain a token that they can use to authenticate to the Sourcegraph API.\n- Code intelligence indexes are now built for all repositories in the background, regardless of whether or not they are visited directly by a user.\n- Language servers are now automatically enabled when visiting a repository. For example, visiting a Go repository will now automatically download and run the relevant Docker container for Go code intelligence.\n - This change only affects when Sourcegraph is deployed using the `sourcegraph/server` Docker image (not using Kubernetes).\n - You will need to use the new `docker run` command at https://docs.sourcegraph.com/#quick-install in order for this feature to be enabled. Otherwise, you will receive errors in the log about `/var/run/docker.sock` and things will work just as they did before. See https://docs.sourcegraph.com/extensions/language_servers for more information.\n- The site admin Analytics page will now display the number of \"Code Intelligence\" actions each user has made, including hovers, jump to definitions, and find references, on the Sourcegraph webapp or in a code host integration or extension.\n- An experimental cross repository jump to definition which consults the OSS index on Sourcegraph.com. This is disabled by default; use `\"experimentalFeatures\": { \"jumpToDefOSSIndex\": \"enabled\" }` in your site configuration to enable it.\n- Users can now view Git branches, tags, and commits, and compare Git branches and revisions on Sourcegraph. (The code host icon in the header takes you to the commit on the code host.)\n- A new admin panel allows you to view and manage language servers. For Docker deployments, it allows you to enable/disable/update/restart language servers at the click of a button. For cluster deployments, it shows the current status of language servers.\n- Users can now tweet their feedback about Sourcegraph when clicking on the feedback smiley located in the navbar and filling out a Twitter feedback form.\n- A new button in the repository header toggles on/off the Git history panel for the current file.", "## 2.6.8", "### Bug fixes", "- Searches of `type:repo` now work correctly with \"Show more\" and the `max` parameter.\n- Fixes an issue where the server would crash if the DB was not available upon startup.", "## 2.6.7", "### Added", "- The duration that the frontend waits for the PostgreSQL database to become available is now configurable with the `DB_STARTUP_TIMEOUT` env var (the value is any valid Go duration string).\n- Dynamic search filters now suggest exclusions of Go test files, vendored files and node_modules files.", "## 2.6.6", "### Added", "- Authentication to Bitbucket Server using username-password credentials is now supported (in the `bitbucketServer` site config `username`/`password` options), for servers running Bitbucket Server version 2.4 and older (which don't support personal access tokens).", "## 2.6.5", "### Added", "- The externally accessible URL path `/healthz` performs a basic application health check, returning HTTP 200 on success and HTTP 500 on failure.", "### Behavior changes", "- Read-only forks on GitHub are no longer synced by default. If you want to add a readonly fork, navigate directly to the repository page on Sourcegraph to add it (e.g. https://sourcegraph.mycompany.internal/github.com/owner/repo). This prevents your repositories list from being cluttered with a large number of private forks of a private repository that you have access to. One notable example is https://github.com/EpicGames/UnrealEngine.\n- SAML cookies now expire after 90 days. The previous behavior was every 1 hour, which was unintentionally low.", "## 2.6.4", "### Added", "- Improve search timeout error messages\n- Performance improvements for searching regular expressions that do not start with a literal.", "## 2.6.3", "### Bug fixes", "- Symbol results are now only returned for searches that contain `type:symbol`", "## 2.6.2", "### Added", "- More detailed logging to help diagnose errors with third-party authentication providers.\n- Anchors (such as `#my-section`) in rendered Markdown files are now supported.\n- Instrumentation section for admins. For each service we expose pprof, prometheus metrics and traces.", "### Bug fixes", "- Applies a 1s timeout to symbol search if invoked without specifying `type:` to not block plain text results. No change of behaviour if `type:symbol` is given explicitly.\n- Only show line wrap toggle for code-view-rendered files.", "## 2.6.1", "### Bug fixes", "- Fixes a bug where typing in the search query field would modify the expanded state of file search results.\n- Fixes a bug where new logins via OpenID Connect would fail with the error `SSO error: ID Token verification failed`.", "## 2.6.0", "### Added", "- Support for [Bitbucket Server](https://www.atlassian.com/software/bitbucket/server) as a codehost. Configure via the `bitbucketServer` site config field.\n- Prometheus gauges for git clone queue depth (`src_gitserver_clone_queue`) and git ls-remote queue depth (`src_gitserver_lsremote_queue`).\n- Slack notifications for saved searches may now be added for individual users (not just organizations).\n- The new search filter `lang:` filters results by programming language (example: `foo lang:go` or `foo -lang:clojure`).\n- Dynamic filters: filters generated from your search results to help refine your results.\n- Search queries that consist only of `file:` now show files whose path matches the filters (instead of no results).\n- Sourcegraph now automatically detects basic `$GOPATH` configurations found in `.envrc` files in the root of repositories.\n- You can now configure the effective `$GOPATH`s of a repository by adding a `.sourcegraph/config.json` file to your repository with the contents `{\"go\": {\"GOPATH\": [\"mygopath\"]}}`.\n- A new `\"blacklistGoGet\": [\"mydomain.org,myseconddomain.com\"]` offers users a quick escape hatch in the event that Sourcegraph is making unwanted `go get` or `git clone` requests to their website due to incorrectly-configured monorepos. Most users will never use this option.\n- Search suggestions and results now include symbol results. The new filter `type:symbol` causes only symbol results to be shown.\n Additionally, symbols for a repository can be browsed in the new symbols sidebar.\n- You can now expand and collapse all items on a search results page or selectively expand and collapse individual items.", "### Configuration changes", "- Reduced the `gitMaxConcurrentClones` site config option's default value from 100 to 5, to help prevent too many concurrent clones from causing issues on code hosts.\n- Changes to some site configuration options are now automatically detected and no longer require a server restart. After hitting Save in the UI, you will be informed if a server restart is required, per usual.\n- Saved search notifications are now only sent to the owner of a saved search (all of an organization's members for an organization-level saved search, or a single user for a user-level saved search). The `notifyUsers` and `notifyOrganizations` properties underneath `search.savedQueries` have been removed.\n- Slack webhook URLs are now defined in user/organization JSON settings, not on the organization profile page. Previously defined organization Slack webhook URLs are automatically migrated to the organization's JSON settings.\n- The \"unlimited\" value for `maxReposToSearch` is now `-1` instead of `0`, and `0` now means to use the default.\n- `auth.provider` must be set (`builtin`, `openidconnect`, `saml`, `http-header`, etc.) to configure an authentication provider. Previously you could just set the detailed configuration property (`\"auth.openIDConnect\": {...}`, etc.) and it would implicitly enable that authentication provider.\n- The `autoRepoAdd` site configuration property was removed. Site admins can add repositories via site configuration.", "### Bug fixes", "- Only cross reference index enabled repositories.\n- Fixed an issue where search would return results with empty file contents for matches in submodules with indexing enabled. Searching over submodules is not supported yet, so these (empty) results have been removed.\n- Fixed an issue where match highlighting would be incorrect on lines that contained multibyte characters.\n- Fixed an issue where search suggestions would always link to master (and 404) even if the file only existed on a branch. Now suggestions always link to the revision that is being searched over.\n- Fixed an issue where all file and repository links on the search results page (for all search results types) would always link to master branch, even if the results only existed in another branch. Now search results links always link to the revision that is being searched over.\n- The first user to sign up for a (not-yet-initialized) server is made the site admin, even if they signed up using SSO. Previously if the first user signed up using SSO, they would not be a site admin and no site admin could be created.\n- Fixed an issue where our code intelligence archive cache (in `lsp-proxy`) would not evict items from the disk. This would lead to disks running out of free space.", "## 2.5.16, 2.5.17", "- Version bump to keep deployment variants in sync.", "## 2.5.15", "### Bug fixes", "- Fixed issue where a Sourcegraph cluster would incorrectly show \"An update is available\".\n- Fixed Phabricator links to repositories\n- Searches over a single repository are now less likely to immediately time out the first time they are searched.\n- Fixed a bug where `auth.provider == \"http-header\"` would incorrectly require builtin authentication / block site access when `auth.public == \"false\"`.", "### Phabricator Integration Changes", "We now display a \"View on Phabricator\" link rather than a \"View on other code host\" link if you are using Phabricator and hosting on GitHub or another code host with a UI. Commit links also will point to Phabricator.", "### Improvements to SAML authentication", "You may now optionally provide the SAML Identity Provider metadata XML file contents directly, with the `auth.saml` `identityProviderMetadata` site configuration property. (Previously, you needed to specify the URL where that XML file was available; that is still possible and is more common.) The new option is useful for organizations whose SAML metadata is not web-accessible or while testing SAML metadata configuration changes.", "## 2.5.13", "### Improvements to builtin authentication", "When using `auth.provider == \"builtin\"`, two new important changes mean that a Sourcegraph server will be locked down and only accessible to users who are invited by an admin user (previously, we advised users to place their own auth proxy in front of Sourcegraph servers).", "1. When `auth.provider == \"builtin\"` Sourcegraph will now by default require an admin to invite users instead of allowing anyone who can visit the site to sign up. Set `auth.allowSignup == true` to retain the old behavior of allowing anyone who can access the site to signup.\n2. When `auth.provider == \"builtin\"`, Sourcegraph will now respects a new `auth.public` site configuration option (default value: `false`). When `auth.public == false`, Sourcegraph will not allow anyone to access the site unless they have an account and are signed in.", "## 2.4.3", "### Added", "- Code Intelligence support\n- Custom links to code hosts with the `links:` config options in `repos.list`", "### Changed", "- Search by file path enabled by default", "## 2.4.2", "### Added", "- Repository settings mirror/cloning diagnostics page", "### Changed", "- Repositories added from GitHub are no longer enabled by default. The site admin UI for enabling/disabling repositories is improved.", "## 2.4.0", "### Added", "- Search files by name by including `type:path` in a search query\n- Global alerts for configuration-needed and cloning-in-progress\n- Better list interfaces for repositories, users, organizations, and threads\n- Users can change their own password in settings\n- Repository groups can now be specified in settings by site admins, organizations, and users. Then `repogroup:foo` in a search query will search over only those repositories specified for the `foo` repository group.", "### Changed", "- Log messages are much quieter by default", "## 2.3.11", "### Added", "- Added site admin updates page and update checking\n- Added site admin telemetry page", "### Changed", "- Enhanced site admin panel\n- Changed repo- and SSO-related site config property names to be consistent, updated documentation", "## 2.3.10", "### Added", "- Online site configuration editing and reloading", "### Changed", "- Site admins are now configured in the site admin area instead of in the `adminUsernames` config key or `ADMIN_USERNAMES` env var. Users specified in those deprecated configs will be designated as site admins in the database upon server startup until those configs are removed in a future release.", "## 2.3.9", "### Fixed", "- An issue that prevented creation and deletion of saved queries", "## 2.3.8", "### Added", "- Built-in authentication: you can now sign up without an SSO provider.\n- Faster default branch code search via indexing.", "### Fixed", "- Many performance improvements to search.\n- Much log spam has been eliminated.", "### Changed", "- We optionally read `SOURCEGRAPH_CONFIG` from `$DATA_DIR/config.json`.\n- SSH key required to clone repositories from GitHub Enterprise when using a self-signed certificate.", "## 0.3 - 13 December 2017", "The last version without a CHANGELOG." ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [26, 1516, 36, 537], "buggy_code_start_loc": [26, 39, 33, 537], "filenames": ["CHANGELOG.md", "cmd/frontend/graphqlbackend/search_results.go", "dev/gqltest/README.md", "dev/gqltest/search_test.go"], "fixing_code_end_loc": [35, 1518, 36, 544], "fixing_code_start_loc": [27, 40, 33, 538], "message": "Sourcegraph is a code search and navigation engine. Sourcegraph prior to version 3.33.2 is vulnerable to a side-channel attack where strings in private source code could be guessed by an authenticated but unauthorized actor. This issue affects the Saved Searches and Code Monitoring features. A successful attack would require an authenticated bad actor to create many Saved Searches or Code Monitors to receive confirmation that a specific string exists. This could allow an attacker to guess formatted tokens in source code, such as API keys. This issue was patched in version 3.33.2 and any future versions of Sourcegraph. We strongly encourage upgrading to secure versions. If you are unable to, you may disable Saved Searches and Code Monitors.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sourcegraph:sourcegraph:*:*:*:*:*:*:*:*", "matchCriteriaId": "8AC67147-DAE3-4326-9027-0DEB53C55D32", "versionEndExcluding": "3.33.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Sourcegraph is a code search and navigation engine. Sourcegraph prior to version 3.33.2 is vulnerable to a side-channel attack where strings in private source code could be guessed by an authenticated but unauthorized actor. This issue affects the Saved Searches and Code Monitoring features. A successful attack would require an authenticated bad actor to create many Saved Searches or Code Monitors to receive confirmation that a specific string exists. This could allow an attacker to guess formatted tokens in source code, such as API keys. This issue was patched in version 3.33.2 and any future versions of Sourcegraph. We strongly encourage upgrading to secure versions. If you are unable to, you may disable Saved Searches and Code Monitors."}, {"lang": "es", "value": "Sourcegraph es un motor de b\u00fasqueda y navegaci\u00f3n de c\u00f3digo. Sourcegraph versiones anteriores a 3.33.2 es vulnerable a un ataque de canal lateral en el que las cadenas del c\u00f3digo fuente privado podr\u00edan ser adivinadas por un actor autenticado pero no autorizado. Este problema afecta a las funciones de B\u00fasquedas Guardadas y Monitorizaci\u00f3n de C\u00f3digo. Un ataque con \u00e9xito requerir\u00eda que un actor malo autenticado creara muchas B\u00fasquedas Guardadas o Monitores de C\u00f3digo para recibir la confirmaci\u00f3n de que una cadena espec\u00edfica esta presente. Esto podr\u00eda permitir a un atacante adivinar los tokens formateados en el c\u00f3digo fuente, como las claves de la API. Este problema ha sido parcheado en la versi\u00f3n 3.33.2 y en las futuras versiones de Sourcegraph. Recomendamos encarecidamente que se actualice a las versiones seguras. Si no puede hacerlo, puede deshabilitar las B\u00fasquedas Guardadas y los Monitores de C\u00f3digo"}], "evaluatorComment": null, "id": "CVE-2021-43823", "lastModified": "2021-12-16T15:00:25.970", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Primary"}]}, "published": "2021-12-13T20:15:07.813", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/sourcegraph/sourcegraph/commit/a88d90a8302c492282186d39718cd8fb093c14fa"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/sourcegraph/sourcegraph/security/advisories/GHSA-cpq7-hmvv-29w9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-203"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/sourcegraph/sourcegraph/commit/a88d90a8302c492282186d39718cd8fb093c14fa"}, "type": "CWE-203"}
326
Determine whether the {function_name} code is vulnerable or not.
[ "<!--\n###################################### READ ME ###########################################\n### This changelog should always be read on `main` branch. Its contents on version ###\n### branches do not necessarily reflect the changes that have gone into that branch. ###\n##########################################################################################\n-->", "# Changelog", "All notable changes to Sourcegraph are documented in this file.", "<!-- START CHANGELOG -->", "## Unreleased", "### Added", "-", "### Changed", "-", "### Fixed", "-", "- An issue that causes the server to panic when performing a structural search via the GQL API for a query that also\n matches missing repos (affected versions 3.33.0 and 3.32.0)\n . [#26630](https://github.com/sourcegraph/sourcegraph/pull/26630)\n- Improve detection for Docker running in non-linux\n environments. [#23477](https://github.com/sourcegraph/sourcegraph/issues/23477)\n- Fixed the cache size calculation used for Kubernetes deployments. Previously, the calculated value was too high and would exceed the ephemeral storage request limit. #[26283](https://github.com/sourcegraph/sourcegraph/issues/26283)\n- Fixed a regression that was introduced in 3.27 and broke SSH-based authentication for managing Batch Changes changesets on code hosts. SSH keys generated by Sourcegraph were not used for authentication and authenticating with the code host would fail if no SSH key with write-access had been added to `gitserver`. [#27491](https://github.com/sourcegraph/sourcegraph/pull/27491)\n- Private repositories matching `-repo:` expressions are now excluded. This was a regression introduced in 3.33.0. [#27044](https://github.com/sourcegraph/sourcegraph/issues/27044)", "\n### Removed", "-", "## 3.33.0", "### Added", "- More rules have been added to the search query validation so that user get faster feedback on issues with their query. [#24747](https://github.com/sourcegraph/sourcegraph/pull/24747)\n- Bloom filters have been added to the zoekt indexing backend to accelerate queries with code fragments matching `\\w{4,}`. [zoekt#126](https://github.com/sourcegraph/zoekt/pull/126)\n- For short search queries containing no filters but the name of a supported programming language we are now suggesting to run the query with a language filter. [#25792](https://github.com/sourcegraph/sourcegraph/pull/25792)\n- The API scope used by GitLab OAuth can now optionally be configured in the provider. [#26152](https://github.com/sourcegraph/sourcegraph/pull/26152)", "### Changed", "- Search context management pages are now only available in the Sourcegraph enterprise version. Search context dropdown is disabled in the OSS version. [#25147](https://github.com/sourcegraph/sourcegraph/pull/25147)\n- Search contexts GQL API is now only available in the Sourcegraph enterprise version. [#25281](https://github.com/sourcegraph/sourcegraph/pull/25281)\n- When running a commit or diff query, the accepted values of `before` and `after` have changed from \"whatever git accepts\" to a [slightly more strict subset](https://docs.sourcegraph.com/code_search/reference/language#before) of that. [#25414](https://github.com/sourcegraph/sourcegraph/pull/25414)\n- Repogroups and version contexts are deprecated in favor of search contexts. Read more about the deprecation and how to migrate to search contexts in the [blog post](https://about.sourcegraph.com/blog/introducing-search-contexts). [#25676](https://github.com/sourcegraph/sourcegraph/pull/25676)\n- Search contexts are now enabled by default in the Sourcegraph enterprise version. [#25674](https://github.com/sourcegraph/sourcegraph/pull/25674)\n- Code Insights background queries will now retry a maximum of 10 times (down from 100). [#26057](https://github.com/sourcegraph/sourcegraph/pull/26057)\n- Our `sourcegraph/cadvisor` Docker image has been upgraded to cadvisor version `v0.42.0`. [#26126](https://github.com/sourcegraph/sourcegraph/pull/26126)\n- Our `jaeger` version in the `sourcegraph/sourcegraph` Docker image has been upgraded to `1.24.0`. [#26215](https://github.com/sourcegraph/sourcegraph/pull/26215)", "### Fixed", "- A search regression in 3.32.0 which caused instances with search indexing _disabled_ (very rare) via `\"search.index.enabled\": false,` in their site config to crash with a panic. [#25321](https://github.com/sourcegraph/sourcegraph/pull/25321)\n- An issue where the default `search.index.enabled` value on single-container Docker instances would incorrectly be computed as `false` in some situations. [#25321](https://github.com/sourcegraph/sourcegraph/pull/25321)\n- StatefulSet service discovery in Kubernetes correctly constructs pod hostnames in the case where the ServiceName is different from the StatefulSet name. [#25146](https://github.com/sourcegraph/sourcegraph/pull/25146)\n- An issue where clicking on a link in the 'Revisions' search sidebar section would result in an invalid query if the query didn't already contain a 'repo:' filter. [#25076](https://github.com/sourcegraph/sourcegraph/pull/25076)\n- An issue where links to jump to Bitbucket Cloud wouldn't render in the UI. [#25533](https://github.com/sourcegraph/sourcegraph/pull/25533)\n- Fixed some code insights pings being aggregated on `anonymous_user_id` instead of `user_id`. [#25926](https://github.com/sourcegraph/sourcegraph/pull/25926)\n- Code insights running over all repositories using a commit search (`type:commit` or `type:diff`) would fail to deserialize and produce no results. [#25928](https://github.com/sourcegraph/sourcegraph/pull/25928)\n- Fixed an issue where code insights queries could produce a panic on queued records that did not include a `record_time` [#25929](https://github.com/sourcegraph/sourcegraph/pull/25929)\n- Fixed an issue where Batch Change changeset diffs would sometimes render incorrectly when previewed from the UI if they contained deleted empty lines. [#25866](https://github.com/sourcegraph/sourcegraph/pull/25866)\n- An issue where `repo:contains.commit.after()` would fail on some malformed git repositories. [#25974](https://github.com/sourcegraph/sourcegraph/issues/25974)\n- Fixed primary email bug where users with no primary email set would break the email setting page when trying to add a new email. [#25008](https://github.com/sourcegraph/sourcegraph/pull/25008)\n- An issue where keywords like `and`, `or`, `not` would not be highlighted properly in the search bar due to the presence of quotes. [#26135](https://github.com/sourcegraph/sourcegraph/pull/26135)\n- An issue where frequent search indexing operations led to incoming search queries timing out. When these timeouts happened in quick succession, `zoekt-webserver` processes would shut themselves down via their `watchdog` routine. This should now only happen when a given `zoekt-webserver` is under-provisioned on CPUs. [#25872](https://github.com/sourcegraph/sourcegraph/issues/25872)\n- Since 3.28.0, Batch Changes webhooks would not update changesets opened in private repositories. This has been fixed. [#26380](https://github.com/sourcegraph/sourcegraph/issues/26380)\n- Reconciling batch changes could stall when updating the state of a changeset that already existed. This has been fixed. [#26386](https://github.com/sourcegraph/sourcegraph/issues/26386)", "### Removed", "- Batch Changes changeset specs stored the raw JSON used when creating them, which is no longer used and is not exposed in the API. This column has been removed, thereby saving space in the Sourcegraph database. [#25453](https://github.com/sourcegraph/sourcegraph/issues/25453)\n- The query builder page experimental feature, which was disabled in 3.21, is now removed. The setting `{ \"experimentalFeatures\": { \"showQueryBuilder\": true } }` now has no effect. [#26125](https://github.com/sourcegraph/sourcegraph/pull/26125)", "## 3.32.0", "### Added", "- The search sidebar shows a revisions section if all search results are from a single repository. This makes it easier to search in and switch between different revisions. [#23835](https://github.com/sourcegraph/sourcegraph/pull/23835)\n- The various alerts overview panels in Grafana can now be clicked to go directly to the relevant panels and dashboards. [#24920](https://github.com/sourcegraph/sourcegraph/pull/24920)\n- Added a `Documentation` tab to the Site Admin Maintenance panel that links to the official Sourcegraph documentation. [#24917](https://github.com/sourcegraph/sourcegraph/pull/24917)\n- Code Insights that run over all repositories now generate a moving daily snapshot between time points. [#24804](https://github.com/sourcegraph/sourcegraph/pull/24804)\n- The Code Insights GraphQL API now restricts the results to user, org, and globally scoped insights. Insights will be synced to the database with access associated to the user or org setting containing the insight definition. [#25017](https://github.com/sourcegraph/sourcegraph/pull/25017)\n- The timeout for long-running Git commands can be customized via `gitLongCommandTimeout` in the site config. [#25080](https://github.com/sourcegraph/sourcegraph/pull/25080)", "### Changed", "- `allowGroupsPermissionsSync` in the GitHub authorization provider is now required to enable the experimental GitHub teams and organization permissions caching. [#24561](https://github.com/sourcegraph/sourcegraph/pull/24561)\n- GitHub external code hosts now validate if a corresponding authorization provider is set, and emits a warning if not. [#24526](https://github.com/sourcegraph/sourcegraph/pull/24526)\n- Sourcegraph is now built with Go 1.17. [#24566](https://github.com/sourcegraph/sourcegraph/pull/24566)\n- Code Insights is now available only in the Sourcegraph enterprise. [#24741](https://github.com/sourcegraph/sourcegraph/pull/24741)\n- Prometheus in Sourcegraph with Docker Compose now scrapes Postgres and Redis instances for metrics. [deploy-sourcegraph-docker#580](https://github.com/sourcegraph/deploy-sourcegraph-docker/pull/580)\n- Symbol suggestions now leverage optimizations for global searches. [#24943](https://github.com/sourcegraph/sourcegraph/pull/24943)", "### Fixed", "- Fixed a number of issues where repository permissions sync may fail for instances with very large numbers of repositories. [#24852](https://github.com/sourcegraph/sourcegraph/pull/24852), [#24972](https://github.com/sourcegraph/sourcegraph/pull/24972)\n- Fixed excessive re-rendering of the whole web application on every keypress in the search query input. [#24844](https://github.com/sourcegraph/sourcegraph/pull/24844)\n- Code Insights line chart now supports different timelines for each data series (lines). [#25005](https://github.com/sourcegraph/sourcegraph/pull/25005)\n- Postgres exporter now exposes pg_stat_activity account to show the number of active DB connections. [#25086](https://github.com/sourcegraph/sourcegraph/pull/25086)", "### Removed", "- The `PRECISE_CODE_INTEL_DATA_TTL` environment variable is no longer read by the worker service. Instead, global and repository-specific data retention policies configurable in the UI by site-admins will control the length of time LSIF uploads are considered _fresh_. [#24793](https://github.com/sourcegraph/sourcegraph/pull/24793)\n- The `repo.cloned` column was removed as it was deprecated in 3.26. [#25066](https://github.com/sourcegraph/sourcegraph/pull/25066)", "## 3.31.2", "### Fixed", "- Fixed multiple CVEs for [libssl](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-3711) and [Python3](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-29921). [#24700](https://github.com/sourcegraph/sourcegraph/pull/24700) [#24620](https://github.com/sourcegraph/sourcegraph/pull/24620) [#24695](https://github.com/sourcegraph/sourcegraph/pull/24695)", "## 3.31.1", "### Added", "- The required authentication scopes required to enable caching behaviour for GitHub repository permissions can now be requested via `allowGroupsPermissionsSync` in GitHub `auth.providers`. [#24328](https://github.com/sourcegraph/sourcegraph/pull/24328)", "### Changed", "- Caching behaviour for GitHub repository permissions enabled via the `authorization.groupsCacheTTL` field in the code host config can now leverage additional caching of team and organization permissions for repository permissions syncing (on top of the caching for user permissions syncing introduced in 3.31). [#24328](https://github.com/sourcegraph/sourcegraph/pull/24328)", "## 3.31.0", "### Added", "- Backend Code Insights GraphQL queries now support arguments `includeRepoRegex` and `excludeRepoRegex` to filter on repository names. [#23256](https://github.com/sourcegraph/sourcegraph/pull/23256)\n- Code Insights background queries now process in a priority order backwards through time. This will allow insights to populate concurrently. [#23101](https://github.com/sourcegraph/sourcegraph/pull/23101)\n- Operator documentation has been added to the Search Reference sidebar section. [#23116](https://github.com/sourcegraph/sourcegraph/pull/23116)\n- Syntax highlighting support for the [Cue](https://cuelang.org) language.\n- Reintroduced a revised version of the Search Types sidebar section. [#23170](https://github.com/sourcegraph/sourcegraph/pull/23170)\n- Improved usability where filters followed by a space in the search query will warn users that the filter value is empty. [#23646](https://github.com/sourcegraph/sourcegraph/pull/23646)\n- Perforce: [`git p4`'s `--use-client-spec` option](https://git-scm.com/docs/git-p4#Documentation/git-p4.txt---use-client-spec) can now be enabled by configuring the `p4.client` field. [#23833](https://github.com/sourcegraph/sourcegraph/pull/23833), [#23845](https://github.com/sourcegraph/sourcegraph/pull/23845)\n- Code Insights will do a one-time reset of ephemeral insights specific database tables to clean up stale and invalid data. Insight data will regenerate automatically. [23791](https://github.com/sourcegraph/sourcegraph/pull/23791)\n- Perforce: added basic support for Perforce permission table path wildcards. [#23755](https://github.com/sourcegraph/sourcegraph/pull/23755)\n- Added autocompletion and search filtering of branch/tag/commit revisions to the repository compare page. [#23977](https://github.com/sourcegraph/sourcegraph/pull/23977)\n- Batch Changes changesets can now be [set to published when previewing new or updated batch changes](https://docs.sourcegraph.com/batch_changes/how-tos/publishing_changesets#within-the-ui). [#22912](https://github.com/sourcegraph/sourcegraph/issues/22912)\n- Added Python3 to server and gitserver images to enable git-p4 support. [#24204](https://github.com/sourcegraph/sourcegraph/pull/24204)\n- Code Insights drill-down filters now allow filtering insights data on the dashboard page using repo: filters. [#23186](https://github.com/sourcegraph/sourcegraph/issues/23186)\n- GitHub repository permissions can now leverage caching of team and organization permissions for user permissions syncing. Caching behaviour can be enabled via the `authorization.groupsCacheTTL` field in the code host config. This can significantly reduce the amount of time it takes to perform a full permissions sync due to reduced instances of being rate limited by the code host. [#23978](https://github.com/sourcegraph/sourcegraph/pull/23978)", "### Changed", "- Code Insights will now always backfill from the time the data series was created. [#23430](https://github.com/sourcegraph/sourcegraph/pull/23430)\n- Code Insights queries will now extract repository name out of the GraphQL response instead of going to the database. [#23388](https://github.com/sourcegraph/sourcegraph/pull/23388)\n- Code Insights backend has moved from the `repo-updater` service to the `worker` service. [#23050](https://github.com/sourcegraph/sourcegraph/pull/23050)\n- Code Insights feature flag `DISABLE_CODE_INSIGHTS` environment variable has moved from the `repo-updater` service to the `worker` service. Any users of this flag will need to update their `worker` service configuration to continue using it. [#23050](https://github.com/sourcegraph/sourcegraph/pull/23050)\n- Updated Docker-Compose Caddy Image to v2.0.0-alpine. [#468](https://github.com/sourcegraph/deploy-sourcegraph-docker/pull/468)\n- Code Insights historical samples will record using the timestamp of the commit that was searched. [#23520](https://github.com/sourcegraph/sourcegraph/pull/23520)\n- Authorization checks are now handled using role based permissions instead of manually altering SQL statements. [23398](https://github.com/sourcegraph/sourcegraph/pull/23398)\n- Docker Compose: the Jaeger container's `SAMPLING_STRATEGIES_FILE` now has a default value. If you are currently using a custom sampling strategies configuration, you may need to make sure your configuration is not overridden by the change when upgrading. [sourcegraph/deploy-sourcegraph#489](https://github.com/sourcegraph/deploy-sourcegraph-docker/pull/489)\n- Code Insights historical samples will record using the most recent commit to the start of the frame instead of the middle of the frame. [#23573](https://github.com/sourcegraph/sourcegraph/pull/23573)\n- The copy icon displayed next to files and repositories will now copy the file or repository path. Previously, this action copied the URL to clipboard. [#23390](https://github.com/sourcegraph/sourcegraph/pull/23390)\n- Sourcegraph's Prometheus dependency has been upgraded to v2.28.1. [23663](https://github.com/sourcegraph/sourcegraph/pull/23663)\n- Sourcegraph's Alertmanager dependency has been upgraded to v0.22.2. [23663](https://github.com/sourcegraph/sourcegraph/pull/23714)\n- Code Insights will now schedule sample recordings for the first of the next month after creation or a previous recording. [#23799](https://github.com/sourcegraph/sourcegraph/pull/23799)\n- Code Insights now stores data in a new format. Data points will store complete vectors for all repositories even if the underlying Sourcegraph queries were compressed. [#23768](https://github.com/sourcegraph/sourcegraph/pull/23768)\n- Code Insights rate limit values have been tuned for a more reasonable performance. [#23860](https://github.com/sourcegraph/sourcegraph/pull/23860)\n- Code Insights will now generate historical data once per month on the first of the month, up to the configured `insights.historical.frames` number of frames. [#23768](https://github.com/sourcegraph/sourcegraph/pull/23768)\n- Code Insights will now schedule recordings for the first of the next calendar month after an insight is created or recorded. [#23799](https://github.com/sourcegraph/sourcegraph/pull/23799)\n- Code Insights will attempt to sync insight definitions from settings to the database once every 10 minutes. [23805](https://github.com/sourcegraph/sourcegraph/pull/23805)\n- Code Insights exposes information about queries that are flagged `dirty` through the `insights` GraphQL query. [#23857](https://github.com/sourcegraph/sourcegraph/pull/23857/)\n- Code Insights GraphQL query `insights` will now fetch 12 months of data instead of 6 if a specific time range is not provided. [#23786](https://github.com/sourcegraph/sourcegraph/pull/23786)\n- Code Insights will now generate 12 months of historical data during a backfill instead of 6. [#23860](https://github.com/sourcegraph/sourcegraph/pull/23860)\n- The `sourcegraph-frontend.Role` in Kubernetes deployments was updated to permit statefulsets access in the Kubernetes API. This is needed to better support stable service discovery for stateful sets during deployments, which isn't currently possible by using service endpoints. [#3670](https://github.com/sourcegraph/deploy-sourcegraph/pull/3670) [#23889](https://github.com/sourcegraph/sourcegraph/pull/23889)\n- For Docker-Compose and Kubernetes users, the built-in main Postgres and codeintel databases have switched to an alpine Docker image. This requires re-indexing the entire database. This process can take up to a few hours on systems with large datasets. [#23697](https://github.com/sourcegraph/sourcegraph/pull/23697)\n- Results are now streamed from searcher by default, improving memory usage and latency for large, unindexed searches. [#23754](https://github.com/sourcegraph/sourcegraph/pull/23754)\n- [`deploy-sourcegraph` overlays](https://docs.sourcegraph.com/admin/install/kubernetes/configure#overlays) now use `resources:` instead of the [deprecated `bases:` field](https://kubectl.docs.kubernetes.io/references/kustomize/kustomization/bases/) for referencing Kustomize bases. [deploy-sourcegraph#3606](https://github.com/sourcegraph/deploy-sourcegraph/pull/3606)\n- The `deploy-sourcegraph-docker` Pure Docker deployment scripts and configuration has been moved to the `./pure-docker` subdirectory. [deploy-sourcegraph-docker#454](https://github.com/sourcegraph/deploy-sourcegraph-docker/pull/454)\n- In Kubernetes deployments, setting the `SRC_GIT_SERVERS` environment variable explicitly is no longer needed. Addresses of the gitserver pods will be discovered automatically and in the same numerical order as with the static list. Unset the env var in your `frontend.Deployment.yaml` to make use of this feature. [#24094](https://github.com/sourcegraph/sourcegraph/pull/24094)\n- The consistent hashing scheme used to distribute repositories across indexed-search replicas has changed to improve distribution and reduce load discrepancies. In the next upgrade, indexed-search pods will re-index the majority of repositories since the repo to replica assignments will change. This can take a few hours in large instances, but searches should succeed during that time since a replica will only delete a repo once it has been indexed in the new replica that owns it. You can monitor this process in the Zoekt Index Server Grafana dashboard - the \"assigned\" repos in \"Total number of repos\" will spike and then reduce until it becomes the same as \"indexed\". As a fail-safe, the old consistent hashing scheme can be enabled by setting the `SRC_ENDPOINTS_CONSISTENT_HASH` env var to `consistent(crc32ieee)` in the `sourcegraph-frontend` deployment. [#23921](https://github.com/sourcegraph/sourcegraph/pull/23921)\n- In Kubernetes deployments an emptyDir (`/dev/shm`) is now mounted in the `pgsql` deployment to allow Postgres to access more than 64KB shared memory. This value should be configured to match the `shared_buffers` value in your Postgres configuration. [deploy-sourcegraph#3784](https://github.com/sourcegraph/deploy-sourcegraph/pull/3784/)", "### Fixed", "- The search reference will now show matching entries when using the filter input. [#23224](https://github.com/sourcegraph/sourcegraph/pull/23224)\n- Graceful termination periods have been added to database deployments. [#3358](https://github.com/sourcegraph/deploy-sourcegraph/pull/3358) & [#477](https://github.com/sourcegraph/deploy-sourcegraph-docker/pull/477)\n- All commit search results for `and`-expressions are now highlighted. [#23336](https://github.com/sourcegraph/sourcegraph/pull/23336)\n- Email notifiers in `observability.alerts` now correctly respect the `email.smtp.noVerifyTLS` site configuration field. [#23636](https://github.com/sourcegraph/sourcegraph/issues/23636)\n- Alertmanager (Prometheus) now respects `SMTPServerConfig.noVerifyTLS` field. [#23636](https://github.com/sourcegraph/sourcegraph/issues/23636)\n- Clicking on symbols in the left search pane now renders hover tooltips for indexed repositories. [#23664](https://github.com/sourcegraph/sourcegraph/pull/23664)\n- Fixed a result streaming throttling issue that was causing significantly increased latency for some searches. [#23736](https://github.com/sourcegraph/sourcegraph/pull/23736)\n- GitCredentials passwords stored in AWS CodeCommit configuration is now redacted. [#23832](https://github.com/sourcegraph/sourcegraph/pull/23832)\n- Patched a vulnerability in `apk-tools`. [#23917](https://github.com/sourcegraph/sourcegraph/pull/23917)\n- Line content was being duplicated in unindexed search payloads, causing memory instability for some dense search queries. [#23918](https://github.com/sourcegraph/sourcegraph/pull/23918)\n- Updating draft merge requests on GitLab from batch changes no longer removes the draft status. [#23944](https://github.com/sourcegraph/sourcegraph/issues/23944)\n- Report highlight matches instead of line matches in search results. [#21443](https://github.com/sourcegraph/sourcegraph/issues/21443)\n- Force the `codeinsights-db` database to read from the `configMap` configuration file by explicitly setting the `POSTGRESQL_CONF_DIR` environment variable to the `configMap` mount path. [deploy-sourcegraph#3788](https://github.com/sourcegraph/deploy-sourcegraph/pull/3788)", "### Removed", "- The old batch repository syncer was removed and can no longer be activated by setting `ENABLE_STREAMING_REPOS_SYNCER=false`. [#22949](https://github.com/sourcegraph/sourcegraph/pull/22949)\n- Email notifications for saved searches are now deprecated in favor of Code Monitoring. Email notifications can no longer be enabled for saved searches. Saved searches that already have notifications enabled will continue to work, but there is now a button users can click to migrate to code monitors. Notifications for saved searches will be removed entirely in the future. [#23275](https://github.com/sourcegraph/sourcegraph/pull/23275)\n- The `sg_service` Postgres role and `sg_repo_access_policy` policy on the `repo` table have been removed due to performance concerns. [#23622](https://github.com/sourcegraph/sourcegraph/pull/23622)\n- Deprecated site configuration field `email.smtp.disableTLS` has been removed. [#23639](https://github.com/sourcegraph/sourcegraph/pull/23639)\n- Deprecated language servers have been removed from `deploy-sourcegraph`. [deploy-sourcegraph#3605](https://github.com/sourcegraph/deploy-sourcegraph/pull/3605)\n- The experimental `codeInsightsAllRepos` feature flag has been removed. [#23850](https://github.com/sourcegraph/sourcegraph/pull/23850)", "## 3.30.4", "### Added", "- Add a new environment variable `SRC_HTTP_CLI_EXTERNAL_TIMEOUT` to control the timeout for all external HTTP requests. [#23620](https://github.com/sourcegraph/sourcegraph/pull/23620)", "### Changed", "- Postgres has been upgraded to `12.8` in the single-server Sourcegraph image [#23999](https://github.com/sourcegraph/sourcegraph/pull/23999)", "## 3.30.3", "**⚠️ Users on 3.29.x are advised to upgrade directly to 3.30.3**. If you have already upgraded to 3.30.0, 3.30.1, or 3.30.2 please follow [this migration guide](https://docs.sourcegraph.com/admin/migration/3_30).", "### Fixed", "- Codeintel-db database images have been reverted back to debian due to corruption caused by glibc and alpine. [23324](https://github.com/sourcegraph/sourcegraph/pull/23324)", "## 3.30.2", "**⚠️ Users on 3.29.x are advised to upgrade directly to 3.30.3**. If you have already upgraded to 3.30.0, 3.30.1, or 3.30.2 please follow [this migration guide](https://docs.sourcegraph.com/admin/migration/3_30).", "### Fixed", "- Postgres database images have been reverted back to debian due to corruption caused by glibc and alpine. [23302](https://github.com/sourcegraph/sourcegraph/pull/23302)", "## 3.30.1", "**⚠️ Users on 3.29.x are advised to upgrade directly to 3.30.3**. If you have already upgraded to 3.30.0, 3.30.1, or 3.30.2 please follow [this migration guide](https://docs.sourcegraph.com/admin/migration/3_30).", "### Fixed", "- An issue where the UI would occasionally display `lsifStore.Ranges: ERROR: relation \\\"lsif_documentation_mappings\\\" does not exist (SQLSTATE 42P01)` [#23115](https://github.com/sourcegraph/sourcegraph/pull/23115)\n- Fixed a vulnerability in our Postgres Alpine image related to libgcrypt [#23174](https://github.com/sourcegraph/sourcegraph/pull/23174)\n- When syncing in streaming mode, repo-updater will now ensure a repo's transaction is committed before notifying gitserver to update that repo. [#23169](https://github.com/sourcegraph/sourcegraph/pull/23169)\n- When encountering spurious errors during streaming syncing (like temporary 500s from codehosts), repo-updater will no longer delete all associated repos that weren't seen. Deletion will happen only if there were no errors or if the error was one of \"Unauthorized\", \"Forbidden\" or \"Account Suspended\". [#23171](https://github.com/sourcegraph/sourcegraph/pull/23171)\n- External HTTP requests are now automatically retried when appropriate. [#23131](https://github.com/sourcegraph/sourcegraph/pull/23131)", "## 3.30.0", "**⚠️ Users on 3.29.x are advised to upgrade directly to 3.30.3**. If you have already upgraded to 3.30.0, 3.30.1, or 3.30.2 please follow [this migration guide](https://docs.sourcegraph.com/admin/migration/3_30).", "### Added", "- Added support for `select:file.directory` in search queries, which returns unique directory paths for results that satisfy the query. [#22449](https://github.com/sourcegraph/sourcegraph/pull/22449)\n- An `sg_service` Postgres role has been introduced, as well as an `sg_repo_access_policy` policy on the `repo` table that restricts access to that role. The role that owns the `repo` table will continue to get unrestricted access. [#22303](https://github.com/sourcegraph/sourcegraph/pull/22303)\n- Every service that connects to the database (i.e. Postgres) now has a \"Database connections\" monitoring section in its Grafana dashboard. [#22570](https://github.com/sourcegraph/sourcegraph/pull/22570)\n- A new bulk operation to close many changesets at once has been added to Batch Changes. [#22547](https://github.com/sourcegraph/sourcegraph/pull/22547)\n- Backend Code Insights will aggregate viewable repositories based on the authenticated user. [#22471](https://github.com/sourcegraph/sourcegraph/pull/22471)\n- Added support for highlighting .frugal files as Thrift syntax.\n- Added `file:contains.content(regexp)` predicate, which filters only to files that contain matches of the given pattern. [#22666](https://github.com/sourcegraph/sourcegraph/pull/22666)\n- Repository syncing is now done in streaming mode by default. Customers with many repositories should notice code host updates much faster, with repo-updater consuming less memory. Using the previous batch mode can be done by setting the `ENABLE_STREAMING_REPOS_SYNCER` environment variable to `false` in `repo-updater`. That environment variable will be deleted in the next release. [#22756](https://github.com/sourcegraph/sourcegraph/pull/22756)\n- Enabled the ability to query Batch Changes changesets, changesets stats, and file diff stats for an individual repository via the Sourcegraph GraphQL API. [#22744](https://github.com/sourcegraph/sourcegraph/pull/22744/)\n- Added \"Groovy\" to the initial `lang:` filter suggestions in the search bar. [#22755](https://github.com/sourcegraph/sourcegraph/pull/22755)\n- The `lang:` filter suggestions now show all supported, matching languages as the user types a language name. [#22765](https://github.com/sourcegraph/sourcegraph/pull/22765)\n- Code Insights can now be grouped into dashboards. [#22215](https://github.com/sourcegraph/sourcegraph/issues/22215)\n- Batch Changes changesets can now be [published from the Sourcegraph UI](https://docs.sourcegraph.com/batch_changes/how-tos/publishing_changesets#within-the-ui). [#18277](https://github.com/sourcegraph/sourcegraph/issues/18277)\n- The repository page now has a new button to view batch change changesets created in that specific repository, with a badge indicating how many changesets are currently open. [#22804](https://github.com/sourcegraph/sourcegraph/pull/22804)\n- Experimental: Search-based code insights can run over all repositories on the instance. To enable, use the feature flag `\"experimentalFeatures\": { \"codeInsightsAllRepos\": true }` and tick the checkbox in the insight creation/edit UI. [#22759](https://github.com/sourcegraph/sourcegraph/issues/22759)\n- Search References is a new search sidebar section to simplify learning about the available search filters directly where they are used. [#21539](https://github.com/sourcegraph/sourcegraph/issues/21539)", "### Changed", "- Backend Code Insights only fills historical data frames that have changed to reduce the number of searches required. [#22298](https://github.com/sourcegraph/sourcegraph/pull/22298)\n- Backend Code Insights displays data points for a fixed 6 months period in 2 week intervals, and will carry observations forward that are missing. [#22298](https://github.com/sourcegraph/sourcegraph/pull/22298)\n- Backend Code Insights now aggregate over 26 weeks instead of 6 months. [#22527](https://github.com/sourcegraph/sourcegraph/pull/22527)\n- Search queries now disallow specifying `rev:` without `repo:`. Note that to search across potentially multiple revisions, a query like `repo:.* rev:<revision>` remains valid. [#22705](https://github.com/sourcegraph/sourcegraph/pull/22705)\n- The extensions status bar on diff pages has been redesigned and now shows information for both the base and head commits. [#22123](https://github.com/sourcegraph/sourcegraph/pull/22123/files)\n- The `applyBatchChange` and `createBatchChange` mutations now accept an optional `publicationStates` argument to set the publication state of specific changesets within the batch change. [#22485](https://github.com/sourcegraph/sourcegraph/pull/22485) and [#22854](https://github.com/sourcegraph/sourcegraph/pull/22854)\n- Search queries now return up to 80 suggested filters. Previously we returned up to 24. [#22863](https://github.com/sourcegraph/sourcegraph/pull/22863)\n- GitHub code host connections can now include `repositoryQuery` entries that match more than 1000 repositories from the GitHub search API without requiring the previously documented work-around of splitting the query up with `created:` qualifiers, which is now done automatically. [#2562](https://github.com/sourcegraph/sourcegraph/issues/2562)", "### Fixed", "- The Batch Changes user and site credential encryption migrators added in Sourcegraph 3.28 could report zero progress when encryption was disabled, even though they had nothing to do. This has been fixed, and progress will now be correctly reported. [#22277](https://github.com/sourcegraph/sourcegraph/issues/22277)\n- Listing Github Entreprise org repos now returns internal repos as well. [#22339](https://github.com/sourcegraph/sourcegraph/pull/22339)\n- Jaeger works in Docker-compose deployments again. [#22691](https://github.com/sourcegraph/sourcegraph/pull/22691)\n- A bug where the pattern `)` makes the browser unresponsive. [#22738](https://github.com/sourcegraph/sourcegraph/pull/22738)\n- An issue where using `select:repo` in conjunction with `and` patterns did not yield expected repo results. [#22743](https://github.com/sourcegraph/sourcegraph/pull/22743)\n- The `isLocked` and `isDisabled` fields of GitHub repositories are now fetched correctly from the GraphQL API of GitHub Enterprise instances. Users that rely on the `repos` config in GitHub code host connections should update so that locked and disabled repositories defined in that list are actually skipped. [#22788](https://github.com/sourcegraph/sourcegraph/pull/22788)\n- Homepage no longer fails to load if there are invalid entries in user's search history. [#22857](https://github.com/sourcegraph/sourcegraph/pull/22857)\n- An issue where regexp query highlighting in the search bar would render incorrectly on Firefox. [#23043](https://github.com/sourcegraph/sourcegraph/pull/23043)\n- Code intelligence uploads and indexes are restricted to only site-admins. It was read-only for any user. [#22890](https://github.com/sourcegraph/sourcegraph/pull/22890)\n- Daily usage statistics are restricted to only site-admins. It was read-only for any user. [#23026](https://github.com/sourcegraph/sourcegraph/pull/23026)\n- Ephemeral storage requests now match their cache size requests for Kubernetes deployments. [#2953](https://github.com/sourcegraph/deploy-sourcegraph/pull/2953)", "### Removed", "- The experimental paginated search feature (the `stable:` keyword) has been removed, to be replaced with streaming search. [#22428](https://github.com/sourcegraph/sourcegraph/pull/22428)\n- The experimental extensions view page has been removed. [#22565](https://github.com/sourcegraph/sourcegraph/pull/22565)\n- A search query diagnostic that previously warned the user when quotes are interpreted literally has been removed. The literal meaning has been Sourcegraph's default search behavior for some time now. [#22892](https://github.com/sourcegraph/sourcegraph/pull/22892)\n- Non-root overlays were removed for `deploy-sourcegraph` in favor of using `non-privileged`. [#3404](https://github.com/sourcegraph/deploy-sourcegraph/pull/3404)", "### API docs (experimental)", "API docs is a new experimental feature of Sourcegraph ([learn more](https://docs.sourcegraph.com/code_intelligence/apidocs)). It is enabled by default in Sourcegraph 3.30.0.", "- API docs is enabled by default in Sourcegraph 3.30.0. It can be disabled by adding `\"apiDocs\": false` to the `experimentalFeatures` section of user settings.\n- The API docs landing page now indicates what API docs are and provide more info.\n- The API docs landing page now represents the code in the repository root, instead of an empty page.\n- Pages now correctly indicate it is an experimental feature, and include a feedback widget.\n- Subpages linked via the sidebar are now rendered much better, and have an expandable section.\n- Symbols in documentation now have distinct icons for e.g. functions/vars/consts/etc.\n- Symbols are now sorted in exported-first, alphabetical order.\n- Repositories without LSIF documentation data now show a friendly error page indicating what languages are supported, how to set it up, etc.\n- API docs can now distinguish between different types of symbols, tests, examples, benchmarks, etc. and whether symbols are public/private - to support filtering in the future.\n- Only public/exported symbols are included by default for now.\n- URL paths for Go packages are now friendlier, e.g. `/-/docs/cmd/frontend/auth` instead of `/-/docs/cmd-frontend-auth`.\n- URLs are now formatted by the language indexer, in a way that makes sense for the language, e.g. `#Mocks.CreateUserAndSave` instead of `#ypeMocksCreateUserAndSave` for a Go method `CreateUserAndSave` on type `Mocks`.\n- Go blank identifier assignments `var _ = ...` are no longer incorrectly included.\n- Go symbols defined within functions, e.g. a `var` inside a `func` scope are no longer incorrectly included.\n- `Functions`, `Variables`, and other top-level sections are no longer rendered empty if there are none in that section.\n- A new test suite for LSIF indexers implementing the Sourcegraph documentation extension to LSIF [is available](https://github.com/sourcegraph/lsif-static-doc).\n- We now emit the LSIF data needed to in the future support \"Jump to API docs\" from code views, \"View code\" from API docs, usage examples in API docs, and search indexing.\n- Various UI style issues, color contrast issues, etc. have been fixed.\n- Major improvements to the GraphQL APIs for API documentation.", "## 3.29.0", "### Added", "- Code Insights queries can now run concurrently up to a limit set by the `insights.query.worker.concurrency` site config. [#21219](https://github.com/sourcegraph/sourcegraph/pull/21219)\n- Code Insights workers now support a rate limit for query execution and historical data frame analysis using the `insights.query.worker.rateLimit` and `insights.historical.worker.rateLimit` site configurations. [#21533](https://github.com/sourcegraph/sourcegraph/pull/21533)\n- The GraphQL `Site` `SettingsSubject` type now has an `allowSiteSettingsEdits` field to allow clients to determine whether the instance uses the `GLOBAL_SETTINGS_FILE` environment variable. [#21827](https://github.com/sourcegraph/sourcegraph/pull/21827)\n- The Code Insights creation UI now remembers previously filled-in field values when returning to the form after having navigated away. [#21744](https://github.com/sourcegraph/sourcegraph/pull/21744)\n- The Code Insights creation UI now shows autosuggestions for the repository field. [#21699](https://github.com/sourcegraph/sourcegraph/pull/21699)\n- A new bulk operation to retry many changesets at once has been added to Batch Changes. [#21173](https://github.com/sourcegraph/sourcegraph/pull/21173)\n- A `security_event_logs` database table has been added in support of upcoming security-related efforts. [#21949](https://github.com/sourcegraph/sourcegraph/pull/21949)\n- Added featured Sourcegraph extensions query to the GraphQL API, as well as a section in the extension registry to display featured extensions. [#21665](https://github.com/sourcegraph/sourcegraph/pull/21665)\n- The search page now has a `create insight` button to create search-based insight based on your search query [#21943](https://github.com/sourcegraph/sourcegraph/pull/21943)\n- Added support for Terraform syntax highlighting. [#22040](https://github.com/sourcegraph/sourcegraph/pull/22040)\n- A new bulk operation to merge many changesets at once has been added to Batch Changes. [#21959](https://github.com/sourcegraph/sourcegraph/pull/21959)\n- Pings include aggregated usage for the Code Insights creation UI, organization visible insight count per insight type, and insight step size in days. [#21671](https://github.com/sourcegraph/sourcegraph/pull/21671)\n- Search-based insight creation UI now supports `count:` filter in data series query input. [#22049](https://github.com/sourcegraph/sourcegraph/pull/22049)\n- Code Insights background workers will now index commits in a new table `commit_index` for future optimization efforts. [#21994](https://github.com/sourcegraph/sourcegraph/pull/21994)\n- The creation UI for search-based insights now supports the `count:` filter in the data series query input. [#22049](https://github.com/sourcegraph/sourcegraph/pull/22049)\n- A new service, `worker`, has been introduced to run background jobs that were previously run in the frontend. See the [deployment documentation](https://docs.sourcegraph.com/admin/workers) for additional details. [#21768](https://github.com/sourcegraph/sourcegraph/pull/21768)", "### Changed", "- SSH public keys generated to access code hosts with batch changes now include a comment indicating they originated from Sourcegraph. [#20523](https://github.com/sourcegraph/sourcegraph/issues/20523)\n- The copy query button is now permanently enabled and `experimentalFeatures.copyQueryButton` setting has been deprecated. [#21364](https://github.com/sourcegraph/sourcegraph/pull/21364)\n- Search streaming is now permanently enabled and `experimentalFeatures.searchStreaming` setting has been deprecated. [#21522](https://github.com/sourcegraph/sourcegraph/pull/21522)\n- Pings removes the collection of aggregate search filter usage counts and adds a smaller set of aggregate usage counts for query operators, predicates, and pattern counts. [#21320](https://github.com/sourcegraph/sourcegraph/pull/21320)\n- Sourcegraph will now refuse to start if there are unfinished [out-of-band-migrations](https://docs.sourcegraph.com/admin/migrations) that are deprecated in the current version. See the [upgrade documentation](https://docs.sourcegraph.com/admin/updates) for changes to the upgrade process. [#20967](https://github.com/sourcegraph/sourcegraph/pull/20967)\n- Code Insight pages now have new URLs [#21856](https://github.com/sourcegraph/sourcegraph/pull/21856)\n- We are proud to bring you [an entirely new visual design for the Sourcegraph UI](https://about.sourcegraph.com/blog/introducing-sourcegraphs-new-ui/). We think you’ll find this new design improves your experience and sets the stage for some incredible features to come. Some of the highlights include:", " - **Refined search results:** The redesigned search bar provides more space for expressive queries, and the new results sidebar helps to discover search syntax without referencing documentation.\n - **Improved focus on code:** We’ve reduced non-essential UI elements to provide greater focus on the code itself, and positioned the most important items so they’re unobtrusive and located exactly where they are needed.\n - **Improved layouts:** We’ve improved pages like diff views to make them easier to use and to help find information quickly.\n - **New navigation:** A new global navigation provides immediate discoverability and access to current and future functionality.\n - **Promoting extensibility:** We've brought the extension registry back to the main navigation and improved its design and navigation.", " With bulk of the redesign complete, future releases will include more improvements and refinements.", "### Fixed", "- Stricter validation of structural search queries. The `type:` parameter is not supported for structural searches and returns an appropriate alert. [#21487](https://github.com/sourcegraph/sourcegraph/pull/21487)\n- Batch changeset specs that are not attached to changesets will no longer prematurely expire before the batch specs that they are associated with. [#21678](https://github.com/sourcegraph/sourcegraph/pull/21678)\n- The Y-axis of Code Insights line charts no longer start at a negative value. [#22018](https://github.com/sourcegraph/sourcegraph/pull/22018)\n- Correctly handle field aliases in the query (like `r:` versus `repo:`) when used with `contains` predicates. [#22105](https://github.com/sourcegraph/sourcegraph/pull/22105)\n- Running a code insight over a timeframe when the repository didn't yet exist doesn't break the entire insight anymore. [#21288](https://github.com/sourcegraph/sourcegraph/pull/21288)", "### Removed", "- The deprecated GraphQL `icon` field on CommitSearchResult and Repository was removed. [#21310](https://github.com/sourcegraph/sourcegraph/pull/21310)\n- The undocumented `index` filter was removed from search type-ahead suggestions. [#18806](https://github.com/sourcegraph/sourcegraph/issues/18806)\n- Code host connection tokens aren't used for creating changesets anymore when the user is site admin and no credential has been specified. [#16814](https://github.com/sourcegraph/sourcegraph/issues/16814)", "## 3.28.0", "### Added", "- Added `select:commit.diff.added` and `select:commit.diff.removed` for `type:diff` search queries. These selectors return commit diffs only if a pattern matches in `added` (respespectively, `removed`) lines. [#20328](https://github.com/sourcegraph/sourcegraph/pull/20328)\n- Additional language autocompletions for the `lang:` filter in the search bar. [#20535](https://github.com/sourcegraph/sourcegraph/pull/20535)\n- Steps in batch specs can now have an `if:` attribute to enable conditional execution of different steps. [#20701](https://github.com/sourcegraph/sourcegraph/pull/20701)\n- Extensions can now log messages through `sourcegraph.app.log` to aid debugging user issues. [#20474](https://github.com/sourcegraph/sourcegraph/pull/20474)\n- Bulk comments on many changesets are now available in Batch Changes. [#20361](https://github.com/sourcegraph/sourcegraph/pull/20361)\n- Batch specs are now viewable when previewing changesets. [#19534](https://github.com/sourcegraph/sourcegraph/issues/19534)\n- Added a new UI for creating code insights. [#20212](https://github.com/sourcegraph/sourcegraph/issues/20212)", "### Changed", "- User and site credentials used in Batch Changes are now encrypted in the database if encryption is enabled with the `encryption.keys` config. [#19570](https://github.com/sourcegraph/sourcegraph/issues/19570)\n- All Sourcegraph images within [deploy-sourcegraph](https://github.com/sourcegraph/deploy-sourcegraph) now specify the registry. Thanks! @k24dizzle [#2901](https://github.com/sourcegraph/deploy-sourcegraph/pull/2901).\n- Default reviewers are now added to Bitbucket Server PRs opened by Batch Changes. [#20551](https://github.com/sourcegraph/sourcegraph/pull/20551)\n- The default memory requirements for the `redis-*` containers have been raised by 1GB (to a new total of 7GB). This change allows Redis to properly run its key-eviction routines (when under memory pressure) without getting killed by the host machine. This affects both the docker-compose and Kubernetes deployments. [sourcegraph/deploy-sourcegraph-docker#373](https://github.com/sourcegraph/deploy-sourcegraph-docker/pull/373) and [sourcegraph/deploy-sourcegraph#2898](https://github.com/sourcegraph/deploy-sourcegraph/pull/2898)\n- Only site admins can now list users on an instance. [#20619](https://github.com/sourcegraph/sourcegraph/pull/20619)\n- Repository permissions can now be enabled for site admins via the `authz.enforceForSiteAdmins` setting. [#20674](https://github.com/sourcegraph/sourcegraph/pull/20674)\n- Site admins can no longer view user added code host configuration. [#20851](https://github.com/sourcegraph/sourcegraph/pull/20851)\n- Site admins cannot add access tokens for any user by default. [#20988](https://github.com/sourcegraph/sourcegraph/pull/20988)\n- Our namespaced overlays now only scrape container metrics within that namespace. [#2969](https://github.com/sourcegraph/deploy-sourcegraph/pull/2969)\n- The extension registry main page has a new visual design that better conveys the most useful information about extensions, and individual extension pages have better information architecture. [#20822](https://github.com/sourcegraph/sourcegraph/pull/20822)", "### Fixed", "- Search returned inconsistent result counts when a `count:` limit was not specified.\n- Indexed search failed when the `master` branch needed indexing but was not the default. [#20260](https://github.com/sourcegraph/sourcegraph/pull/20260)\n- `repo:contains(...)` built-in did not respect parameters that affect repo filtering (e.g., `repogroup`, `fork`). It now respects these. [#20339](https://github.com/sourcegraph/sourcegraph/pull/20339)\n- An issue where duplicate results would render for certain `or`-expressions. [#20480](https://github.com/sourcegraph/sourcegraph/pull/20480)\n- Issue where the search query bar suggests that some `lang` values are not valid. [#20534](https://github.com/sourcegraph/sourcegraph/pull/20534)\n- Pull request event webhooks received from GitHub with unexpected actions no longer cause panics. [#20571](https://github.com/sourcegraph/sourcegraph/pull/20571)\n- Repository search patterns like `^repo/(prefix-suffix|prefix)$` now correctly match both `repo/prefix-suffix` and `repo/prefix`. [#20389](https://github.com/sourcegraph/sourcegraph/issues/20389)\n- Ephemeral storage requests and limits now match the default cache size to avoid Symbols pods being evicted. The symbols pod now requires 10GB of ephemeral space as a minimum to scheduled. [#2369](https://github.com/sourcegraph/deploy-sourcegraph/pull/2369)\n- Minor query syntax highlighting bug for `repo:contains` predicate. [#21038](https://github.com/sourcegraph/sourcegraph/pull/21038)\n- An issue causing diff and commit results with file filters to return invalid results. [#21039](https://github.com/sourcegraph/sourcegraph/pull/21039)\n- All databases now have the Kubernetes Quality of Service class of 'Guaranteed' which should reduce the chance of them\n being evicted during NodePressure events. [#2900](https://github.com/sourcegraph/deploy-sourcegraph/pull/2900)\n- An issue causing diff views to display without syntax highlighting [#21160](https://github.com/sourcegraph/sourcegraph/pull/21160)", "### Removed", "- The deprecated `SetRepositoryEnabled` mutation was removed. [#21044](https://github.com/sourcegraph/sourcegraph/pull/21044)", "## 3.27.5", "### Fixed", "- Fix scp style VCS url parsing. [#20799](https://github.com/sourcegraph/sourcegraph/pull/20799)", "## 3.27.4", "### Fixed", "- Fixed an issue related to Gitolite repos with `@` being prepended with a `?`. [#20297](https://github.com/sourcegraph/sourcegraph/pull/20297)\n- Add missing return from handler when DisableAutoGitUpdates is true. [#20451](https://github.com/sourcegraph/sourcegraph/pull/20451)", "## 3.27.3", "### Fixed", "- Pushing batch changes to Bitbucket Server code hosts over SSH was broken in 3.27.0, and has been fixed. [#20324](https://github.com/sourcegraph/sourcegraph/issues/20324)", "## 3.27.2", "### Fixed", "- Fixed an issue with our release tooling that was preventing all images from being tagged with the correct version.\n All sourcegraph images have the proper release version now.", "## 3.27.1", "### Fixed", "- Indexed search failed when the `master` branch needed indexing but was not the default. [#20260](https://github.com/sourcegraph/sourcegraph/pull/20260)\n- Fixed a regression that caused \"other\" code hosts urls to not be built correctly which prevents code to be cloned / updated in 3.27.0. This change will provoke some cloning errors on repositories that are already sync'ed, until the next code host sync. [#20258](https://github.com/sourcegraph/sourcegraph/pull/20258)", "## 3.27.0", "### Added", "- `count:` now supports \"all\" as value. Queries with `count:all` will return up to 999999 results. [#19756](https://github.com/sourcegraph/sourcegraph/pull/19756)\n- Credentials for Batch Changes are now validated when adding them. [#19602](https://github.com/sourcegraph/sourcegraph/pull/19602)\n- Batch Changes now ignore repositories that contain a `.batchignore` file. [#19877](https://github.com/sourcegraph/sourcegraph/pull/19877) and [src-cli#509](https://github.com/sourcegraph/src-cli/pull/509)\n- Side-by-side diff for commit visualization. [#19553](https://github.com/sourcegraph/sourcegraph/pull/19553)\n- The site configuration now supports defining batch change rollout windows, which can be used to slow or disable pushing changesets at particular times of day or days of the week. [#19796](https://github.com/sourcegraph/sourcegraph/pull/19796), [#19797](https://github.com/sourcegraph/sourcegraph/pull/19797), and [#19951](https://github.com/sourcegraph/sourcegraph/pull/19951).\n- Search functionality via built-in `contains` predicate: `repo:contains(...)`, `repo:contains.file(...)`, `repo:contains.content(...)`, repo:contains.commit.after(...)`. [#18584](https://github.com/sourcegraph/sourcegraph/issues/18584)\n- Database encryption, external service config & user auth data can now be encrypted in the database using the `encryption.keys` config. See [the docs](https://docs.sourcegraph.com/admin/encryption) for more info.\n- Repositories that gitserver fails to clone or fetch are now gradually moved to the back of the background update queue instead of remaining at the front. [#20204](https://github.com/sourcegraph/sourcegraph/pull/20204)\n- The new `disableAutoCodeHostSyncs` setting allows site admins to disable any periodic background syncing of configured code host connections. That includes syncing of repository metadata (i.e. not git updates, use `disableAutoGitUpdates` for that), permissions and batch changes changesets, but may include other data we'd sync from the code host API in the future.", "### Changed", "- Bumped the minimum supported version of Postgres from `9.6` to `12`. The upgrade procedure is mostly automated for existing deployments, but may require action if using the single-container deployment or an external database. See the [upgrade documentation](https://docs.sourcegraph.com/admin/updates) for your deployment type for detailed instructions.\n- Changesets in batch changes will now be marked as archived instead of being detached when a new batch spec that doesn't include the changesets is applied. Once they're archived users can manually detach them in the UI. [#19527](https://github.com/sourcegraph/sourcegraph/pull/19527)\n- The default replica count on `sourcegraph-frontend` and `precise-code-intel-worker` for Kubernetes has changed from `1` -> `2`.\n- Changes to code monitor trigger search queries [#19680](https://github.com/sourcegraph/sourcegraph/pull/19680)\n - A `repo:` filter is now required. This is due to an existing limitations where only 50 repositories can be searched at a time, so using a `repo:` filter makes sure the right code is being searched. Any existing code monitor without `repo:` in the trigger query will continue to work (with the limitation that not all repositories will be searched) but will require a `repo:` filter to be added when making any changes to it.\n - A `patternType` filter is no longer required. `patternType:literal` will be added to a code monitor query if not specified.\n - Added a new checklist UI to make it more intuitive to create code monitor trigger queries.\n- Deprecated the GraphQL `icon` field on `GenericSearchResultInterface`. It will be removed in a future release. [#20028](https://github.com/sourcegraph/sourcegraph/pull/20028/files)\n- Creating changesets through Batch Changes as a site-admin without configured Batch Changes credentials has been deprecated. Please configure user or global credentials before Sourcegraph 3.29 to not experience any interruptions in changeset creation. [#20143](https://github.com/sourcegraph/sourcegraph/pull/20143)\n- Deprecated the GraphQL `limitHit` field on `LineMatch`. It will be removed in a future release. [#20164](https://github.com/sourcegraph/sourcegraph/pull/20164)", "### Fixed", "- A regression caused by search onboarding tour logic to never focus input in the search bar on the homepage. Input now focuses on the homepage if the search tour isn't in effect. [#19678](https://github.com/sourcegraph/sourcegraph/pull/19678)\n- New changes of a Perforce depot will now be reflected in `master` branch after the initial clone. [#19718](https://github.com/sourcegraph/sourcegraph/pull/19718)\n- Gitolite and Other type code host connection configuration can be correctly displayed. [#19976](https://github.com/sourcegraph/sourcegraph/pull/19976)\n- Fixed a regression that caused user and code host limits to be ignored. [#20089](https://github.com/sourcegraph/sourcegraph/pull/20089)\n- A regression where incorrect query highlighting happens for certain quoted values. [#20110](https://github.com/sourcegraph/sourcegraph/pull/20110)\n- We now respect the `disableAutoGitUpdates` setting when cloning or fetching repos on demand and during cleanup tasks that may re-clone old repos. [#20194](https://github.com/sourcegraph/sourcegraph/pull/20194)", "## 3.26.3", "### Fixed", "- Setting `gitMaxCodehostRequestsPerSecond` to `0` now actually blocks all Git operations happening on the gitserver. [#19716](https://github.com/sourcegraph/sourcegraph/pull/19716)", "## 3.26.2", "### Fixed", "- Our indexed search logic now correctly handles de-duplication of search results across multiple replicas. [#19743](https://github.com/sourcegraph/sourcegraph/pull/19743)", "## 3.26.1", "### Added", "- Experimental: Sync permissions of Perforce depots through the Sourcegraph UI. To enable, use the feature flag `\"experimentalFeatures\": { \"perforce\": \"enabled\" }`. For more information, see [how to enable permissions for your Perforce depots](https://docs.sourcegraph.com/admin/repo/perforce). [#16705](https://github.com/sourcegraph/sourcegraph/issues/16705)\n- Added support for user email headers in the HTTP auth proxy. See [HTTP Auth Proxy docs](https://docs.sourcegraph.com/admin/auth#http-authentication-proxies) for more information.\n- Ignore locked and disabled GitHub Enterprise repositories. [#19500](https://github.com/sourcegraph/sourcegraph/pull/19500)\n- Remote code host git operations (such as `clone` or `ls-remote`) can now be rate limited beyond concurrency (which was already possible with `gitMaxConcurrentClones`). Set `gitMaxCodehostRequestsPerSecond` in site config to control the maximum rate of these operations per git-server instance. [#19504](https://github.com/sourcegraph/sourcegraph/pull/19504)", "### Changed", "-", "### Fixed", "- Commit search returning duplicate commits. [#19460](https://github.com/sourcegraph/sourcegraph/pull/19460)\n- Clicking the Code Monitoring tab tries to take users to a non-existent repo. [#19525](https://github.com/sourcegraph/sourcegraph/pull/19525)\n- Diff and commit search not highlighting search terms correctly for some files. [#19543](https://github.com/sourcegraph/sourcegraph/pull/19543), [#19639](https://github.com/sourcegraph/sourcegraph/pull/19639)\n- File actions weren't appearing on large window sizes in Firefox and Safari. [#19380](https://github.com/sourcegraph/sourcegraph/pull/19380)", "### Removed", "-", "## 3.26.0", "### Added", "- Searches are streamed into Sourcegraph by default. [#19300](https://github.com/sourcegraph/sourcegraph/pull/19300)\n - This gives a faster time to first result.\n - Several heuristics around result limits have been improved. You should see more consistent result counts now.\n - Can be disabled with the setting `experimentalFeatures.streamingSearch`.\n- Opsgenie API keys can now be added via an environment variable. [#18662](https://github.com/sourcegraph/sourcegraph/pull/18662)\n- It's now possible to control where code insights are displayed through the boolean settings `insights.displayLocation.homepage`, `insights.displayLocation.insightsPage` and `insights.displayLocation.directory`. [#18979](https://github.com/sourcegraph/sourcegraph/pull/18979)\n- Users can now create changesets in batch changes on repositories that are cloned using SSH. [#16888](https://github.com/sourcegraph/sourcegraph/issues/16888)\n- Syntax highlighting for Elixir, Elm, REG, Julia, Move, Nix, Puppet, VimL, Coq. [#19282](https://github.com/sourcegraph/sourcegraph/pull/19282)\n- `BUILD.in` files are now highlighted as Bazel/Starlark build files. Thanks to @jjwon0 [#19282](https://github.com/sourcegraph/sourcegraph/pull/19282)\n- `*.pyst` and `*.pyst-include` are now highlighted as Python files. Thanks to @jjwon0 [#19282](https://github.com/sourcegraph/sourcegraph/pull/19282)\n- The code monitoring feature flag is now enabled by default. [#19295](https://github.com/sourcegraph/sourcegraph/pull/19295)\n- New query field `select` enables returning only results of the desired type. See [documentation](https://docs.sourcegraph.com/code_search/reference/language#select) for details. [#19236](https://github.com/sourcegraph/sourcegraph/pull/19236)\n- Syntax highlighting for Elixer, Elm, REG, Julia, Move, Nix, Puppet, VimL thanks to @rvantonder\n- `BUILD.in` files are now highlighted as Bazel/Starlark build files. Thanks to @jjwon0\n- `*.pyst` and `*.pyst-include` are now highlighted as Python files. Thanks to @jjwon0\n- Added a `search.defaultCaseSensitive` setting to configure whether query patterns should be treated case sensitivitely by default.", "### Changed", "- Campaigns have been renamed to Batch Changes! See [#18771](https://github.com/sourcegraph/sourcegraph/issues/18771) for a detailed log on what has been renamed.\n - A new [Sourcegraph CLI](https://docs.sourcegraph.com/cli) version will use `src batch [preview|apply]` commands, while keeping the old ones working to be used with older Sourcegraph versions.\n - Old URLs in the application and in the documentation will redirect.\n - GraphQL API entities with \"campaign\" in their name have been deprecated and have new Batch Changes counterparts:\n - Deprecated GraphQL entities: `CampaignState`, `Campaign`, `CampaignSpec`, `CampaignConnection`, `CampaignsCodeHostConnection`, `CampaignsCodeHost`, `CampaignsCredential`, `CampaignDescription`\n - Deprecated GraphQL mutations: `createCampaign`, `applyCampaign`, `moveCampaign`, `closeCampaign`, `deleteCampaign`, `createCampaignSpec`, `createCampaignsCredential`, `deleteCampaignsCredential`\n - Deprecated GraphQL queries: `Org.campaigns`, `User.campaigns`, `User.campaignsCodeHosts`, `camapigns`, `campaign`\n - Site settings with `campaigns` in their name have been replaced with equivalent `batchChanges` settings.\n- A repository's `remote.origin.url` is not stored on gitserver disk anymore. Note: if you use the experimental feature `customGitFetch` your setting may need to be updated to specify the remote URL. [#18535](https://github.com/sourcegraph/sourcegraph/pull/18535)\n- Repositories and files containing spaces will now render with escaped spaces in the query bar rather than being\n quoted. [#18642](https://github.com/sourcegraph/sourcegraph/pull/18642)\n- Sourcegraph is now built with Go 1.16. [#18447](https://github.com/sourcegraph/sourcegraph/pull/18447)\n- Cursor hover information in the search query bar will now display after 150ms (previously 0ms). [#18916](https://github.com/sourcegraph/sourcegraph/pull/18916)\n- The `repo.cloned` column is deprecated in favour of `gitserver_repos.clone_status`. It will be removed in a subsequent release.\n- Precision class indicators have been improved for code intelligence results in both the hover overlay as well as the definition and references locations panel. [#18843](https://github.com/sourcegraph/sourcegraph/pull/18843)\n- Pings now contain added, aggregated campaigns usage data: aggregate counts of unique monthly users and Weekly campaign and changesets counts for campaign cohorts created in the last 12 months. [#18604](https://github.com/sourcegraph/sourcegraph/pull/18604)", "### Fixed", "- Auto complete suggestions for repositories and files containing spaces will now be automatically escaped when accepting the suggestion. [#18635](https://github.com/sourcegraph/sourcegraph/issues/18635)\n- An issue causing repository results containing spaces to not be clickable in some cases. [#18668](https://github.com/sourcegraph/sourcegraph/pull/18668)\n- Closing a batch change now correctly closes the entailed changesets, when requested by the user. [#18957](https://github.com/sourcegraph/sourcegraph/pull/18957)\n- TypesScript highlighting bug. [#15930](https://github.com/sourcegraph/sourcegraph/issues/15930)\n- The number of shards is now reported accurately in Site Admin > Repository Status > Settings > Indexing. [#19265](https://github.com/sourcegraph/sourcegraph/pull/19265)", "### Removed", "- Removed the deprecated GraphQL fields `SearchResults.repositoriesSearched` and `SearchResults.indexedRepositoriesSearched`.\n- Removed the deprecated search field `max`\n- Removed the `experimentalFeatures.showBadgeAttachments` setting", "## 3.25.2", "### Fixed", "- A security vulnerability with in the authentication workflow has been fixed. [#18686](https://github.com/sourcegraph/sourcegraph/pull/18686)", "## 3.25.1", "### Added", "- Experimental: Sync Perforce depots directly through the Sourcegraph UI. To enable, use the feature flag `\"experimentalFeatures\": { \"perforce\": \"enabled\" }`. For more information, see [how to add your Perforce depots](https://docs.sourcegraph.com/admin/repo/perforce). [#16703](https://github.com/sourcegraph/sourcegraph/issues/16703)", "## 3.25.0", "**IMPORTANT** Sourcegraph now uses Go 1.15. This may break AWS RDS database connections with older x509 certificates. Please follow the Amazon [docs](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL-certificate-rotation.html) to rotate your certificate.", "### Added", "- New site config option `\"log\": { \"sentry\": { \"backendDSN\": \"<REDACTED>\" } }` to use a separate Sentry project for backend errors. [#17363](https://github.com/sourcegraph/sourcegraph/pull/17363)\n- Structural search now supports searching indexed branches other than default. [#17726](https://github.com/sourcegraph/sourcegraph/pull/17726)\n- Structural search now supports searching unindexed revisions. [#17967](https://github.com/sourcegraph/sourcegraph/pull/17967)\n- New site config option `\"allowSignup\"` for SAML authentication to determine if automatically create new users is allowed. [#17989](https://github.com/sourcegraph/sourcegraph/pull/17989)\n- Experimental: The webapp can now stream search results to the client, improving search performance. To enable it, add `{ \"experimentalFeatures\": { \"searchStreaming\": true } }` in user settings. [#16097](https://github.com/sourcegraph/sourcegraph/pull/16097)\n- New product research sign-up page. This can be accessed by all users in their user settings. [#17945](https://github.com/sourcegraph/sourcegraph/pull/17945)\n- New site config option `productResearchPage.enabled` to disable access to the product research sign-up page. [#17945](https://github.com/sourcegraph/sourcegraph/pull/17945)\n- Pings now contain Sourcegraph extension activation statistics. [#16421](https://github.com/sourcegraph/sourcegraph/pull/16421)\n- Pings now contain aggregate Sourcegraph extension activation statistics: the number of users and number of activations per (public) extension per week, and the number of total extension users per week and average extensions activated per user. [#16421](https://github.com/sourcegraph/sourcegraph/pull/16421)\n- Pings now contain aggregate code insights usage data: total insight views, interactions, edits, creations, removals, and counts of unique users that view and create insights. [#16421](https://github.com/sourcegraph/sourcegraph/pull/17805)\n- When previewing a campaign spec, changesets can be filtered by current state or the action(s) to be performed. [#16960](https://github.com/sourcegraph/sourcegraph/issues/16960)", "### Changed", "- Alert solutions links included in [monitoring alerts](https://docs.sourcegraph.com/admin/observability/alerting) now link to the relevant documentation version. [#17828](https://github.com/sourcegraph/sourcegraph/pull/17828)\n- Secrets (such as access tokens and passwords) will now appear as REDACTED when editing external service config, and in graphql API responses. [#17261](https://github.com/sourcegraph/sourcegraph/issues/17261)\n- Sourcegraph is now built with Go 1.15\n - Go `1.15` introduced changes to SSL/TLS connection validation which requires certificates to include a `SAN`. This field was not included in older certificates and clients relied on the `CN` field. You might see an error like `x509: certificate relies on legacy Common Name field`. We recommend that customers using Sourcegraph with an external database and connecting to it using SSL/TLS check whether the certificate is up to date.\n - RDS Customers please reference [AWS' documentation on updating the SSL/TLS certificate](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL-certificate-rotation.html).\n- Search results on `.rs` files now recommend `lang:rust` instead of `lang:renderscript` as a filter. [#18316](https://github.com/sourcegraph/sourcegraph/pull/18316)\n- Campaigns users creating Personal Access Tokens on GitHub are now asked to request the `user:email` scope in addition to the [previous scopes](https://docs.sourcegraph.com/@3.24/admin/external_service/github#github-api-token-and-access). This will be used in a future Sourcegraph release to display more fine-grained information on the progress of pull requests. [#17555](https://github.com/sourcegraph/sourcegraph/issues/17555)", "### Fixed", "- Fixes an issue that prevented the hard deletion of a user if they had saved searches. [#17461](https://github.com/sourcegraph/sourcegraph/pull/17461)\n- Fixes an issue that caused some missing results for `type:commit` when a pattern was used instead of the `message` field. [#17490](https://github.com/sourcegraph/sourcegraph/pull/17490#issuecomment-764004758)\n- Fixes an issue where cAdvisor-based alerts would not fire correctly for services with multiple replicas. [#17600](https://github.com/sourcegraph/sourcegraph/pull/17600)\n- Significantly improved performance of structural search on monorepo deployments [#17846](https://github.com/sourcegraph/sourcegraph/pull/17846)\n- Fixes an issue where upgrades on Kubernetes may fail due to null environment variable lists in deployment manifests [#1781](https://github.com/sourcegraph/deploy-sourcegraph/pull/1781)\n- Fixes an issue where counts on search filters were inaccurate. [#18158](https://github.com/sourcegraph/sourcegraph/pull/18158)\n- Fixes services with emptyDir volumes being evicted from nodes. [#1852](https://github.com/sourcegraph/deploy-sourcegraph/pull/1852)", "### Removed", "- Removed the `search.migrateParser` setting. As of 3.20 and onward, a new parser processes search queries by default. Previously, `search.migrateParser` was available to enable the legacy parser. Enabling/disabling this setting now no longer has any effect. [#17344](https://github.com/sourcegraph/sourcegraph/pull/17344)", "## 3.24.1", "### Fixed", "- Fixes an issue that SAML is not able to proceed with the error `Expected Enveloped and C14N transforms`. [#13032](https://github.com/sourcegraph/sourcegraph/issues/13032)", "## 3.24.0", "### Added", "- Panels in the [Sourcegraph monitoring dashboards](https://docs.sourcegraph.com/admin/observability/metrics#grafana) now:\n - include links to relevant alerts documentation and the new [monitoring dashboards reference](https://docs.sourcegraph.com/admin/observability/dashboards). [#16939](https://github.com/sourcegraph/sourcegraph/pull/16939)\n - include alert events and version changes annotations that can be enabled from the top of each service dashboard. [#17198](https://github.com/sourcegraph/sourcegraph/pull/17198)\n- Suggested filters in the search results page can now be scrolled. [#17097](https://github.com/sourcegraph/sourcegraph/pull/17097)\n- Structural search queries can now be used in saved searches by adding `patternType:structural`. [#17265](https://github.com/sourcegraph/sourcegraph/pull/17265)", "### Changed", "- Dashboard links included in [monitoring alerts](https://docs.sourcegraph.com/admin/observability/alerting) now:\n - link directly to the relevant Grafana panel, instead of just the service dashboard. [#17014](https://github.com/sourcegraph/sourcegraph/pull/17014)\n - link to a time frame relevant to the alert, instead of just the past few hours. [#17034](https://github.com/sourcegraph/sourcegraph/pull/17034)\n- Added `serviceKind` field of the `ExternalServiceKind` type to `Repository.externalURLs` GraphQL API, `serviceType` field is deprecated and will be removed in the future releases. [#14979](https://github.com/sourcegraph/sourcegraph/issues/14979)\n- Deprecated the GraphQL fields `SearchResults.repositoriesSearched` and `SearchResults.indexedRepositoriesSearched`.\n- The minimum Kubernetes version required to use the [Kubernetes deployment option](https://docs.sourcegraph.com/admin/install/kubernetes) is now [v1.15 (released June 2019)](https://kubernetes.io/blog/2019/06/19/kubernetes-1-15-release-announcement/).", "### Fixed", "- Imported changesets acquired an extra button to download the \"generated diff\", which did nothing, since imported changesets don't have a generated diff. This button has been removed. [#16778](https://github.com/sourcegraph/sourcegraph/issues/16778)\n- Quoted global filter values (case, patterntype) are now properly extracted and set in URL parameters. [#16186](https://github.com/sourcegraph/sourcegraph/issues/16186)\n- The endpoint for \"Open in Sourcegraph\" functionality in editor extensions now uses code host connection information to resolve the repository, which makes it more correct and respect the `repositoryPathPattern` setting. [#16846](https://github.com/sourcegraph/sourcegraph/pull/16846)\n- Fixed an issue that prevented search expressions of the form `repo:foo (rev:a or rev:b)` from evaluating all revisions [#16873](https://github.com/sourcegraph/sourcegraph/pull/16873)\n- Updated language detection library. Includes language detection for `lang:starlark`. [#16900](https://github.com/sourcegraph/sourcegraph/pull/16900)\n- Fixed retrieving status for indexed tags and deduplicated main branches in the indexing settings page. [#13787](https://github.com/sourcegraph/sourcegraph/issues/13787)\n- Specifying a ref that doesn't exist would show an alert, but still return results [#15576](https://github.com/sourcegraph/sourcegraph/issues/15576)\n- Fixed search highlighting the wrong line. [#10468](https://github.com/sourcegraph/sourcegraph/issues/10468)\n- Fixed an issue where searches of the form `foo type:file` returned results of type `path` too. [#17076](https://github.com/sourcegraph/sourcegraph/issues/17076)\n- Fixed queries like `(type:commit or type:diff)` so that if the query matches both the commit message and the diff, both are returned as results. [#16899](https://github.com/sourcegraph/sourcegraph/issues/16899)\n- Fixed container monitoring and provisioning dashboard panels not displaying metrics in certain deployment types and environments. If you continue to have issues with these panels not displaying any metrics after upgrading, please [open an issue](https://github.com/sourcegraph/sourcegraph/issues/new).\n- Fixed a nonexistent field in site configuration being marked as \"required\" when configuring PagerDuty alert notifications. [#17277](https://github.com/sourcegraph/sourcegraph/pull/17277)\n- Fixed cases of incorrect highlighting for symbol definitions in the definitions panel. [#17258](https://github.com/sourcegraph/sourcegraph/pull/17258)\n- Fixed a Cross-Site Scripting vulnerability where quick links created on the homepage were not sanitized and allowed arbitrary JavaScript execution. [#17099](https://github.com/sourcegraph/sourcegraph/pull/17099)", "### Removed", "- Interactive mode has now been removed. [#16868](https://github.com/sourcegraph/sourcegraph/pull/16868).", "## 3.23.0", "### Added", "- Password reset link expiration can be customized via `auth.passwordResetLinkExpiry` in the site config. [#13999](https://github.com/sourcegraph/sourcegraph/issues/13999)\n- Campaign steps may now include environment variables from outside of the campaign spec using [array syntax](http://docs.sourcegraph.com/campaigns/references/campaign_spec_yaml_reference#environment-array). [#15822](https://github.com/sourcegraph/sourcegraph/issues/15822)\n- The total size of all Git repositories and the lines of code for indexed branches are displayed in the site admin overview. [#15125](https://github.com/sourcegraph/sourcegraph/issues/15125)\n- Extensions can now add decorations to files on the sidebar tree view and tree page through the experimental `FileDecoration` API. [#15833](https://github.com/sourcegraph/sourcegraph/pull/15833)\n- Extensions can now easily query the Sourcegraph GraphQL API through a dedicated API method. [#15566](https://github.com/sourcegraph/sourcegraph/pull/15566)\n- Individual changesets can now be downloaded as a diff. [#16098](https://github.com/sourcegraph/sourcegraph/issues/16098)\n- The campaigns preview page is much more detailed now, especially when updating existing campaigns. [#16240](https://github.com/sourcegraph/sourcegraph/pull/16240)\n- When a newer version of a campaign spec is uploaded, a message is now displayed when viewing the campaign or an outdated campaign spec. [#14532](https://github.com/sourcegraph/sourcegraph/issues/14532)\n- Changesets in a campaign can now be searched by title and repository name. [#15781](https://github.com/sourcegraph/sourcegraph/issues/15781)\n- Experimental: [`transformChanges` in campaign specs](https://docs.sourcegraph.com/campaigns/references/campaign_spec_yaml_reference#transformchanges) is now available as a feature preview to allow users to create multiple changesets in a single repository. [#16235](https://github.com/sourcegraph/sourcegraph/pull/16235)\n- The `gitUpdateInterval` site setting was added to allow custom git update intervals based on repository names. [#16765](https://github.com/sourcegraph/sourcegraph/pull/16765)\n- Various additions to syntax highlighting and hover tooltips in the search query bar (e.g., regular expressions). Can be disabled with `{ \"experimentalFeatures\": { \"enableSmartQuery\": false } }` in case of unlikely adverse effects. [#16742](https://github.com/sourcegraph/sourcegraph/pull/16742)\n- Search queries may now scope subexpressions across repositories and files, and also allow greater freedom for combining search filters. See the updated documentation on [search subexpressions](https://docs.sourcegraph.com/code_search/tutorials/search_subexpressions) to learn more. [#16866](https://github.com/sourcegraph/sourcegraph/pull/16866)", "### Changed", "- Search indexer tuned to wait longer before assuming a deadlock has occurred. Previously if the indexserver had many cores (40+) and indexed a monorepo it could give up. [#16110](https://github.com/sourcegraph/sourcegraph/pull/16110)\n- The total size of all Git repositories and the lines of code for indexed branches will be sent back in pings as part of critical telemetry. [#16188](https://github.com/sourcegraph/sourcegraph/pull/16188)\n- The `gitserver` container now has a dependency on Postgres. This does not require any additional configuration unless access to Postgres requires a sidecar proxy / firewall rules. [#16121](https://github.com/sourcegraph/sourcegraph/pull/16121)\n- Licensing is now enforced for campaigns: creating a campaign with more than five changesets requires a valid license. Please [contact Sourcegraph with any licensing questions](https://about.sourcegraph.com/contact/sales/). [#15715](https://github.com/sourcegraph/sourcegraph/issues/15715)", "### Fixed", "- Syntax highlighting on files with mixed extension case (e.g. `.CPP` vs `.cpp`) now works as expected. [#11327](https://github.com/sourcegraph/sourcegraph/issues/11327)\n- After applying a campaign, some GitLab MRs might have had outdated state shown in the UI until the next sync with the code host. [#16100](https://github.com/sourcegraph/sourcegraph/pull/16100)\n- The web app no longer sends stale text document content to extensions. [#14965](https://github.com/sourcegraph/sourcegraph/issues/14965)\n- The blob viewer now supports multiple decorations per line as intended. [#15063](https://github.com/sourcegraph/sourcegraph/issues/15063)\n- Repositories with plus signs in their name can now be navigated to as expected. [#15079](https://github.com/sourcegraph/sourcegraph/issues/15079)", "### Removed", "-", "## 3.22.1", "### Changed", "- Reduced memory and CPU required for updating the code intelligence commit graph [#16517](https://github.com/sourcegraph/sourcegraph/pull/16517)", "## 3.22.0", "### Added", "- GraphQL and TOML syntax highlighting is now back (special thanks to @rvantonder) [#13935](https://github.com/sourcegraph/sourcegraph/issues/13935)\n- Zig and DreamMaker syntax highlighting.\n- Campaigns now support publishing GitHub draft PRs and GitLab WIP MRs. [#7998](https://github.com/sourcegraph/sourcegraph/issues/7998)\n- `indexed-searcher`'s watchdog can be configured and has additional instrumentation. This is useful when diagnosing [zoekt-webserver is restarting due to watchdog](https://docs.sourcegraph.com/admin/observability/troubleshooting#scenario-zoekt-webserver-is-restarting-due-to-watchdog). [#15148](https://github.com/sourcegraph/sourcegraph/pull/15148)\n- Pings now contain Redis & Postgres server versions. [14405](https://github.com/sourcegraph/sourcegraph/14405)\n- Aggregated usage data of the search onboarding tour is now included in pings. The data tracked are: total number of views of the onboarding tour, total number of views of each step in the onboarding tour, total number of tours closed. [#15113](https://github.com/sourcegraph/sourcegraph/pull/15113)\n- Users can now specify credentials for code hosts to enable campaigns for non site-admin users. [#15506](https://github.com/sourcegraph/sourcegraph/pull/15506)\n- A `campaigns.restrictToAdmins` site configuration option has been added to prevent non site-admin users from using campaigns. [#15785](https://github.com/sourcegraph/sourcegraph/pull/15785)\n- Number of page views on campaign apply page, page views on campaign details page after create/update, closed campaigns, created campaign specs and changesets specs and the sum of changeset diff stats will be sent back in pings. [#15279](https://github.com/sourcegraph/sourcegraph/pull/15279)\n- Users can now explicitly set their primary email address. [#15683](https://github.com/sourcegraph/sourcegraph/pull/15683)\n- \"[Why code search is still needed for monorepos](https://docs.sourcegraph.com/adopt/code_search_in_monorepos)\" doc page", "### Changed", "- Improved contrast / visibility in comment syntax highlighting. [#14546](https://github.com/sourcegraph/sourcegraph/issues/14546)\n- Campaigns are no longer in beta. [#14900](https://github.com/sourcegraph/sourcegraph/pull/14900)\n- Campaigns now have a fancy new icon. [#14740](https://github.com/sourcegraph/sourcegraph/pull/14740)\n- Search queries with an unbalanced closing paren `)` are now invalid, since this likely indicates an error. Previously, patterns with dangling `)` were valid in some cases. Note that patterns with dangling `)` can still be searched, but should be quoted via `content:\"foo)\"`. [#15042](https://github.com/sourcegraph/sourcegraph/pull/15042)\n- Extension providers can now return AsyncIterables, enabling dynamic provider results without dependencies. [#15042](https://github.com/sourcegraph/sourcegraph/issues/15061)\n- Deprecated the `\"email.smtp\": { \"disableTLS\" }` site config option, this field has been replaced by `\"email.smtp\": { \"noVerifyTLS\" }`. [#15682](https://github.com/sourcegraph/sourcegraph/pull/15682)", "### Fixed", "- The `file:` added to the search field when navigating to a tree or file view will now behave correctly when the file path contains spaces. [#12296](https://github.com/sourcegraph/sourcegraph/issues/12296)\n- OAuth login now respects site configuration `experimentalFeatures: { \"tls.external\": {...} }` for custom certificates and skipping TLS verify. [#14144](https://github.com/sourcegraph/sourcegraph/issues/14144)\n- If the `HEAD` file in a cloned repo is absent or truncated, background cleanup activities will use a best-effort default to remedy the situation. [#14962](https://github.com/sourcegraph/sourcegraph/pull/14962)\n- Search input will always show suggestions. Previously we only showed suggestions for letters and some special characters. [#14982](https://github.com/sourcegraph/sourcegraph/pull/14982)\n- Fixed an issue where `not` keywords were not recognized inside expression groups, and treated incorrectly as patterns. [#15139](https://github.com/sourcegraph/sourcegraph/pull/15139)\n- Fixed an issue where hover pop-ups would not show on the first character of a valid hover range in search queries. [#15410](https://github.com/sourcegraph/sourcegraph/pull/15410)\n- Fixed an issue where submodules configured with a relative URL resulted in non-functional hyperlinks in the file tree UI. [#15286](https://github.com/sourcegraph/sourcegraph/issues/15286)\n- Pushing commits to public GitLab repositories with campaigns now works, since we use the configured token even if the repository is public. [#15536](https://github.com/sourcegraph/sourcegraph/pull/15536)\n- `.kts` is now highlighted properly as Kotlin code, fixed various other issues in Kotlin syntax highlighting.\n- Fixed an issue where the value of `content:` was treated literally when the regular expression toggle is active. [#15639](https://github.com/sourcegraph/sourcegraph/pull/15639)\n- Fixed an issue where non-site admins were prohibited from updating some of their other personal metadata when `auth.enableUsernameChanges` was `false`. [#15663](https://github.com/sourcegraph/sourcegraph/issues/15663)\n- Fixed the `url` fields of repositories and trees in GraphQL returning URLs that were not %-encoded (e.g. when the repository name contained spaces). [#15667](https://github.com/sourcegraph/sourcegraph/issues/15667)\n- Fixed \"Find references\" showing errors in the references panel in place of the syntax-highlighted code for repositories with spaces in their name. [#15618](https://github.com/sourcegraph/sourcegraph/issues/15618)\n- Fixed an issue where specifying the `repohasfile` filter did not return results as expected unless `repo` was specified. [#15894](https://github.com/sourcegraph/sourcegraph/pull/15894)\n- Fixed an issue causing user input in the search query field to be erased in some cases. [#15921](https://github.com/sourcegraph/sourcegraph/issues/15921).", "### Removed", "-", "## 3.21.2", ":warning: WARNING :warning: For users of single-image Sourcegraph instance, please delete the secret key file `/var/lib/sourcegraph/token` inside the container before attempting to upgrade to 3.21.x.", "### Fixed", "- Fix externalURLs alert logic [#14980](https://github.com/sourcegraph/sourcegraph/pull/14980)", "## 3.21.1", ":warning: WARNING :warning: For users of single-image Sourcegraph instance, please delete the secret key file `/var/lib/sourcegraph/token` inside the container before attempting to upgrade to 3.21.x.", "### Fixed", "- Fix alerting for native integration condition [#14775](https://github.com/sourcegraph/sourcegraph/pull/14775)\n- Fix query with large repo count hanging [#14944](https://github.com/sourcegraph/sourcegraph/pull/14944)\n- Fix server upgrade where codeintel database does not exist [#14953](https://github.com/sourcegraph/sourcegraph/pull/14953)\n- CVE-2019-18218 in postgres docker image [#14954](https://github.com/sourcegraph/sourcegraph/pull/14954)\n- Fix an issue where .git/HEAD in invalid [#14962](https://github.com/sourcegraph/sourcegraph/pull/14962)\n- Repository syncing will not happen more frequently than the repoListUpdateInterval config value [#14901](https://github.com/sourcegraph/sourcegraph/pull/14901) [#14983](https://github.com/sourcegraph/sourcegraph/pull/14983)", "## 3.21.0", ":warning: WARNING :warning: For users of single-image Sourcegraph instance, please delete the secret key file `/var/lib/sourcegraph/token` inside the container before attempting to upgrade to 3.21.x.", "### Added", "- The new GraphQL API query field `namespaceByName(name: String!)` makes it easier to look up the user or organization with the given name. Previously callers needed to try looking up the user and organization separately.\n- Changesets created by campaigns will now include a link back to the campaign in their body text. [#14033](https://github.com/sourcegraph/sourcegraph/issues/14033)\n- Users can now preview commits that are going to be created in their repositories in the campaign preview UI. [#14181](https://github.com/sourcegraph/sourcegraph/pull/14181)\n- If emails are configured, the user will be sent an email when important account information is changed. This currently encompasses changing/resetting the password, adding/removing emails, and adding/removing access tokens. [#14320](https://github.com/sourcegraph/sourcegraph/pull/14320)\n- A subset of changesets can now be published by setting the `published` flag in campaign specs [to an array](https://docs.sourcegraph.com/@main/campaigns/campaign_spec_yaml_reference#publishing-only-specific-changesets), which allows only specific changesets within a campaign to be published based on the repository name. [#13476](https://github.com/sourcegraph/sourcegraph/pull/13476)\n- Homepage panels are now enabled by default. [#14287](https://github.com/sourcegraph/sourcegraph/issues/14287)\n- The most recent ping data is now available to site admins via the Site-admin > Pings page. [#13956](https://github.com/sourcegraph/sourcegraph/issues/13956)\n- Homepage panel engagement metrics will be sent back in pings. [#14589](https://github.com/sourcegraph/sourcegraph/pull/14589)\n- Homepage now has a footer with links to different extensibility features. [#14638](https://github.com/sourcegraph/sourcegraph/issues/14638)\n- Added an onboarding tour of Sourcegraph for new users. It can be enabled in user settings with `experimentalFeatures.showOnboardingTour` [#14636](https://github.com/sourcegraph/sourcegraph/pull/14636)\n- Added an onboarding tour of Sourcegraph for new users. [#14636](https://github.com/sourcegraph/sourcegraph/pull/14636)\n- Repository GraphQL queries now support an `after` parameter that permits cursor-based pagination. [#13715](https://github.com/sourcegraph/sourcegraph/issues/13715)\n- Searches in the Recent Searches panel and other places are now syntax highlighted. [#14443](https://github.com/sourcegraph/sourcegraph/issues/14443)", "### Changed", "- Interactive search mode is now disabled by default because the new plain text search input is smarter. To reenable it, add `{ \"experimentalFeatures\": { \"splitSearchModes\": true } }` in user settings.\n- The extension registry has been redesigned to make it easier to find non-default Sourcegraph extensions.\n- Tokens and similar sensitive information included in the userinfo portion of remote repository URLs will no longer be visible on the Mirroring settings page. [#14153](https://github.com/sourcegraph/sourcegraph/pull/14153)\n- The sign in and sign up forms have been redesigned with better input validation.\n- Kubernetes admins mounting [configuration files](https://docs.sourcegraph.com/admin/config/advanced_config_file#kubernetes-configmap) are encouraged to change how the ConfigMap is mounted. See the new documentation. Previously our documentation suggested using subPath. However, this lead to Kubernetes not automatically updating the files on configuration change. [#14297](https://github.com/sourcegraph/sourcegraph/pull/14297)\n- The precise code intel bundle manager will now expire any converted LSIF data that is older than `PRECISE_CODE_INTEL_MAX_DATA_AGE` (30 days by default) that is also not visible from the tip of the default branch.\n- `SRC_LOG_LEVEL=warn` is now the default in Docker Compose and Kubernetes deployments, reducing the amount of uninformative log spam. [#14458](https://github.com/sourcegraph/sourcegraph/pull/14458)\n- Permissions data that were stored in deprecated binary format are abandoned. Downgrade from 3.21 to 3.20 is OK, but to 3.19 or prior versions might experience missing/incomplete state of permissions for a short period of time. [#13740](https://github.com/sourcegraph/sourcegraph/issues/13740)\n- The query builder page is now disabled by default. To reenable it, add `{ \"experimentalFeatures\": { \"showQueryBuilder\": true } }` in user settings.\n- The GraphQL `updateUser` mutation now returns the updated user (instead of an empty response).", "### Fixed", "- Git clone URLs now validate their format correctly. [#14313](https://github.com/sourcegraph/sourcegraph/pull/14313)\n- Usernames set in Slack `observability.alerts` now apply correctly. [#14079](https://github.com/sourcegraph/sourcegraph/pull/14079)\n- Path segments in breadcrumbs get truncated correctly again on small screen sizes instead of inflating the header bar. [#14097](https://github.com/sourcegraph/sourcegraph/pull/14097)\n- GitLab pipelines are now parsed correctly and show their current status in campaign changesets. [#14129](https://github.com/sourcegraph/sourcegraph/pull/14129)\n- Fixed an issue where specifying any repogroups would effectively search all repositories for all repogroups. [#14190](https://github.com/sourcegraph/sourcegraph/pull/14190)\n- Changesets that were previously closed after being detached from a campaign are now reopened when being reattached. [#14099](https://github.com/sourcegraph/sourcegraph/pull/14099)\n- Previously large files that match the site configuration [search.largeFiles](https://docs.sourcegraph.com/admin/config/site_config#search-largeFiles) would not be indexed if they contained a large number of unique trigrams. We now index those files as well. Note: files matching the glob still need to be valid utf-8. [#12443](https://github.com/sourcegraph/sourcegraph/issues/12443)\n- Git tags without a `creatordate` value will no longer break tag search within a repository. [#5453](https://github.com/sourcegraph/sourcegraph/issues/5453)\n- Campaigns pages now work properly on small viewports. [#14292](https://github.com/sourcegraph/sourcegraph/pull/14292)\n- Fix an issue with viewing repositories that have spaces in the repository name [#2867](https://github.com/sourcegraph/sourcegraph/issues/2867)", "### Removed", "- Syntax highlighting for GraphQL, INI, TOML, and Perforce files has been removed [due to incompatible/absent licenses](https://github.com/sourcegraph/sourcegraph/issues/13933). We plan to [add it back in the future](https://github.com/sourcegraph/sourcegraph/issues?q=is%3Aissue+is%3Aopen+add+syntax+highlighting+for+develop+a+).\n- Search scope pages (`/search/scope/:id`) were removed.\n- User-defined search scopes are no longer shown below the search bar on the homepage. Use the [`quicklinks`](https://docs.sourcegraph.com/user/personalization/quick_links) setting instead to display links there.\n- The explore page (`/explore`) was removed.\n- The sign out page was removed.\n- The unused GraphQL types `DiffSearchResult` and `DeploymentConfiguration` were removed.\n- The deprecated GraphQL mutation `updateAllMirrorRepositories`.\n- The deprecated GraphQL field `Site.noRepositoriesEnabled`.\n- Total counts of users by product area have been removed from pings.\n- Aggregate daily, weekly, and monthly latencies (in ms) of code intelligence events (e.g., hover tooltips) have been removed from pings.", "## 3.20.1", "### Fixed", "- gomod: rollback go-diff to v0.5.3 (v0.6.0 causes panic in certain cases) [#13973](https://github.com/sourcegraph/sourcegraph/pull/13973).\n- Fixed an issue causing the scoped query in the search field to be erased when viewing files. [#13954](https://github.com/sourcegraph/sourcegraph/pull/13954).", "## 3.20.0", "### Added", "- Site admins can now force a specific user to re-authenticate on their next request or visit. [#13647](https://github.com/sourcegraph/sourcegraph/pull/13647)\n- Sourcegraph now watches its [configuration files](https://docs.sourcegraph.com/admin/config/advanced_config_file) (when using external files) and automatically applies the changes to Sourcegraph's configuration when they change. For example, this allows Sourcegraph to detect when a Kubernetes ConfigMap changes. [#13646](https://github.com/sourcegraph/sourcegraph/pull/13646)\n- To define repository groups (`search.repositoryGroups` in global, org, or user settings), you can now specify regular expressions in addition to single repository names. [#13730](https://github.com/sourcegraph/sourcegraph/pull/13730)\n- The new site configuration property `search.limits` configures the maximum search timeout and the maximum number of repositories to search for various types of searches. [#13448](https://github.com/sourcegraph/sourcegraph/pull/13448)\n- Files and directories can now be excluded from search by adding the file `.sourcegraph/ignore` to the root directory of a repository. Each line in the _ignore_ file is interpreted as a globbing pattern. [#13690](https://github.com/sourcegraph/sourcegraph/pull/13690)\n- Structural search syntax now allows regular expressions in patterns. Also, `...` can now be used in place of `:[_]`. See the [documentation](https://docs.sourcegraph.com/@main/code_search/reference/structural) for example syntax. [#13809](https://github.com/sourcegraph/sourcegraph/pull/13809)\n- The total size of all Git repositories and the lines of code for indexed branches will be sent back in pings. [#13764](https://github.com/sourcegraph/sourcegraph/pull/13764)\n- Experimental: A new homepage UI for Sourcegraph Server shows the user their recent searches, repositories, files, and saved searches. It can be enabled with `experimentalFeatures.showEnterpriseHomePanels`. [#13407](https://github.com/sourcegraph/sourcegraph/issues/13407)", "### Changed", "- Campaigns are enabled by default for all users. Site admins may view and create campaigns; everyone else may only view campaigns. The new site configuration property `campaigns.enabled` can be used to disable campaigns for all users. The properties `campaigns.readAccess`, `automation.readAccess.enabled`, and `\"experimentalFeatures\": { \"automation\": \"enabled\" }}` are deprecated and no longer have any effect.\n- Diff and commit searches are limited to 10,000 repositories (if `before:` or `after:` filters are used), or 50 repositories (if no time filters are used). You can configure this limit in the site configuration property `search.limits`. [#13386](https://github.com/sourcegraph/sourcegraph/pull/13386)\n- The site configuration `maxReposToSearch` has been deprecated in favor of the property `maxRepos` on `search.limits`. [#13439](https://github.com/sourcegraph/sourcegraph/pull/13439)\n- Search queries are now processed by a new parser that will always be enabled going forward. There should be no material difference in behavior. In case of adverse effects, the previous parser can be reenabled by setting `\"search.migrateParser\": false` in settings. [#13435](https://github.com/sourcegraph/sourcegraph/pull/13435)\n- It is now possible to search for file content that excludes a term using the `NOT` operator. [#12412](https://github.com/sourcegraph/sourcegraph/pull/12412)\n- `NOT` is available as an alternative syntax of `-` on supported keywords `repo`, `file`, `content`, `lang`, and `repohasfile`. [#12412](https://github.com/sourcegraph/sourcegraph/pull/12412)\n- Negated content search is now also supported for unindexed repositories. Previously it was only supported for indexed repositories [#13359](https://github.com/sourcegraph/sourcegraph/pull/13359).\n- The experimental feature flag `andOrQuery` is deprecated. [#13435](https://github.com/sourcegraph/sourcegraph/pull/13435)\n- After a user's password changes, they will be signed out on all devices and must sign in again. [#13647](https://github.com/sourcegraph/sourcegraph/pull/13647)\n- `rev:` is available as alternative syntax of `@` for searching revisions instead of the default branch [#13133](https://github.com/sourcegraph/sourcegraph/pull/13133)\n- Campaign URLs have changed to use the campaign name instead of an opaque ID. The old URLs no longer work. [#13368](https://github.com/sourcegraph/sourcegraph/pull/13368)\n- A new `external_service_repos` join table was added. The migration required to make this change may take a few minutes.", "### Fixed", "- User satisfaction/NPS surveys will now correctly provide a range from 0–10, rather than 0–9. [#13163](https://github.com/sourcegraph/sourcegraph/pull/13163)\n- Fixed a bug where we returned repositories with invalid revisions in the search results. Now, if a user specifies an invalid revision, we show an alert. [#13271](https://github.com/sourcegraph/sourcegraph/pull/13271)\n- Previously it wasn't possible to search for certain patterns containing `:` because they would not be considered valid filters. We made these checks less strict. [#10920](https://github.com/sourcegraph/sourcegraph/pull/10920)\n- When a user signs out of their account, all of their sessions will be invalidated, not just the session where they signed out. [#13647](https://github.com/sourcegraph/sourcegraph/pull/13647)\n- URL information will no longer be leaked by the HTTP referer header. This prevents the user's password reset code from being leaked. [#13804](https://github.com/sourcegraph/sourcegraph/pull/13804)\n- GitLab OAuth2 user authentication now respects `tls.external` site setting. [#13814](https://github.com/sourcegraph/sourcegraph/pull/13814)", "### Removed", "- The smartSearchField feature is now always enabled. The `experimentalFeatures.smartSearchField` settings option has been removed.", "## 3.19.2", "### Fixed", "- search: always limit commit and diff to less than 10,000 repos [a97f81b0f7](https://github.com/sourcegraph/sourcegraph/commit/a97f81b0f79535253bd7eae6c30d5c91d48da5ca)\n- search: configurable limits on commit/diff search [1c22d8ce1](https://github.com/sourcegraph/sourcegraph/commit/1c22d8ce13c149b3fa3a7a26f8cb96adc89fc556)\n- search: add site configuration for maxTimeout [d8d61b43c0f](https://github.com/sourcegraph/sourcegraph/commit/d8d61b43c0f0d229d46236f2f128ca0f93455172)", "## 3.19.1", "### Fixed", "- migrations: revert migration causing deadlocks in some deployments [#13194](https://github.com/sourcegraph/sourcegraph/pull/13194)", "## 3.19.0", "### Added", "- Emails can be now be sent to SMTP servers with self-signed certificates, using `email.smtp.disableTLS`. [#12243](https://github.com/sourcegraph/sourcegraph/pull/12243)\n- Saved search emails now include a link to the user's saved searches page. [#11651](https://github.com/sourcegraph/sourcegraph/pull/11651)\n- Campaigns can now be synced using GitLab webhooks. [#12139](https://github.com/sourcegraph/sourcegraph/pull/12139)\n- Configured `observability.alerts` can now be tested using a GraphQL endpoint, `triggerObservabilityTestAlert`. [#12532](https://github.com/sourcegraph/sourcegraph/pull/12532)\n- The Sourcegraph CLI can now serve local repositories for Sourcegraph to clone. This was previously in a command called `src-expose`. See [serving local repositories](https://docs.sourcegraph.com/admin/external_service/src_serve_git) in our documentation to find out more. [#12363](https://github.com/sourcegraph/sourcegraph/issues/12363)\n- The count of retained, churned, resurrected, new and deleted users will be sent back in pings. [#12136](https://github.com/sourcegraph/sourcegraph/pull/12136)\n- Saved search usage will be sent back in pings. [#12956](https://github.com/sourcegraph/sourcegraph/pull/12956)\n- Any request with `?trace=1` as a URL query parameter will enable Jaeger tracing (if Jaeger is enabled). [#12291](https://github.com/sourcegraph/sourcegraph/pull/12291)\n- Password reset emails will now be automatically sent to users created by a site admin if email sending is configured and password reset is enabled. Previously, site admins needed to manually send the user this password reset link. [#12803](https://github.com/sourcegraph/sourcegraph/pull/12803)\n- Syntax highlighting for `and` and `or` search operators. [#12694](https://github.com/sourcegraph/sourcegraph/pull/12694)\n- It is now possible to search for file content that excludes a term using the `NOT` operator. Negating pattern syntax requires setting `\"search.migrateParser\": true` in settings and is currently only supported for literal and regexp queries on indexed repositories. [#12412](https://github.com/sourcegraph/sourcegraph/pull/12412)\n- `NOT` is available as an alternative syntax of `-` on supported keywords `repo`, `file`, `content`, `lang`, and `repohasfile`. `NOT` requires setting `\"search.migrateParser\": true` option in settings. [#12520](https://github.com/sourcegraph/sourcegraph/pull/12520)", "### Changed", "- Repository permissions are now always checked and updated asynchronously ([background permissions syncing](https://docs.sourcegraph.com/admin/repo/permissions#background-permissions-syncing)) instead of blocking each operation. The site config option `permissions.backgroundSync` (which enabled this behavior in previous versions) is now a no-op and is deprecated.\n- [Background permissions syncing](https://docs.sourcegraph.com/admin/repo/permissions#background-permissions-syncing) (`permissions.backgroundSync`) has become the only option for mirroring repository permissions from code hosts. All relevant site configurations are deprecated.", "### Fixed", "- Fixed site admins are getting errors when visiting user settings page in OSS version. [#12313](https://github.com/sourcegraph/sourcegraph/pull/12313)\n- `github-proxy` now respects the environment variables `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` (or the lowercase versions thereof). Other services already respect these variables, but this was missed. If you need a proxy to access github.com set the environment variable for the github-proxy container. [#12377](https://github.com/sourcegraph/sourcegraph/issues/12377)\n- `sourcegraph-frontend` now respects the `tls.external` experimental setting as well as the proxy environment variables. In proxy environments this allows Sourcegraph to fetch extensions. [#12633](https://github.com/sourcegraph/sourcegraph/issues/12633)\n- Fixed a bug that would sometimes cause trailing parentheses to be removed from search queries upon page load. [#12960](https://github.com/sourcegraph/sourcegraph/issues/12690)\n- Indexed search will no longer stall if a specific index job stalls. Additionally at scale many corner cases causing indexing to stall have been fixed. [#12502](https://github.com/sourcegraph/sourcegraph/pull/12502)\n- Indexed search will quickly recover from rebalancing / roll outs. When a indexed search shard goes down, its repositories are re-indexed by other shards. This takes a while and during a rollout leads to effectively re-indexing all repositories. We now avoid indexing the redistributed repositories once a shard comes back online. [#12474](https://github.com/sourcegraph/sourcegraph/pull/12474)\n- Indexed search has many improvements to observability. More detailed Jaeger traces, detailed logging during startup and more prometheus metrics.\n- The site admin repository needs-index page is significantly faster. Previously on large instances it would usually timeout. Now it should load within a second. [#12513](https://github.com/sourcegraph/sourcegraph/pull/12513)\n- User password reset page now respects the value of site config `auth.minPasswordLength`. [#12971](https://github.com/sourcegraph/sourcegraph/pull/12971)\n- Fixed an issue where duplicate search results would show for queries with `or`-expressions. [#12531](https://github.com/sourcegraph/sourcegraph/pull/12531)\n- Faster indexed search queries over a large number of repositories. Searching 100k+ repositories is now ~400ms faster and uses much less memory. [#12546](https://github.com/sourcegraph/sourcegraph/pull/12546)", "### Removed", "- Deprecated site settings `lightstepAccessToken` and `lightstepProject` have been removed. We now only support sending traces to Jaeger. Configure Jaeger with `observability.tracing` site setting.\n- Removed `CloneInProgress` option from GraphQL Repositories API. [#12560](https://github.com/sourcegraph/sourcegraph/pull/12560)", "## 3.18.0", "### Added", "- To search across multiple revisions of the same repository, list multiple branch names (or other revspecs) separated by `:` in your query, as in `repo:myrepo@branch1:branch2:branch2`. To search all branches, use `repo:myrepo@*refs/heads/`. Previously this was only supported for diff and commit searches and only available via the experimental site setting `searchMultipleRevisionsPerRepository`.\n- The \"Add repositories\" page (/site-admin/external-services/new) now displays a dismissable notification explaining how and why we access code host data. [#11789](https://github.com/sourcegraph/sourcegraph/pull/11789).\n- New `observability.alerts` features:\n - Notifications now provide more details about relevant alerts.\n - Support for email and OpsGenie notifications has been added. Note that to receive email alerts, `email.address` and `email.smtp` must be configured.\n - Some notifiers now have new options:\n - PagerDuty notifiers: `severity` and `apiUrl`\n - Webhook notifiers: `bearerToken`\n - A new `disableSendResolved` option disables notifications for when alerts resolve themselves.\n- Recently firing critical alerts can now be displayed to admins via site alerts, use the flag `{ \"alerts.hideObservabilitySiteAlerts\": false }` to enable these alerts in user configuration.\n- Specific alerts can now be silenced using `observability.silenceAlerts`. [#12087](https://github.com/sourcegraph/sourcegraph/pull/12087)\n- Revisions listed in `experimentalFeatures.versionContext` will be indexed for faster searching. This is the first support towards indexing non-default branches. [#6728](https://github.com/sourcegraph/sourcegraph/issues/6728)\n- Revisions listed in `experimentalFeatures.versionContext` or `experimentalFeatures.search.index.branches` will be indexed for faster searching. This is the first support towards indexing non-default branches. [#6728](https://github.com/sourcegraph/sourcegraph/issues/6728)\n- Campaigns are now supported on GitLab.\n- Campaigns now support GitLab and allow users to create, update and track merge requests on GitLab instances.\n- Added a new section on the search homepage on Sourcegraph.com. It is currently feature flagged behind `experimentalFeatures.showRepogroupHomepage` in settings.\n- Added new repository group pages.", "### Changed", "- Some monitoring alerts now have more useful descriptions. [#11542](https://github.com/sourcegraph/sourcegraph/pull/11542)\n- Searching `fork:true` or `archived:true` has the same behaviour as searching `fork:yes` or `archived:yes` respectively. Previously it incorrectly had the same behaviour as `fork:only` and `archived:only` respectively. [#11740](https://github.com/sourcegraph/sourcegraph/pull/11740)\n- Configuration for `observability.alerts` has changed and notifications are now provided by Prometheus Alertmanager. [#11832](https://github.com/sourcegraph/sourcegraph/pull/11832)\n - Removed: `observability.alerts.id`.\n - Removed: Slack notifiers no longer accept `mentionUsers`, `mentionGroups`, `mentionChannel`, and `token` options.", "### Fixed", "- The single-container `sourcegraph/server` image now correctly reports its version.\n- An issue where repositories would not clone and index in some edge cases where the clones were deleted or not successful on gitserver. [#11602](https://github.com/sourcegraph/sourcegraph/pull/11602)\n- An issue where repositories previously deleted on gitserver would not immediately reclone on system startup. [#11684](https://github.com/sourcegraph/sourcegraph/issues/11684)\n- An issue where the sourcegraph/server Jaeger config was invalid. [#11661](https://github.com/sourcegraph/sourcegraph/pull/11661)\n- An issue where valid search queries were improperly hinted as being invalid in the search field. [#11688](https://github.com/sourcegraph/sourcegraph/pull/11688)\n- Reduce frontend memory spikes by limiting the number of goroutines launched by our GraphQL resolvers. [#11736](https://github.com/sourcegraph/sourcegraph/pull/11736)\n- Fixed a bug affecting Sourcegraph icon display in our Phabricator native integration [#11825](https://github.com/sourcegraph/sourcegraph/pull/11825).\n- Improve performance of site-admin repositories status page. [#11932](https://github.com/sourcegraph/sourcegraph/pull/11932)\n- An issue where search autocomplete for files didn't add the right path. [#12241](https://github.com/sourcegraph/sourcegraph/pull/12241)", "### Removed", "- Backwards compatibility for \"critical configuration\" (a type of configuration that was deprecated in December 2019) was removed. All critical configuration now belongs in site configuration.\n- Experimental feature setting `{ \"experimentalFeatures\": { \"searchMultipleRevisionsPerRepository\": true } }` will be removed in 3.19. It is now always on. Please remove references to it.\n- Removed \"Cloning\" tab in site-admin Repository Status page. [#12043](https://github.com/sourcegraph/sourcegraph/pull/12043)\n- The `blacklist` configuration option for Gitolite that was deprecated in 3.17 has been removed in 3.19. Use `exclude.pattern` instead. [#12345](https://github.com/sourcegraph/sourcegraph/pull/12345)", "## 3.17.3", "### Fixed", "- git: Command retrying made a copy that was never used [#11807](https://github.com/sourcegraph/sourcegraph/pull/11807)\n- frontend: Allow opt out of EnsureRevision when making a comparison query [#11811](https://github.com/sourcegraph/sourcegraph/pull/11811)\n- Fix Phabricator icon class [#11825](https://github.com/sourcegraph/sourcegraph/pull/11825)", "## 3.17.2", "### Fixed", "- An issue where repositories previously deleted on gitserver would not immediately reclone on system startup. [#11684](https://github.com/sourcegraph/sourcegraph/issues/11684)", "## 3.17.1", "### Added", "- Improved search indexing metrics", "### Changed", "- Some monitoring alerts now have more useful descriptions. [#11542](https://github.com/sourcegraph/sourcegraph/pull/11542)", "### Fixed", "- The single-container `sourcegraph/server` image now correctly reports its version.\n- An issue where repositories would not clone and index in some edge cases where the clones were deleted or not successful on gitserver. [#11602](https://github.com/sourcegraph/sourcegraph/pull/11602)\n- An issue where the sourcegraph/server Jaeger config was invalid. [#11661](https://github.com/sourcegraph/sourcegraph/pull/11661)", "## 3.17.0", "### Added", "- The search results page now shows a small UI notification if either repository forks or archives are excluded, when `fork` or `archived` options are not explicitly set. [#10624](https://github.com/sourcegraph/sourcegraph/pull/10624)\n- Prometheus metric `src_gitserver_repos_removed_disk_pressure` which is incremented everytime we remove a repository due to disk pressure. [#10900](https://github.com/sourcegraph/sourcegraph/pull/10900)\n- `gitolite.exclude` setting in [Gitolite external service config](https://docs.sourcegraph.com/admin/external_service/gitolite#configuration) now supports a regular expression via the `pattern` field. This is consistent with how we exclude in other external services. Additionally this is a replacement for the deprecated `blacklist` configuration. [#11403](https://github.com/sourcegraph/sourcegraph/pull/11403)\n- Notifications about Sourcegraph being out of date will now be shown to site admins and users (depending on how out-of-date it is).\n- Alerts are now configured using `observability.alerts` in the site configuration, instead of via the Grafana web UI. This does not yet support all Grafana notification channel types, and is not yet supported on `sourcegraph/server` ([#11473](https://github.com/sourcegraph/sourcegraph/issues/11473)). For more details, please refer to the [Sourcegraph alerting guide](https://docs.sourcegraph.com/admin/observability/alerting).\n- Experimental basic support for detecting if your Sourcegraph instance is over or under-provisioned has been added through a set of dashboards and warning-level alerts based on container utilization.\n- Query [operators](https://docs.sourcegraph.com/code_search/reference/queries#boolean-operators) `and` and `or` are now enabled by default in all search modes for searching file content. [#11521](https://github.com/sourcegraph/sourcegraph/pull/11521)", "### Changed", "- Repository search within a version context will link to the revision in the version context. [#10860](https://github.com/sourcegraph/sourcegraph/pull/10860)\n- Background permissions syncing becomes the default method to sync permissions from code hosts. Please [read our documentation for things to keep in mind before upgrading](https://docs.sourcegraph.com/admin/repo/permissions#background-permissions-syncing). [#10972](https://github.com/sourcegraph/sourcegraph/pull/10972)\n- The styling of the hover overlay was overhauled to never have badges or the close button overlap content while also always indicating whether the overlay is currently pinned. The styling on code hosts was also improved. [#10956](https://github.com/sourcegraph/sourcegraph/pull/10956)\n- Previously, it was required to quote most patterns in structural search. This is no longer a restriction and single and double quotes in structural search patterns are interpreted literally. Note: you may still use `content:\"structural-pattern\"` if the pattern without quotes conflicts with other syntax. [#11481](https://github.com/sourcegraph/sourcegraph/pull/11481)", "### Fixed", "- Dynamic repo search filters on branches which contain special characters are correctly escaped now. [#10810](https://github.com/sourcegraph/sourcegraph/pull/10810)\n- Forks and archived repositories at a specific commit are searched without the need to specify \"fork:yes\" or \"archived:yes\" in the query. [#10864](https://github.com/sourcegraph/sourcegraph/pull/10864)\n- The git history for binary files is now correctly shown. [#11034](https://github.com/sourcegraph/sourcegraph/pull/11034)\n- Links to AWS Code Commit repositories have been fixed after the URL schema has been changed. [#11019](https://github.com/sourcegraph/sourcegraph/pull/11019)\n- A link to view all repositories will now always appear on the Explore page. [#11113](https://github.com/sourcegraph/sourcegraph/pull/11113)\n- The Site-admin > Pings page no longer incorrectly indicates that pings are disabled when they aren't. [#11229](https://github.com/sourcegraph/sourcegraph/pull/11229)\n- Match counts are now accurately reported for indexed search. [#11242](https://github.com/sourcegraph/sourcegraph/pull/11242)\n- When background permissions syncing is enabled, it is now possible to only enforce permissions for repositories from selected code hosts (instead of enforcing permissions for repositories from all code hosts). [#11336](https://github.com/sourcegraph/sourcegraph/pull/11336)\n- When more than 200+ repository revisions in a search are unindexed (very rare), the remaining repositories are reported as missing instead of Sourcegraph issuing e.g. several thousand unindexed search requests which causes system slowness and ultimately times out - ensuring searches are still fast even if there are indexing issues on a deployment of Sourcegraph. This does not apply if `index:no` is present in the query.", "### Removed", "- Automatic syncing of Campaign webhooks for Bitbucket Server. [#10962](https://github.com/sourcegraph/sourcegraph/pull/10962)\n- The `blacklist` configuration option for Gitolite is DEPRECATED and will be removed in 3.19. Use `exclude.pattern` instead.", "## 3.16.2", "### Fixed", "- Search: fix indexed search match count [#7fc96](https://github.com/sourcegraph/sourcegraph/commit/7fc96d319f49f55da46a7649ccf261aa7e8327c3)\n- Sort detected languages properly [#e7750](https://github.com/sourcegraph/sourcegraph/commit/e77507d060a40355e7b86fb093d21a7149ea03ac)", "## 3.16.1", "### Fixed", "- Fix repo not found error for patches [#11021](https://github.com/sourcegraph/sourcegraph/pull/11021).\n- Show expired license screen [#10951](https://github.com/sourcegraph/sourcegraph/pull/10951).\n- Sourcegraph is now built with Go 1.14.3, fixing issues running Sourcegraph onUbuntu 19 and 20. [#10447](https://github.com/sourcegraph/sourcegraph/issues/10447)", "## 3.16.0", "### Added", "- Autocompletion for `repogroup` filters in search queries. [#10141](https://github.com/sourcegraph/sourcegraph/pull/10286)\n- If the experimental feature flag `codeInsights` is enabled, extensions can contribute content to directory pages through the experimental `ViewProvider` API. [#10236](https://github.com/sourcegraph/sourcegraph/pull/10236)\n - Directory pages are then represented as an experimental `DirectoryViewer` in the `visibleViewComponents` of the extension API. **Note: This may break extensions that were assuming `visibleViewComponents` were always `CodeEditor`s and did not check the `type` property.** Extensions checking the `type` property will continue to work. [#10236](https://github.com/sourcegraph/sourcegraph/pull/10236)\n- [Major syntax highlighting improvements](https://github.com/sourcegraph/syntect_server/pull/29), including:\n - 228 commits / 1 year of improvements to the syntax highlighter library Sourcegraph uses ([syntect](https://github.com/trishume/syntect)).\n - 432 commits / 1 year of improvements to the base syntax definitions for ~36 languages Sourcegraph uses ([sublimehq/Packages](https://github.com/sublimehq/Packages)).\n - 30 new file extensions/names now detected.\n - Likely fixes other major instability and language support issues. #9557\n - Added [Smarty](#2885), [Ethereum / Solidity / Vyper)](#2440), [Cuda](#5907), [COBOL](#10154), [vb.NET](#4901), and [ASP.NET](#4262) syntax highlighting.\n - Fixed OCaml syntax highlighting #3545\n - Bazel/Starlark support improved (.star, BUILD, and many more extensions now properly highlighted). #8123\n- New permissions page in both user and repository settings when background permissions syncing is enabled (`\"permissions.backgroundSync\": {\"enabled\": true}`). [#10473](https://github.com/sourcegraph/sourcegraph/pull/10473) [#10655](https://github.com/sourcegraph/sourcegraph/pull/10655)\n- A new dropdown for choosing version contexts appears on the left of the query input when version contexts are specified in `experimentalFeatures.versionContext` in site configuration. Version contexts allow you to scope your search to specific sets of repos at revisions.\n- Campaign changeset usage counts including changesets created, added and merged will be sent back in pings. [#10591](https://github.com/sourcegraph/sourcegraph/pull/10591)\n- Diff views now feature syntax highlighting and can be properly copy-pasted. [#10437](https://github.com/sourcegraph/sourcegraph/pull/10437)\n- Admins can now download an anonymized usage statistics ZIP archive in the **Site admin > Usage stats**. Opting to share this archive with the Sourcegraph team helps us make the product even better. [#10475](https://github.com/sourcegraph/sourcegraph/pull/10475)\n- Extension API: There is now a field `versionContext` and subscribable `versionContextChanges` in `Workspace` to allow extensions to respect the instance's version context.\n- The smart search field, providing syntax highlighting, hover tooltips, and validation on filters in search queries, is now activated by default. It can be disabled by setting `{ \"experimentalFeatures\": { \"smartSearchField\": false } }` in global settings.", "### Changed", "- The `userID` and `orgID` fields in the SavedSearch type in the GraphQL API have been replaced with a `namespace` field. To get the ID of the user or org that owns the saved search, use `namespace.id`. [#5327](https://github.com/sourcegraph/sourcegraph/pull/5327)\n- Tree pages now redirect to blob pages if the path is not a tree and vice versa. [#10193](https://github.com/sourcegraph/sourcegraph/pull/10193)\n- Files and directories that are not found now return a 404 status code. [#10193](https://github.com/sourcegraph/sourcegraph/pull/10193)\n- The site admin flag `disableNonCriticalTelemetry` now allows Sourcegraph admins to disable most anonymous telemetry. Visit https://docs.sourcegraph.com/admin/pings to learn more. [#10402](https://github.com/sourcegraph/sourcegraph/pull/10402)", "### Fixed", "- In the OSS version of Sourcegraph, authorization providers are properly initialized and GraphQL APIs are no longer blocked. [#3487](https://github.com/sourcegraph/sourcegraph/issues/3487)\n- Previously, GitLab repository paths containing certain characters could not be excluded (slashes and periods in parts of the paths). These characters are now allowed, so the repository paths can be excluded. [#10096](https://github.com/sourcegraph/sourcegraph/issues/10096)\n- Symbols for indexed commits in languages Haskell, JSONNet, Kotlin, Scala, Swift, Thrift, and TypeScript will show up again. Previously our symbol indexer would not know how to extract symbols for those languages even though our unindexed symbol service did. [#10357](https://github.com/sourcegraph/sourcegraph/issues/10357)\n- When periodically re-cloning a repository it will still be available. [#10663](https://github.com/sourcegraph/sourcegraph/pull/10663)", "### Removed", "- The deprecated feature discussions has been removed. [#9649](https://github.com/sourcegraph/sourcegraph/issues/9649)", "## 3.15.2", "### Fixed", "- Fix repo not found error for patches [#11021](https://github.com/sourcegraph/sourcegraph/pull/11021).\n- Show expired license screen [#10951](https://github.com/sourcegraph/sourcegraph/pull/10951).", "## 3.15.1", "### Fixed", "- A potential security vulnerability with in the authentication workflow has been fixed. [#10167](https://github.com/sourcegraph/sourcegraph/pull/10167)\n- An issue where `sourcegraph/postgres-11.4:3.15.0` was incorrectly an older version of the image incompatible with non-root Kubernetes deployments. `sourcegraph/postgres-11.4:3.15.1` now matches the same image version found in Sourcegraph 3.14.3 (`20-04-07_56b20163`).\n- An issue that caused the search result type tabs to be overlapped in Safari. [#10191](https://github.com/sourcegraph/sourcegraph/pull/10191)", "## 3.15.0", "### Added", "- Users and site administrators can now view a log of their actions/events in the user settings. [#9141](https://github.com/sourcegraph/sourcegraph/pull/9141)\n- With the new `visibility:` filter search results can now be filtered based on a repository's visibility (possible filter values: `any`, `public` or `private`). [#8344](https://github.com/sourcegraph/sourcegraph/issues/8344)\n- [`sourcegraph/git-extras`](https://sourcegraph.com/extensions/sourcegraph/git-extras) is now enabled by default on new instances [#3501](https://github.com/sourcegraph/sourcegraph/issues/3501)\n- The Sourcegraph Docker image will now copy `/etc/sourcegraph/gitconfig` to `$HOME/.gitconfig`. This is a convenience similiar to what we provide for [repositories that need HTTP(S) or SSH authentication](https://docs.sourcegraph.com/admin/repo/auth). [#658](https://github.com/sourcegraph/sourcegraph/issues/658)\n- Permissions background syncing is now supported for GitHub via site configuration `\"permissions.backgroundSync\": {\"enabled\": true}`. [#8890](https://github.com/sourcegraph/sourcegraph/issues/8890)\n- Search: Adding `stable:true` to a query ensures a deterministic search result order. This is an experimental parameter. It applies only to file contents, and is limited to at max 5,000 results (consider using [the paginated search API](https://docs.sourcegraph.com/api/graphql/search#sourcegraph-3-9-experimental-paginated-search) if you need more than that.). [#9681](https://github.com/sourcegraph/sourcegraph/pull/9681).\n- After completing the Sourcegraph user feedback survey, a button may appear for tweeting this feedback at [@sourcegraph](https://twitter.com/sourcegraph). [#9728](https://github.com/sourcegraph/sourcegraph/pull/9728)\n- `git fetch` and `git clone` now inherit the parent process environment variables. This allows site admins to set `HTTPS_PROXY` or [git http configurations](https://git-scm.com/docs/git-config/2.26.0#Documentation/git-config.txt-httpproxy) via environment variables. For cluster environments site admins should set this on the gitserver container. [#250](https://github.com/sourcegraph/sourcegraph/issues/250)\n- Experimental: Search for file contents using `and`- and `or`-expressions in queries. Enabled via the global settings value `{\"experimentalFeatures\": {\"andOrQuery\": \"enabled\"}}`. [#8567](https://github.com/sourcegraph/sourcegraph/issues/8567)\n- Always include forks or archived repositories in searches via the global/org/user settings with `\"search.includeForks\": true` or `\"search.includeArchived\": true` respectively. [#9927](https://github.com/sourcegraph/sourcegraph/issues/9927)\n- observability (debugging): It is now possible to log all Search and GraphQL requests slower than N milliseconds, using the new site configuration options `observability.logSlowGraphQLRequests` and `observability.logSlowSearches`.\n- observability (monitoring): **More metrics monitored and alerted on, more legible dashboards**\n - Dashboard panels now show an orange/red background color when the defined warning/critical alert threshold has been met, making it even easier to see on a dashboard what is in a bad state.\n - Symbols: failing `symbols` -> `frontend-internal` requests are now monitored. [#9732](https://github.com/sourcegraph/sourcegraph/issues/9732)\n - Frontend dasbhoard: Search error types are now broken into distinct panels for improved visibility/legibility.\n - **IMPORTANT**: If you have previously configured alerting on any of these panels or on \"hard search errors\", you will need to reconfigure it after upgrading.\n - Frontend dasbhoard: Search error and latency are now broken down by type: Browser requests, search-based code intel requests, and API requests.\n- observability (debugging): **Distributed tracing is a powerful tool for investigating performance issues.** The following changes have been made with the goal of making it easier to use distributed tracing with Sourcegraph:", " - The site configuration field `\"observability.tracing\": { \"sampling\": \"...\" }` allows a site admin to control which requests generate tracing data.\n - `\"all\"` will trace all requests.\n - `\"selective\"` (recommended) will trace all requests initiated from an end-user URL with `?trace=1`. Non-end-user-initiated requests can set a HTTP header `X-Sourcegraph-Should-Trace: true`. This is the recommended setting, as `\"all\"` can generate large amounts of tracing data that may cause network and memory resource contention in the Sourcegraph instance.\n - `\"none\"` (default) turns off tracing.\n - Jaeger is now the officially supported distributed tracer. The following is the recommended site configuration to connect Sourcegraph to a Jaeger agent (which must be deployed on the same host and listening on the default ports):", " ```\n \"observability.tracing\": {\n \"sampling\": \"selective\"\n }\n ```", " - Jaeger is now included in the Sourcegraph deployment configuration by default if you are using Kubernetes, Docker Compose, or the pure Docker cluster deployment model. (It is not yet included in the single Docker container distribution.) It will be included as part of upgrading to 3.15 in these deployment models, unless disabled.\n - The site configuration field, `useJaeger`, is deprecated in favor of `observability.tracing`.\n - Support for configuring Lightstep as a distributed tracer is deprecated and will be removed in a subsequent release. Instances that use Lightstep with Sourcegraph are encouraged to migrate to Jaeger (directions for running Jaeger alongside Sourcegraph are included in the installation instructions).", "### Changed", "- Multiple backwards-incompatible changes in the parts of the GraphQL API related to Campaigns [#9106](https://github.com/sourcegraph/sourcegraph/issues/9106):\n - `CampaignPlan.status` has been removed, since we don't need it anymore after moving execution of campaigns to src CLI in [#8008](https://github.com/sourcegraph/sourcegraph/pull/8008).\n - `CampaignPlan` has been renamed to `PatchSet`.\n - `ChangesetPlan`/`ChangesetPlanConnection` has been renamed to `Patch`/`PatchConnection`.\n - `CampaignPlanPatch` has been renamed to `PatchInput`.\n - `Campaign.plan` has been renamed to `Campaign.patchSet`.\n - `Campaign.changesetPlans` has been renamed to `campaign.changesetPlan`.\n - `createCampaignPlanFromPatches` mutation has been renamed to `createPatchSetFromPatches`.\n- Removed the scoped search field on tree pages. When browsing code, the global search query will now get scoped to the current tree or file. [#9225](https://github.com/sourcegraph/sourcegraph/pull/9225)\n- Instances without a license key that exceed the published user limit will now display a notice to all users.", "### Fixed", "- `.*` in the filter pattern were ignored and led to missing search results. [#9152](https://github.com/sourcegraph/sourcegraph/pull/9152)\n- The Phabricator integration no longer makes duplicate requests to Phabricator's API on diff views. [#8849](https://github.com/sourcegraph/sourcegraph/issues/8849)\n- Changesets on repositories that aren't available on the instance anymore are now hidden instead of failing. [#9656](https://github.com/sourcegraph/sourcegraph/pull/9656)\n- observability (monitoring):\n - **Dashboard and alerting bug fixes**\n - Syntect Server dashboard: \"Worker timeouts\" can no longer appear to go negative. [#9523](https://github.com/sourcegraph/sourcegraph/issues/9523)\n - Symbols dashboard: \"Store fetch queue size\" can no longer appear to go negative. [#9731](https://github.com/sourcegraph/sourcegraph/issues/9731)\n - Syntect Server dashboard: \"Worker timeouts\" no longer incorrectly shows multiple values. [#9524](https://github.com/sourcegraph/sourcegraph/issues/9524)\n - Searcher dashboard: \"Search errors on unindexed repositories\" no longer includes cancelled search requests (which are expected).\n - Fixed an issue where NaN could leak into the `alert_count` metric. [#9832](https://github.com/sourcegraph/sourcegraph/issues/9832)\n - Gitserver: \"resolve_revision_duration_slow\" alert is no longer flaky / non-deterministic. [#9751](https://github.com/sourcegraph/sourcegraph/issues/9751)\n - Git Server dashboard: there is now a panel to show concurrent command executions to match the defined alerts. [#9354](https://github.com/sourcegraph/sourcegraph/issues/9354)\n - Git Server dashboard: adjusted the critical disk space alert to 15% so it can now fire. [#9351](https://github.com/sourcegraph/sourcegraph/issues/9351)\n - **Dashboard visiblity and legibility improvements**\n - all: \"frontend internal errors\" are now broken down just by route, which makes reading the graph easier. [#9668](https://github.com/sourcegraph/sourcegraph/issues/9668)\n - Frontend dashboard: panels no longer show misleading duplicate labels. [#9660](https://github.com/sourcegraph/sourcegraph/issues/9660)\n - Syntect Server dashboard: panels are no longer compacted, for improved visibility. [#9525](https://github.com/sourcegraph/sourcegraph/issues/9525)\n - Frontend dashboard: panels are no longer compacted, for improved visibility. [#9356](https://github.com/sourcegraph/sourcegraph/issues/9356)\n - Searcher dashboard: \"Search errors on unindexed repositories\" is now broken down by code instead of instance for improved readability. [#9670](https://github.com/sourcegraph/sourcegraph/issues/9670)\n - Symbols dashboard: metrics are now aggregated instead of per-instance, for improved visibility. [#9730](https://github.com/sourcegraph/sourcegraph/issues/9730)\n - Firing alerts are now correctly sorted at the top of dashboards by default. [#9766](https://github.com/sourcegraph/sourcegraph/issues/9766)\n - Panels at the bottom of the home dashboard no longer appear clipped / cut off. [#9768](https://github.com/sourcegraph/sourcegraph/issues/9768)\n - Git Server dashboard: disk usage now shown in percentages to match the alerts that can fire. [#9352](https://github.com/sourcegraph/sourcegraph/issues/9352)\n - Git Server dashboard: the 'echo command duration test' panel now properly displays units in seconds. [#7628](https://github.com/sourcegraph/sourcegraph/issues/7628)\n - Dashboard panels showing firing alerts no longer over-count firing alerts due to the number of service replicas. [#9353](https://github.com/sourcegraph/sourcegraph/issues/9353)", "### Removed", "- The experimental feature discussions is marked as deprecated. GraphQL and configuration fields related to it will be removed in 3.16. [#9649](https://github.com/sourcegraph/sourcegraph/issues/9649)", "## 3.14.4", "### Fixed", "- A potential security vulnerability with in the authentication workflow has been fixed. [#10167](https://github.com/sourcegraph/sourcegraph/pull/10167)", "## 3.14.3", "### Fixed", "- phabricator: Duplicate requests to phabricator API from sourcegraph extensions. [#8849](https://github.com/sourcegraph/sourcegraph/issues/8849)", "## 3.14.2", "### Fixed", "- campaigns: Ignore changesets where repo does not exist anymore. [#9656](https://github.com/sourcegraph/sourcegraph/pull/9656)", "## 3.14.1", "### Added", "- monitoring: new Permissions dashboard to show stats of repository permissions.", "### Changed", "- Site-Admin/Instrumentation in the Kubernetes cluster deployment now includes indexed-search.", "## 3.14.0", "### Added", "- Site-Admin/Instrumentation is now available in the Kubernetes cluster deployment [8805](https://github.com/sourcegraph/sourcegraph/pull/8805).\n- Extensions can now specify a `baseUri` in the `DocumentFilter` when registering providers.\n- Admins can now exclude GitHub forks and/or archived repositories from the set of repositories being mirrored in Sourcegraph with the `\"exclude\": [{\"forks\": true}]` or `\"exclude\": [{\"archived\": true}]` GitHub external service configuration. [#8974](https://github.com/sourcegraph/sourcegraph/pull/8974)\n- Campaign changesets can be filtered by State, Review State and Check State. [#8848](https://github.com/sourcegraph/sourcegraph/pull/8848)\n- Counts of users of and searches conducted with interactive and plain text search modes will be sent back in pings, aggregated daily, weekly, and monthly.\n- Aggregated counts of daily, weekly, and monthly active users of search will be sent back in pings.\n- Counts of number of searches conducted using each filter will be sent back in pings, aggregated daily, weekly, and monthly.\n- Counts of number of users conducting searches containing each filter will be sent back in pings, aggregated daily, weekly, and monthly.\n- Added more entries (Bash, Erlang, Julia, OCaml, Scala) to the list of suggested languages for the `lang:` filter.\n- Permissions background sync is now supported for GitLab and Bitbucket Server via site configuration `\"permissions.backgroundSync\": {\"enabled\": true}`.\n- Indexed search exports more prometheus metrics and debug logs to aid debugging performance issues. [#9111](https://github.com/sourcegraph/sourcegraph/issues/9111)\n- monitoring: the Frontend dashboard now shows in excellent detail how search is behaving overall and at a glance.\n- monitoring: added alerts for when hard search errors (both timeouts and general errors) are high.\n- monitoring: added alerts for when partial search timeouts are high.\n- monitoring: added alerts for when search 90th and 99th percentile request duration is high.\n- monitoring: added alerts for when users are being shown an abnormally large amount of search alert user suggestions and no results.\n- monitoring: added alerts for when the internal indexed and unindexed search services are returning bad responses.\n- monitoring: added alerts for when gitserver may be under heavy load due to many concurrent command executions or under-provisioning.", "### Changed", "- The \"automation\" feature was renamed to \"campaigns\".\n - `campaigns.readAccess.enabled` replaces the deprecated site configuration property `automation.readAccess.enabled`.\n - The experimental feature flag was not renamed (because it will go away soon) and remains `{\"experimentalFeatures\": {\"automation\": \"enabled\"}}`.\n- The [Kubernetes deployment](https://github.com/sourcegraph/deploy-sourcegraph) for **existing** installations requires a\n [migration step](https://github.com/sourcegraph/deploy-sourcegraph/blob/master/docs/migrate.md) when upgrading\n past commit [821032e2ee45f21f701](https://github.com/sourcegraph/deploy-sourcegraph/commit/821032e2ee45f21f701caac624e4f090c59fd259) or when upgrading to 3.14.\n New installations starting with the mentioned commit or with 3.14 do not need this migration step.\n- Aggregated search latencies (in ms) of search queries are now included in [pings](https://docs.sourcegraph.com/admin/pings).\n- The [Kubernetes deployment](https://github.com/sourcegraph/deploy-sourcegraph) frontend role has added services as a resource to watch/listen/get.\n This change does not affect the newly-introduced, restricted Kubernetes config files.\n- Archived repositories are excluded from search by default. Adding `archived:yes` includes archived repositories.\n- Forked repositories are excluded from search by default. Adding `fork:yes` includes forked repositories.\n- CSRF and session cookies now set `SameSite=None` when Sourcegraph is running behind HTTPS and `SameSite=Lax` when Sourcegraph is running behind HTTP in order to comply with a [recent IETF proposal](https://web.dev/samesite-cookies-explained/#samesitenone-must-be-secure). As a side effect, the Sourcegraph browser extension and GitLab/Bitbucket native integrations can only connect to private instances that have HTTPS configured. If your private instance is only running behind HTTP, please configure your instance to use HTTPS in order to continue using these.\n- The Bitbucket Server rate limit that Sourcegraph self-imposes has been raised from 120 req/min to 480 req/min to account for Sourcegraph instances that make use of Sourcegraphs' Bitbucket Server repository permissions and campaigns at the same time (which require a larger number of API requests against Bitbucket Server). The new number is based on Sourcegraph consuming roughly 8% the average API request rate of a large customers' Bitbucket Server instance. [#9048](https://github.com/sourcegraph/sourcegraph/pull/9048/files)\n- If a single, unambiguous commit SHA is used in a search query (e.g., `repo@c98f56`) and a search index exists at this commit (i.e., it is the `HEAD` commit), then the query is searched using the index. Prior to this change, unindexed search was performed for any query containing an `@commit` specifier.", "### Fixed", "- Zoekt's watchdog ensures the service is down upto 3 times before exiting. The watchdog would misfire on startup on resource constrained systems, with the retries this should make a false positive far less likely. [#7867](https://github.com/sourcegraph/sourcegraph/issues/7867)\n- A regression in repo-updater was fixed that lead to every repository's git clone being updated every time the list of repositories was synced from the code host. [#8501](https://github.com/sourcegraph/sourcegraph/issues/8501)\n- The default timeout of indexed search has been increased. Previously indexed search would always return within 3s. This lead to broken behaviour on new instances which had yet to tune resource allocations. [#8720](https://github.com/sourcegraph/sourcegraph/pull/8720)\n- Bitbucket Server older than 5.13 failed to sync since Sourcegraph 3.12. This was due to us querying for the `archived` label, but Bitbucket Server 5.13 does not support labels. [#8883](https://github.com/sourcegraph/sourcegraph/issues/8883)\n- monitoring: firing alerts are now ordered at the top of the list in dashboards by default for better visibility.\n- monitoring: fixed an issue where some alerts would fail to report in for the \"Total alerts defined\" panel in the overview dashboard.", "### Removed", "- The v3.11 migration to merge critical and site configuration has been removed. If you are still making use of the deprecated `CRITICAL_CONFIG_FILE`, your instance may not start up. See the [migration notes for Sourcegraph 3.11](https://docs.sourcegraph.com/admin/migration/3_11) for more information.", "## 3.13.2", "### Fixed", "- The default timeout of indexed search has been increased. Previously indexed search would always return within 3s. This lead to broken behaviour on new instances which had yet to tune resource allocations. [#8720](https://github.com/sourcegraph/sourcegraph/pull/8720)\n- Bitbucket Server older than 5.13 failed to sync since Sourcegraph 3.12. This was due to us querying for the `archived` label, but Bitbucket Server 5.13 does not support labels. [#8883](https://github.com/sourcegraph/sourcegraph/issues/8883)\n- A regression in repo-updater was fixed that lead to every repository's git clone being updated every time the list of repositories was synced from the code host. [#8501](https://github.com/sourcegraph/sourcegraph/issues/8501)", "## 3.13.1", "### Fixed", "- To reduce the chance of users running into \"502 Bad Gateway\" errors an internal timeout has been increased from 60 seconds to 10 minutes so that long running requests are cut short by the proxy in front of `sourcegraph-frontend` and correctly reported as \"504 Gateway Timeout\". [#8606](https://github.com/sourcegraph/sourcegraph/pull/8606)\n- Sourcegraph instances that are not connected to the internet will no longer display errors when users submit NPS survey responses (the responses will continue to be stored locally). Rather, an error will be printed to the frontend logs. [#8598](https://github.com/sourcegraph/sourcegraph/issues/8598)\n- Showing `head>` in the search results if the first line of the file is shown [#8619](https://github.com/sourcegraph/sourcegraph/issues/8619)", "## 3.13.0", "### Added", "- Experimental: Added new field `experimentalFeatures.customGitFetch` that allows defining custom git fetch commands for code hosts and repositories with special settings. [#8435](https://github.com/sourcegraph/sourcegraph/pull/8435)\n- Experimental: the search query input now provides syntax highlighting, hover tooltips, and diagnostics on filters in search queries. Requires the global settings value `{ \"experimentalFeatures\": { \"smartSearchField\": true } }`.\n- Added a setting `search.hideSuggestions`, which when set to `true`, will hide search suggestions in the search bar. [#8059](https://github.com/sourcegraph/sourcegraph/pull/8059)\n- Experimental: A tool, [src-expose](https://docs.sourcegraph.com/admin/external_service/other#experimental-src-expose), can be used to import code from any code host.\n- Experimental: Added new field `certificates` as in `{ \"experimentalFeatures\" { \"tls.external\": { \"certificates\": [\"<CERT>\"] } } }`. This allows you to add certificates to trust when communicating with a code host (via API or git+http). We expect this to be useful for adding internal certificate authorities/self-signed certificates. [#71](https://github.com/sourcegraph/sourcegraph/issues/71)\n- Added a setting `auth.minPasswordLength`, which when set, causes a minimum password length to be enforced when users sign up or change passwords. [#7521](https://github.com/sourcegraph/sourcegraph/issues/7521)\n- GitHub labels associated with code change campaigns are now displayed. [#8115](https://github.com/sourcegraph/sourcegraph/pull/8115)\n- GitHub labels associated with campaigns are now displayed. [#8115](https://github.com/sourcegraph/sourcegraph/pull/8115)\n- When creating a campaign, users can now specify the branch name that will be used on code host. This is also a breaking change for users of the GraphQL API since the `branch` attribute is now required in `CreateCampaignInput` when a `plan` is also specified. [#7646](https://github.com/sourcegraph/sourcegraph/issues/7646)\n- Added an optional `content:` parameter for specifying a search pattern. This parameter overrides any other search patterns in a query. Useful for unambiguously specifying what to search for when search strings clash with other query syntax. [#6490](https://github.com/sourcegraph/sourcegraph/issues/6490)\n- Interactive search mode, which helps users construct queries using UI elements, is now made available to users by default. A dropdown to the left of the search bar allows users to toggle between interactive and plain text modes. The option to use interactive search mode can be disabled by adding `{ \"experimentalFeatures\": { \"splitSearchModes\": false } }` in global settings. [#8461](https://github.com/sourcegraph/sourcegraph/pull/8461)\n- Our [upgrade policy](https://docs.sourcegraph.com/#upgrading-sourcegraph) is now enforced by the `sourcegraph-frontend` on startup to prevent admins from mistakenly jumping too many versions. [#8157](https://github.com/sourcegraph/sourcegraph/pull/8157) [#7702](https://github.com/sourcegraph/sourcegraph/issues/7702)\n- Repositories with bad object packs or bad objects are automatically repaired. We now detect suspect output of git commands to mark a repository for repair. [#6676](https://github.com/sourcegraph/sourcegraph/issues/6676)\n- Hover tooltips for Scala and Perl files now have syntax highlighting. [#8456](https://github.com/sourcegraph/sourcegraph/pull/8456) [#8307](https://github.com/sourcegraph/sourcegraph/issues/8307)", "### Changed", "- `experimentalFeatures.splitSearchModes` was removed as a site configuration option. It should be set in global/org/user settings.\n- Sourcegraph now waits for `90s` instead of `5s` for Redis to be available before quitting. This duration is configurable with the new `SRC_REDIS_WAIT_FOR` environment variable.\n- Code intelligence usage statistics will be sent back via pings by default. Aggregated event counts can be disabled via the site admin flag `disableNonCriticalTelemetry`.\n- The Sourcegraph Docker image optimized its use of Redis to make start-up significantly faster in certain scenarios (e.g when container restarts were frequent). ([#3300](https://github.com/sourcegraph/sourcegraph/issues/3300), [#2904](https://github.com/sourcegraph/sourcegraph/issues/2904))\n- Upgrading Sourcegraph is officially supported for one minor version increment (e.g., 3.12 -> 3.13). Previously, upgrades from 2 minor versions previous were supported. Please reach out to support@sourcegraph.com if you would like assistance upgrading from a much older version of Sourcegraph.\n- The GraphQL mutation `previewCampaignPlan` has been renamed to `createCampaignPlan`. This mutation is part of campaigns, which is still in beta and behind a feature flag and thus subject to possible breaking changes while we still work on it.\n- The GraphQL mutation `previewCampaignPlan` has been renamed to `createCampaignPlan`. This mutation is part of the campaigns feature, which is still in beta and behind a feature flag and thus subject to possible breaking changes while we still work on it.\n- The GraphQL field `CampaignPlan.changesets` has been deprecated and will be removed in 3.15. A new field called `CampaignPlan.changesetPlans` has been introduced to make the naming more consistent with the `Campaign.changesetPlans` field. Please use that instead. [#7966](https://github.com/sourcegraph/sourcegraph/pull/7966)\n- Long lines (>2000 bytes) are no longer highlighted, in order to prevent performance issues in browser rendering. [#6489](https://github.com/sourcegraph/sourcegraph/issues/6489)\n- No longer requires `read:org` permissions for GitHub OAuth if `allowOrgs` is not enabled in the site configuration. [#8163](https://github.com/sourcegraph/sourcegraph/issues/8163)\n- [Documentation](https://github.com/sourcegraph/deploy-sourcegraph/blob/master/configure/jaeger/README.md) in github.com/sourcegraph/deploy-sourcegraph for deploying Jaeger in Kubernetes clusters running Sourcegraph has been updated to use the [Jaeger Operator](https://www.jaegertracing.io/docs/1.16/operator/), the recommended standard way of deploying Jaeger in a Kubernetes cluster. We recommend existing customers that use Jaeger adopt this new method of deployment. Please reach out to support@sourcegraph.com if you'd like assistance updating.", "### Fixed", "- The syntax highlighter (syntect-server) no longer fails when run in environments without IPv6 support. [#8463](https://github.com/sourcegraph/sourcegraph/pull/8463)\n- After adding/removing a gitserver replica the admin interface will correctly report that repositories that need to move replicas as cloning. [#7970](https://github.com/sourcegraph/sourcegraph/issues/7970)\n- Show download button for images. [#7924](https://github.com/sourcegraph/sourcegraph/issues/7924)\n- gitserver backoffs trying to re-clone repositories if they fail to clone. In the case of large monorepos that failed this lead to gitserver constantly cloning them and using many resources. [#7804](https://github.com/sourcegraph/sourcegraph/issues/7804)\n- It is now possible to escape spaces using `\\` in the search queries when using regexp. [#7604](https://github.com/sourcegraph/sourcegraph/issues/7604)\n- Clicking filter chips containing whitespace is now correctly quoted in the web UI. [#6498](https://github.com/sourcegraph/sourcegraph/issues/6498)\n- **Monitoring:** Fixed an issue with the **Frontend** -> **Search responses by status** panel which caused search response types to not be aggregated as expected. [#7627](https://github.com/sourcegraph/sourcegraph/issues/7627)\n- **Monitoring:** Fixed an issue with the **Replacer**, **Repo Updater**, and **Searcher** dashboards would incorrectly report on a metric from the unrelated query-runner service. [#7531](https://github.com/sourcegraph/sourcegraph/issues/7531)\n- Deterministic ordering of results from indexed search. Previously when refreshing a page with many results some results may come and go.\n- Spread out periodic git reclones. Previously we would reclone all git repositories every 45 days. We now add in a jitter of 12 days to spread out the load for larger installations. [#8259](https://github.com/sourcegraph/sourcegraph/issues/8259)\n- Fixed an issue with missing commit information in graphql search results. [#8343](https://github.com/sourcegraph/sourcegraph/pull/8343)", "### Removed", "- All repository fields related to `enabled` and `disabled` have been removed from the GraphQL API. These fields have been deprecated since 3.4. [#3971](https://github.com/sourcegraph/sourcegraph/pull/3971)\n- The deprecated extension API `Hover.__backcompatContents` was removed.", "## 3.12.10", "This release backports the fixes released in `3.13.2` for customers still on `3.12`.", "### Fixed", "- The default timeout of indexed search has been increased. Previously indexed search would always return within 3s. This lead to broken behaviour on new instances which had yet to tune resource allocations. [#8720](https://github.com/sourcegraph/sourcegraph/pull/8720)\n- Bitbucket Server older than 5.13 failed to sync since Sourcegraph 3.12. This was due to us querying for the `archived` label, but Bitbucket Server 5.13 does not support labels. [#8883](https://github.com/sourcegraph/sourcegraph/issues/8883)\n- A regression in repo-updater was fixed that lead to every repository's git clone being updated every time the list of repositories was synced from the code host. [#8501](https://github.com/sourcegraph/sourcegraph/issues/8501)", "## 3.12.9", "This is `3.12.8` release with internal infrastructure fixes to publish the docker images.", "## 3.12.8", "### Fixed", "- Extension API showInputBox and other Window methods now work on search results pages [#8519](https://github.com/sourcegraph/sourcegraph/issues/8519)\n- Extension error notification styling is clearer [#8521](https://github.com/sourcegraph/sourcegraph/issues/8521)", "## 3.12.7", "### Fixed", "- Campaigns now gracefully handle GitHub review dismissals when rendering the burndown chart.", "## 3.12.6", "### Changed", "- When GitLab permissions are turned on using GitLab OAuth authentication, GitLab project visibility is fetched in batches, which is generally more efficient than fetching them individually. The `minBatchingThreshold` and `maxBatchRequests` fields of the `authorization.identityProvider` object in the GitLab repositories configuration control when such batch fetching is used. [#8171](https://github.com/sourcegraph/sourcegraph/pull/8171)", "## 3.12.5", "### Fixed", "- Fixed an internal race condition in our Docker build process. The previous patch version 3.12.4 contained an lsif-server version that was newer than expected. The affected artifacts have since been removed from the Docker registry.", "## 3.12.4", "### Added", "- New optional `apiURL` configuration option for Bitbucket Cloud code host connection [#8082](https://github.com/sourcegraph/sourcegraph/pull/8082)", "## 3.12.3", "### Fixed", "- Fixed an issue in `sourcegraph/*` Docker images where data folders were either not created or had incorrect permissions - preventing the use of Docker volumes. [#7991](https://github.com/sourcegraph/sourcegraph/pull/7991)", "## 3.12.2", "### Added", "- Experimental: The site configuration field `campaigns.readAccess.enabled` allows site-admins to give read-only access for code change campaigns to non-site-admins. This is a setting for the experimental feature campaigns and will only have an effect when campaigns are enabled under `experimentalFeatures`. [#8013](https://github.com/sourcegraph/sourcegraph/issues/8013)", "### Fixed", "- A regression in 3.12.0 which caused [find-leaked-credentials campaigns](https://docs.sourcegraph.com/user/campaigns#finding-leaked-credentials) to not return any results for private repositories. [#7914](https://github.com/sourcegraph/sourcegraph/issues/7914)\n- Experimental: The site configuration field `campaigns.readAccess.enabled` allows site-admins to give read-only access for campaigns to non-site-admins. This is a setting for the experimental campaigns feature and will only have an effect when campaigns is enabled under `experimentalFeatures`. [#8013](https://github.com/sourcegraph/sourcegraph/issues/8013)", "### Fixed", "- A regression in 3.12.0 which caused find-leaked-credentials campaigns to not return any results for private repositories. [#7914](https://github.com/sourcegraph/sourcegraph/issues/7914)\n- A regression in 3.12.0 which removed the horizontal bar between search result matches.\n- Manual campaigns were wrongly displayed as being in draft mode. [#8009](https://github.com/sourcegraph/sourcegraph/issues/8009)\n- Manual campaigns could be published and create the wrong changesets on code hosts, even though the campaign was never in draft mode (see line above). [#8012](https://github.com/sourcegraph/sourcegraph/pull/8012)\n- A regression in 3.12.0 which caused manual campaigns to not properly update the UI after adding a changeset. [#8023](https://github.com/sourcegraph/sourcegraph/pull/8023)\n- Minor improvements to manual campaign form fields. [#8033](https://github.com/sourcegraph/sourcegraph/pull/8033)", "## 3.12.1", "### Fixed", "- The ephemeral `/site-config.json` escape-hatch config file has moved to `$HOME/site-config.json`, to support non-root container environments. [#7873](https://github.com/sourcegraph/sourcegraph/issues/7873)\n- Fixed an issue where repository permissions would sometimes not be cached, due to improper Redis nil value handling. [#7912](https://github.com/sourcegraph/sourcegraph/issues/7912)", "## 3.12.0", "### Added", "- Bitbucket Server repositories with the label `archived` can be excluded from search with `archived:no` [syntax](https://docs.sourcegraph.com/code_search/reference/queries). [#5494](https://github.com/sourcegraph/sourcegraph/issues/5494)\n- Add button to download file in code view. [#5478](https://github.com/sourcegraph/sourcegraph/issues/5478)\n- The new `allowOrgs` site config setting in GitHub `auth.providers` enables admins to restrict GitHub logins to members of specific GitHub organizations. [#4195](https://github.com/sourcegraph/sourcegraph/issues/4195)\n- Support case field in repository search. [#7671](https://github.com/sourcegraph/sourcegraph/issues/7671)\n- Skip LFS content when cloning git repositories. [#7322](https://github.com/sourcegraph/sourcegraph/issues/7322)\n- Hover tooltips and _Find Reference_ results now display a badge to indicate when a result is search-based. These indicators can be disabled by adding `{ \"experimentalFeatures\": { \"showBadgeAttachments\": false } }` in global settings.\n- Campaigns can now be created as drafts, which can be shared and updated without creating changesets (pull requests) on code hosts. When ready, a draft can then be published, either completely or changeset by changeset, to create changesets on the code host. [#7659](https://github.com/sourcegraph/sourcegraph/pull/7659)\n- Experimental: feature flag `BitbucketServerFastPerm` can be enabled to speed up fetching ACL data from Bitbucket Server instances. This requires [Bitbucket Server Sourcegraph plugin](https://github.com/sourcegraph/bitbucket-server-plugin) to be installed.\n- Experimental: A site configuration field `{ \"experimentalFeatures\" { \"tls.external\": { \"insecureSkipVerify\": true } } }` which allows you to configure SSL/TLS settings for Sourcegraph contacting your code hosts. Currently just supports turning off TLS/SSL verification. [#71](https://github.com/sourcegraph/sourcegraph/issues/71)\n- Experimental: To search across multiple revisions of the same repository, list multiple branch names (or other revspecs) separated by `:` in your query, as in `repo:myrepo@branch1:branch2:branch2`. To search all branches, use `repo:myrepo@*refs/heads/`. Requires the site configuration value `{ \"experimentalFeatures\": { \"searchMultipleRevisionsPerRepository\": true } }`. Previously this was only supported for diff and commit searches.\n- Experimental: interactive search mode, which helps users construct queries using UI elements. Requires the site configuration value `{ \"experimentalFeatures\": { \"splitSearchModes\": true } }`. The existing plain text search format is still available via the dropdown menu on the left of the search bar.\n- A case sensitivity toggle now appears in the search bar.\n- Add explicit repository permissions support with site configuration field `{ \"permissions.userMapping\" { \"enabled\": true, \"bindID\": \"email\" } }`.", "### Changed", "- The \"Files\" tab in the search results page has been renamed to \"Filenames\" for clarity.\n- The search query builder now lives on its own page at `/search/query-builder`. The home search page has a link to it.\n- User passwords when using builtin auth are limited to 256 characters. Existing passwords longer than 256 characters will continue to work.\n- GraphQL API: Campaign.changesetCreationStatus has been renamed to Campaign.status to be aligned with CampaignPlan. [#7654](https://github.com/sourcegraph/sourcegraph/pull/7654)\n- When using GitHub as an authentication provider, `read:org` scope is now required. This is used to support the new `allowOrgs` site config setting in the GitHub `auth.providers` configuration, which enables site admins to restrict GitHub logins to members of a specific GitHub organization. This for example allows having a Sourcegraph instance with GitHub sign in configured be exposed to the public internet without allowing everyone with a GitHub account access to your Sourcegraph instance.", "### Fixed", "- The experimental search pagination API no longer times out when large repositories are encountered. [#6384](https://github.com/sourcegraph/sourcegraph/issues/6384)\n- We resolve relative symbolic links from the directory of the symlink, rather than the root of the repository. [#6034](https://github.com/sourcegraph/sourcegraph/issues/6034)\n- Show errors on repository settings page when repo-updater is down. [#3593](https://github.com/sourcegraph/sourcegraph/issues/3593)\n- Remove benign warning that verifying config took more than 10s when updating or saving an external service. [#7176](https://github.com/sourcegraph/sourcegraph/issues/7176)\n- repohasfile search filter works again (regressed in 3.10). [#7380](https://github.com/sourcegraph/sourcegraph/issues/7380)\n- Structural search can now run on very large repositories containing any number of files. [#7133](https://github.com/sourcegraph/sourcegraph/issues/7133)", "### Removed", "- The deprecated GraphQL mutation `setAllRepositoriesEnabled` has been removed. [#7478](https://github.com/sourcegraph/sourcegraph/pull/7478)\n- The deprecated GraphQL mutation `deleteRepository` has been removed. [#7483](https://github.com/sourcegraph/sourcegraph/pull/7483)", "## 3.11.4", "### Fixed", "- The `/.auth/saml/metadata` endpoint has been fixed. Previously it panicked if no encryption key was set.\n- The version updating logic has been fixed for `sourcegraph/server`. Users running `sourcegraph/server:3.11.1` will need to manually modify their `docker run` command to use `sourcegraph/server:3.11.4` or higher. [#7442](https://github.com/sourcegraph/sourcegraph/issues/7442)", "## 3.11.1", "### Fixed", "- The syncing process for newly created campaign changesets has been fixed again after they have erroneously been marked as deleted in the database. [#7522](https://github.com/sourcegraph/sourcegraph/pull/7522)\n- The syncing process for newly created changesets (in campaigns) has been fixed again after they have erroneously been marked as deleted in the database. [#7522](https://github.com/sourcegraph/sourcegraph/pull/7522)", "## 3.11.0", "**Important:** If you use `SITE_CONFIG_FILE` or `CRITICAL_CONFIG_FILE`, please be sure to follow the steps in: [migration notes for Sourcegraph v3.11+](https://docs.sourcegraph.com/admin/migration/3_11.md) after upgrading.", "### Added", "- Language statistics by commit are available via the API. [#6737](https://github.com/sourcegraph/sourcegraph/pull/6737)\n- Added a new page that shows [language statistics for the results of a search query](https://docs.sourcegraph.com/user/search#statistics).\n- Global settings can be configured from a local file using the environment variable `GLOBAL_SETTINGS_FILE`.\n- High-level health metrics and dashboards have been added to Sourcegraph's monitoring (found under the **Site admin** -> **Monitoring** area). [#7216](https://github.com/sourcegraph/sourcegraph/pull/7216)\n- Logging for GraphQL API requests not issued by Sourcegraph is now much more verbose, allowing for easier debugging of problematic queries and where they originate from. [#5706](https://github.com/sourcegraph/sourcegraph/issues/5706)\n- A new campaign type finds and removes leaked NPM credentials. [#6893](https://github.com/sourcegraph/sourcegraph/pull/6893)\n- Campaigns can now be retried to create failed changesets due to ephemeral errors (e.g. network problems when creating a pull request on GitHub). [#6718](https://github.com/sourcegraph/sourcegraph/issues/6718)\n- The initial release of [structural code search](https://docs.sourcegraph.com/code_search/reference/structural).", "### Changed", "- `repohascommitafter:` search filter uses a more efficient git command to determine inclusion. [#6739](https://github.com/sourcegraph/sourcegraph/pull/6739)\n- `NODE_NAME` can be specified instead of `HOSTNAME` for zoekt-indexserver. `HOSTNAME` was a confusing configuration to use in [Pure-Docker Sourcegraph deployments](https://github.com/sourcegraph/deploy-sourcegraph-docker). [#6846](https://github.com/sourcegraph/sourcegraph/issues/6846)\n- The feedback toast now requests feedback every 60 days of usage (was previously only once on the 3rd day of use). [#7165](https://github.com/sourcegraph/sourcegraph/pull/7165)\n- The lsif-server container now only has a dependency on Postgres, whereas before it also relied on Redis. [#6880](https://github.com/sourcegraph/sourcegraph/pull/6880)\n- Renamed the GraphQL API `LanguageStatistics` fields to `name`, `totalBytes`, and `totalLines` (previously the field names started with an uppercase letter, which was inconsistent).\n- Detecting a file's language uses a more accurate but slower algorithm. To revert to the old (faster and less accurate) algorithm, set the `USE_ENHANCED_LANGUAGE_DETECTION` env var to the string `false` (on the `sourcegraph/server` container, or if using the cluster deployment, on the `sourcegraph-frontend` pod).\n- Diff and commit searches that make use of `before:` and `after:` filters to narrow their search area are now no longer subject to the 50-repository limit. This allows for creating saved searches on more than 50 repositories as before. [#7215](https://github.com/sourcegraph/sourcegraph/issues/7215)", "### Fixed", "- Changes to external service configurations are reflected much faster. [#6058](https://github.com/sourcegraph/sourcegraph/issues/6058)\n- Deleting an external service will not show warnings for the non-existent service. [#5617](https://github.com/sourcegraph/sourcegraph/issues/5617)\n- Suggested search filter chips are quoted if necessary. [#6498](https://github.com/sourcegraph/sourcegraph/issues/6498)\n- Remove potential panic in gitserver if heavily loaded. [#6710](https://github.com/sourcegraph/sourcegraph/issues/6710)\n- Multiple fixes to make the preview and creation of campaigns more robust and a smoother user experience. [#6682](https://github.com/sourcegraph/sourcegraph/pull/6682) [#6625](https://github.com/sourcegraph/sourcegraph/issues/6625) [#6658](https://github.com/sourcegraph/sourcegraph/issues/6658) [#7088](https://github.com/sourcegraph/sourcegraph/issues/7088) [#6766](https://github.com/sourcegraph/sourcegraph/issues/6766) [#6717](https://github.com/sourcegraph/sourcegraph/issues/6717) [#6659](https://github.com/sourcegraph/sourcegraph/issues/6659)\n- Repositories referenced in campaigns that are removed in an external service configuration change won't lead to problems with the syncing process anymore. [#7015](https://github.com/sourcegraph/sourcegraph/pull/7015)\n- The Searcher dashboard (and the `src_graphql_search_response` Prometheus metric) now properly account for search alerts instead of them being incorrectly added to the `timeout` category. [#7214](https://github.com/sourcegraph/sourcegraph/issues/7214)\n- In the experimental search pagination API, the `cloning`, `missing`, and other repository fields now return a well-defined set of results. [#6000](https://github.com/sourcegraph/sourcegraph/issues/6000)", "### Removed", "- The management console has been removed. All critical configuration previously stored in the management console will be automatically migrated to your site configuration. For more information about this change, or if you use `SITE_CONFIG_FILE` / `CRITICAL_CONFIG_FILE`, please see the [migration notes for Sourcegraph v3.11+](https://docs.sourcegraph.com/admin/migration/3_11.md).", "## 3.10.4", "### Fixed", "- An issue where diff/commit searches that would run over more than 50 repositories would incorrectly display a timeout error instead of the correct error suggesting users scope their query to less repositories. [#7090](https://github.com/sourcegraph/sourcegraph/issues/7090)", "## 3.10.3", "### Fixed", "- A critical regression in 3.10.2 which caused diff, commit, and repository searches to timeout. [#7090](https://github.com/sourcegraph/sourcegraph/issues/7090)\n- A critical regression in 3.10.2 which caused \"No results\" to appear frequently on pages with search results. [#7095](https://github.com/sourcegraph/sourcegraph/pull/7095)\n- An issue where the built-in Grafana Searcher dashboard would show duplicate success/error metrics. [#7078](https://github.com/sourcegraph/sourcegraph/pull/7078)", "## 3.10.2", "### Added", "- Site admins can now use the built-in Grafana Searcher dashboard to observe how many search requests are successful, or resulting in errors or timeouts. [#6756](https://github.com/sourcegraph/sourcegraph/issues/6756)", "### Fixed", "- When searches timeout, a consistent UI with clear actions like a button to increase the timeout is now returned. [#6754](https://github.com/sourcegraph/sourcegraph/issues/6754)\n- To reduce the chance of search timeouts in some cases, the default indexed search timeout has been raised from 1.5s to 3s. [#6754](https://github.com/sourcegraph/sourcegraph/issues/6754)\n- We now correctly inform users of the limitations of diff/commit search. If a diff/commit search would run over more than 50 repositories, users will be shown an error suggesting they scope their search to less repositories using the `repo:` filter. Global diff/commit search support is being tracked in [#6826](https://github.com/sourcegraph/sourcegraph/issues/6826). [#5519](https://github.com/sourcegraph/sourcegraph/issues/5519)", "## 3.10.1", "### Added", "- Syntax highlighting for Starlark (Bazel) files. [#6827](https://github.com/sourcegraph/sourcegraph/issues/6827)", "### Fixed", "- The experimental search pagination API no longer times out when large repositories are encountered. [#6384](https://github.com/sourcegraph/sourcegraph/issues/6384) [#6383](https://github.com/sourcegraph/sourcegraph/issues/6383)\n- In single-container deployments, the builtin `postgres_exporter` now correctly respects externally configured databases. This previously caused PostgreSQL metrics to not show up in Grafana when an external DB was in use. [#6735](https://github.com/sourcegraph/sourcegraph/issues/6735)", "## 3.10.0", "### Added", "- Indexed Search supports horizontally scaling. Instances with large number of repositories can update the `replica` field of the `indexed-search` StatefulSet. See [configure indexed-search replica count](https://github.com/sourcegraph/deploy-sourcegraph/blob/master/docs/configure.md#configure-indexed-search-replica-count). [#5725](https://github.com/sourcegraph/sourcegraph/issues/5725)\n- Bitbucket Cloud external service supports `exclude` config option. [#6035](https://github.com/sourcegraph/sourcegraph/issues/6035)\n- `sourcegraph/server` Docker deployments now support the environment variable `IGNORE_PROCESS_DEATH`. If set to true the container will keep running, even if a subprocess has died. This is useful when manually fixing problems in the container which the container refuses to start. For example a bad database migration.\n- Search input now offers filter type suggestions [#6105](https://github.com/sourcegraph/sourcegraph/pull/6105).\n- The keyboard shortcut <kbd>Ctrl</kbd>+<kbd>Space</kbd> in the search input shows a list of available filter types.\n- Sourcegraph Kubernetes cluster site admins can configure PostgreSQL by specifying `postgresql.conf` via ConfigMap. [sourcegraph/deploy-sourcegraph#447](https://github.com/sourcegraph/deploy-sourcegraph/pull/447)", "### Changed", "- **Required Kubernetes Migration:** The [Kubernetes deployment](https://github.com/sourcegraph/deploy-sourcegraph) manifest for indexed-search services has changed from a Normal Service to a Headless Service. This is to enable Sourcegraph to individually resolve indexed-search pods. Services are immutable, so please follow the [migration guide](https://github.com/sourcegraph/deploy-sourcegraph/blob/master/docs/migrate.md#310).\n- Fields of type `String` in our GraphQL API that contain [JSONC](https://komkom.github.io/) now have the custom scalar type `JSONCString`. [#6209](https://github.com/sourcegraph/sourcegraph/pull/6209)\n- `ZOEKT_HOST` environment variable has been deprecated. Please use `INDEXED_SEARCH_SERVERS` instead. `ZOEKT_HOST` will be removed in 3.12.\n- Directory names on the repository tree page are now shown in bold to improve readability.\n- Added support for Bitbucket Server pull request activity to the [campaign](https://about.sourcegraph.com/product/code-change-management/) burndown chart. When used, this feature leads to more requests being sent to Bitbucket Server, since Sourcegraph needs to keep track of how a pull request's state changes over time. With [the instance scoped webhooks](https://docs.google.com/document/d/1I3Aq1WSUh42BP8KvKr6AlmuCfo8tXYtJu40WzdNT6go/edit) in our [Bitbucket Server plugin](https://github.com/sourcegraph/bitbucket-server-plugin/pull/10) as well as up-coming [heuristical syncing changes](#6389), this additional load will be significantly reduced in the future.\n- Added support for Bitbucket Server pull request activity to the campaign burndown chart. When used, this feature leads to more requests being sent to Bitbucket Server, since Sourcegraph needs to keep track of how a pull request's state changes over time. With [the instance scoped webhooks](https://docs.google.com/document/d/1I3Aq1WSUh42BP8KvKr6AlmuCfo8tXYtJu40WzdNT6go/edit) in our [Bitbucket Server plugin](https://github.com/sourcegraph/bitbucket-server-plugin/pull/10) as well as up-coming [heuristical syncing changes](#6389), this additional load will be significantly reduced in the future.", "### Fixed", "- Support hyphens in Bitbucket Cloud team names. [#6154](https://github.com/sourcegraph/sourcegraph/issues/6154)\n- Server will run `redis-check-aof --fix` on startup to fix corrupted AOF files. [#651](https://github.com/sourcegraph/sourcegraph/issues/651)\n- Authorization provider configuration errors in external services will be shown as site alerts. [#6061](https://github.com/sourcegraph/sourcegraph/issues/6061)", "### Removed", "## 3.9.4", "### Changed", "- The experimental search pagination API's `PageInfo` object now returns a `String` instead of an `ID` for its `endCursor`, and likewise for the `after` search field. Experimental paginated search API users may need to update their usages to replace `ID` cursor types with `String` ones.", "### Fixed", "- The experimental search pagination API no longer omits a single repository worth of results at the end of the result set. [#6286](https://github.com/sourcegraph/sourcegraph/issues/6286)\n- The experimental search pagination API no longer produces search cursors that can get \"stuck\". [#6287](https://github.com/sourcegraph/sourcegraph/issues/6287)\n- In literal search mode, searching for quoted strings now works as expected. [#6255](https://github.com/sourcegraph/sourcegraph/issues/6255)\n- In literal search mode, quoted field values now work as expected. [#6271](https://github.com/sourcegraph/sourcegraph/pull/6271)\n- `type:path` search queries now correctly work in indexed search again. [#6220](https://github.com/sourcegraph/sourcegraph/issues/6220)", "## 3.9.3", "### Changed", "- Sourcegraph is now built using Go 1.13.3 [#6200](https://github.com/sourcegraph/sourcegraph/pull/6200).", "## 3.9.2", "### Fixed", "- URI-decode the username, password, and pathname when constructing Postgres connection paramers in lsif-server [#6174](https://github.com/sourcegraph/sourcegraph/pull/6174). Fixes a crashing lsif-server process for users with passwords containing special characters.", "## 3.9.1", "### Changed", "- Reverted [#6094](https://github.com/sourcegraph/sourcegraph/pull/6094) because it introduced a minor security hole involving only Grafana.\n [#6075](https://github.com/sourcegraph/sourcegraph/issues/6075) will be fixed with a different approach.", "## 3.9.0", "### Added", "- Our external service syncing model will stream in new repositories to Sourcegraph. Previously we could only add a repository to our database and clone it once we had synced all information from all external services (to detect deletions and renames). Now adding a repository to an external service configuration should be reflected much sooner, even on large instances. [#5145](https://github.com/sourcegraph/sourcegraph/issues/5145)\n- There is now an easy way for site admins to view and export settings and configuration when reporting a bug. The page for doing so is at /site-admin/report-bug, linked to from the site admin side panel under \"Report a bug\".\n- An experimental search pagination API to enable better programmatic consumption of search results is now available to try. For more details and known limitations see [the documentation](https://docs.sourcegraph.com/api/graphql/search).\n- Search queries can now be interpreted literally.\n - There is now a dot-star icon in the search input bar to toggle the pattern type of a query between regexp and literal.\n - There is a new `search.defaultPatternType` setting to configure the default pattern type, regexp or literal, for searches.\n - There is a new `patternType:` search token which overrides the `search.defaultPatternType` setting, and the active state of the dot-star icon in determining the pattern type of the query.\n - Old URLs without a patternType URL parameter will be redirected to the same URL with\n patternType=regexp appended to preserve intended behavior.\n- Added support for GitHub organization webhooks to enable faster updates of metadata used by [campaigns](https://about.sourcegraph.com/product/code-change-management/), such as pull requests or issue comments. See the [GitHub webhook documentation](https://docs.sourcegraph.com/admin/external_service/github#webhooks) for instructions on how to enable webhooks.\n- Added support for GitHub organization webhooks to enable faster updates of changeset metadata used by campaigns. See the [GitHub webhook documentation](https://docs.sourcegraph.com/admin/external_service/github#webhooks) for instructions on how to enable webhooks.\n- Added burndown chart to visualize progress of campaigns.\n- Added ability to edit campaign titles and descriptions.", "### Changed", "- **Recommended Kubernetes Migration:** The [Kubernetes deployment](https://github.com/sourcegraph/deploy-sourcegraph) manifest for indexed-search pods has changed from a Deployment to a StatefulSet. This is to enable future work on horizontally scaling indexed search. To retain your existing indexes there is a [migration guide](https://github.com/sourcegraph/deploy-sourcegraph/blob/master/docs/migrate.md#39).\n- Allow single trailing hyphen in usernames and org names [#5680](https://github.com/sourcegraph/sourcegraph/pull/5680)\n- Indexed search won't spam the logs on startup if the frontend API is not yet available. [zoekt#30](https://github.com/sourcegraph/zoekt/pull/30), [#5866](https://github.com/sourcegraph/sourcegraph/pull/5866)\n- Search query fields are now case insensitive. For example `repoHasFile:` will now be recognized, not just `repohasfile:`. [#5168](https://github.com/sourcegraph/sourcegraph/issues/5168)\n- Search queries are now interpreted literally by default, rather than as regular expressions. [#5899](https://github.com/sourcegraph/sourcegraph/pull/5899)\n- The `search` GraphQL API field now takes a two new optional parameters: `version` and `patternType`. `version` determines the search syntax version to use, and `patternType` determines the pattern type to use for the query. `version` defaults to \"V1\", which is regular expression searches by default, if not explicitly passed in. `patternType` overrides the pattern type determined by version.\n- Saved searches have been updated to support the new patternType filter. All existing saved searches have been updated to append `patternType:regexp` to the end of queries to ensure deterministic results regardless of the patternType configurations on an instance. All new saved searches are required to have a `patternType:` field in the query.\n- Allow text selection in search result headers (to allow for e.g. copying filenames)", "### Fixed", "- Web app: Fix paths with special characters (#6050)\n- Fixed an issue that rendered the search filter `repohascommitafter` unusable in the presence of an empty repository. [#5149](https://github.com/sourcegraph/sourcegraph/issues/5149)\n- An issue where `externalURL` not being configured in the management console could go unnoticed. [#3899](https://github.com/sourcegraph/sourcegraph/issues/3899)\n- Listing branches and refs now falls back to a fast path if there are a large number of branches. Previously we would time out. [#4581](https://github.com/sourcegraph/sourcegraph/issues/4581)\n- Sourcegraph will now ignore the ambiguous ref HEAD if a repository contains it. [#5291](https://github.com/sourcegraph/sourcegraph/issues/5291)", "### Removed", "## 3.8.2", "### Fixed", "- Sourcegraph cluster deployments now run a more stable syntax highlighting server which can self-recover from rarer failure cases such as getting stuck at high CPU usage when highlighting some specific files. [#5406](https://github.com/sourcegraph/sourcegraph/issues/5406) This will be ported to single-container deployments [at a later date](https://github.com/sourcegraph/sourcegraph/issues/5841).", "## 3.8.1", "### Added", "- Add `nameTransformations` setting to GitLab external service to help transform repository name that shows up in the Sourcegraph UI.", "## 3.8.0", "### Added", "- A toggle button for browser extension to quickly enable/disable the core functionality without actually enable/disable the entire extension in the browser extension manager.\n- Tabs to easily toggle between the different search result types on the search results page.", "### Changed", "- A `hardTTL` setting was added to the [Bitbucket Server `authorization` config](https://docs.sourcegraph.com/admin/external_service/bitbucketserver#configuration). This setting specifies a duration after which a user's cached permissions must be updated before any user action is authorized. This contrasts with the already existing `ttl` setting which defines a duration after which a user's cached permissions will get updated in the background, but the previously cached (and now stale) permissions are used to authorize any user action occuring before the update concludes. If your previous `ttl` value is larger than the default of the new `hardTTL` setting (i.e. **3 days**), you must change the `ttl` to be smaller or, `hardTTL` to be larger.", "### Fixed", "### Removed", "- The `statusIndicator` feature flag has been removed from the site configuration's `experimentalFeatures` section. The status indicator has been enabled by default since 3.6.0 and you can now safely remove the feature flag from your configuration.\n- Public usage is now only available on Sourcegraph.com. Because many core features rely on persisted user settings, anonymous usage leads to a degraded experience for most users. As a result, for self-hosted private instances it is preferable for all users to have accounts. But on sourcegraph.com, users will continue to have to opt-in to accounts, despite the degraded UX.", "## 3.7.2", "### Added", "- A [migration guide for Sourcegraph v3.7+](https://docs.sourcegraph.com/admin/migration/3_7.md).", "### Fixed", "- Fixed an issue where some repositories with very long symbol names would fail to index after v3.7.\n- We now retain one prior search index version after an upgrade, meaning upgrading AND downgrading from v3.6.2 <-> v3.7.2 is now 100% seamless and involves no downtime or negated search performance while repositories reindex. Please refer to the [v3.7+ migration guide](https://docs.sourcegraph.com/admin/migration/3_7.md) for details.", "## 3.7.1", "### Fixed", "- When re-indexing repositories, we now continue to serve from the old index in the meantime. Thus, you can upgrade to 3.7.1 without downtime.\n- Indexed symbol search is now faster, as we've fixed a performance issue that occurred when many repositories without any symbols existed.\n- Indexed symbol search now uses less disk space when upgrading directly to v3.7.1 as we properly remove old indexes.", "## 3.7.0", "### Added", "- Indexed search now supports symbol queries. This feature will require re-indexing all repositories. This will increase the disk and memory usage of indexed search by roughly 10%. You can disable the feature with the configuration `search.index.symbols.enabled`. [#3534](https://github.com/sourcegraph/sourcegraph/issues/3534)\n- Multi-line search now works for non-indexed search. [#4518](https://github.com/sourcegraph/sourcegraph/issues/4518)\n- When using `SITE_CONFIG_FILE` and `EXTSVC_CONFIG_FILE`, you [may now also specify e.g. `SITE_CONFIG_ALLOW_EDITS=true`](https://docs.sourcegraph.com/admin/config/advanced_config_file) to allow edits to be made to the config in the application which will be overwritten on the next process restart. [#4912](https://github.com/sourcegraph/sourcegraph/issues/4912)", "### Changed", "- In the [GitHub external service config](https://docs.sourcegraph.com/admin/external_service/github#configuration) it's now possible to specify `orgs` without specifying `repositoryQuery` or `repos` too.\n- Out-of-the-box TypeScript code intelligence is much better with an updated ctags version with a built-in TypeScript parser.\n- Sourcegraph uses Git protocol version 2 for increased efficiency and performance when fetching data from compatible code hosts.\n- Searches with `repohasfile:` are faster at finding repository matches. [#4833](https://github.com/sourcegraph/sourcegraph/issues/4833).\n- Zoekt now runs with GOGC=50 by default, helping to reduce the memory consumption of Sourcegraph. [#3792](https://github.com/sourcegraph/sourcegraph/issues/3792)\n- Upgraded the version of Go in use, which improves security for publicly accessible Sourcegraph instances.", "### Fixed", "- Disk cleanup in gitserver is now done in terms of percentages to fix [#5059](https://github.com/sourcegraph/sourcegraph/issues/5059).\n- Search results now correctly show highlighting of matches with runes like 'İ' that lowercase to runes with a different number of bytes in UTF-8 [#4791](https://github.com/sourcegraph/sourcegraph/issues/4791).\n- Fixed an issue where search would sometimes crash with a panic due to a nil pointer. [#5246](https://github.com/sourcegraph/sourcegraph/issues/5246)", "### Removed", "## 3.6.2", "### Fixed", "- Fixed Phabricator external services so they won't stop the syncing process for repositories when Phabricator doesn't return clone URLs. [#5101](https://github.com/sourcegraph/sourcegraph/pull/5101)", "## 3.6.1", "### Added", "- New site config option `branding.brandName` configures the brand name to display in the Sourcegraph \\<title\\> element.\n- `repositoryPathPattern` option added to the \"Other\" external service type for repository name customization.", "## 3.6.0", "### Added", "- The `github.exclude` setting in [GitHub external service config](https://docs.sourcegraph.com/admin/external_service/github#configuration) additionally allows you to specify regular expressions with `{\"pattern\": \"regex\"}`.\n- A new [`quicklinks` setting](https://docs.sourcegraph.com/user/personalization/quick_links) allows adding links to be displayed on the homepage and search page for all users (or users in an organization).\n- Compatibility with the [Sourcegraph for Bitbucket Server](https://github.com/sourcegraph/bitbucket-server-plugin) plugin.\n- Support for [Bitbucket Cloud](https://bitbucket.org) as an external service.", "### Changed", "- Updating or creating an external service will no longer block until the service is synced.\n- The GraphQL fields `Repository.createdAt` and `Repository.updatedAt` are deprecated and will be removed in 3.8. Now `createdAt` is always the current time and updatedAt is always null.\n- In the [GitHub external service config](https://docs.sourcegraph.com/admin/external_service/github#configuration) and [Bitbucket Server external service config](https://docs.sourcegraph.com/admin/external_service/bitbucket_server#permissions) `repositoryQuery` is now only required if `repos` is not set.\n- Log messages from query-runner when saved searches fail now include the raw query as part of the message.\n- The status indicator in the navigation bar is now enabled by default\n- Usernames and org names can now contain the `.` character. [#4674](https://github.com/sourcegraph/sourcegraph/issues/4674)", "### Fixed", "- Commit searches now correctly highlight unicode characters, for example 加. [#4512](https://github.com/sourcegraph/sourcegraph/issues/4512)\n- Symbol searches now show the number of symbol matches rather than the number of file matches found. [#4578](https://github.com/sourcegraph/sourcegraph/issues/4578)\n- Symbol searches with truncated results now show a `+` on the results page to signal that some results have been omitted. [#4579](https://github.com/sourcegraph/sourcegraph/issues/4579)", "## 3.5.4", "### Fixed", "- Fixed Phabricator external services so they won't stop the syncing process for repositories when Phabricator doesn't return clone URLs. [#5101](https://github.com/sourcegraph/sourcegraph/pull/5101)", "## 3.5.2", "### Changed", "- Usernames and org names can now contain the `.` character. [#4674](https://github.com/sourcegraph/sourcegraph/issues/4674)", "### Added", "- Syntax highlighting requests that fail are now logged and traced. A new Prometheus metric `src_syntax_highlighting_requests` allows monitoring and alerting. [#4877](https://github.com/sourcegraph/sourcegraph/issues/4877).\n- Sourcegraph's SAML authentication now supports RSA PKCS#1 v1.5. [#4869](https://github.com/sourcegraph/sourcegraph/pull/4869)", "### Fixed", "- Increased nginx proxy buffer size to fix issue where login failed when SAML AuthnRequest was too large. [#4849](https://github.com/sourcegraph/sourcegraph/pull/4849)\n- A regression in 3.3.8 where `\"corsOrigin\": \"*\"` was improperly forbidden. [#4424](https://github.com/sourcegraph/sourcegraph/issues/4424)", "## 3.5.1", "### Added", "- A new [`quicklinks` setting](https://docs.sourcegraph.com/user/personalization/quick_links) allows adding links to be displayed on the homepage and search page for all users (or users in an organization).\n- Site admins can prevent the icon in the top-left corner of the screen from spinning on hovers by setting `\"branding\": { \"disableSymbolSpin\": true }` in their site configuration.", "### Fixed", "- Fix `repository.language` GraphQL field (previously returned empty for most repositories).", "## 3.5.0", "### Added", "- Indexed search now supports matching consecutive literal newlines, with queries like e.g. `foo\\nbar.*` to search over multiple lines. [#4138](https://github.com/sourcegraph/sourcegraph/issues/4138)\n- The `orgs` setting in [GitHub external service config](https://docs.sourcegraph.com/admin/external_service/github) allows admins to select all repositories from the specified organizations to be synced.\n- A new experimental search filter `repohascommitafter:\"30 days ago\"` allows users to exclude stale repositories that don't contain commits (to the branch being searched over) past a specified date from their search query.\n- The `authorization` setting in the [Bitbucket Server external service config](https://docs.sourcegraph.com/admin/external_service/bitbucket_server#permissions) enables Sourcegraph to enforce the repository permissions defined in Bitbucket Server.\n- A new, experimental status indicator in the navigation bar allows admins to quickly see whether the configured repositories are up to date or how many are currently being updated in the background. You can enable the status indicator with the following site configuration: `\"experimentalFeatures\": { \"statusIndicator\": \"enabled\" }`.\n- A new search filter `repohasfile` allows users to filter results to just repositories containing a matching file. For example `ubuntu file:Dockerfile repohasfile:\\.py$` would find Dockerfiles mentioning Ubuntu in repositories that contain Python files. [#4501](https://github.com/sourcegraph/sourcegraph/pull/4501)", "### Changed", "- The saved searches UI has changed. There is now a Saved searches page in the user and organizations settings area. A saved search appears in the settings area of the user or organization it is associated with.", "### Removed", "### Fixed", "- Fixed repository search patterns which contain `.*`. Previously our optimizer would ignore `.*`, which in some cases would lead to our repository search excluding some repositories from the results.\n- Fixed an issue where the Phabricator native integration would be broken on recent Phabricator versions. This fix depends on v1.2 of the [Phabricator extension](https://github.com/sourcegraph/phabricator-extension).\n- Fixed an issue where the \"Empty repository\" banner would be shown on a repository page when starting to clone a repository.\n- Prevent data inconsistency on cached archives due to restarts. [#4366](https://github.com/sourcegraph/sourcegraph/pull/4366)\n- On the /extensions page, the UI is now less ambiguous when an extension has not been activated. [#4446](https://github.com/sourcegraph/sourcegraph/issues/4446)", "## 3.4.5", "### Fixed", "- Fixed an issue where syntax highlighting taking too long would result in errors or wait long amounts of time without properly falling back to plaintext rendering after a few seconds. [#4267](https://github.com/sourcegraph/sourcegraph/issues/4267) [#4268](https://github.com/sourcegraph/sourcegraph/issues/4268) (this fix was intended to be in 3.4.3, but was in fact left out by accident)\n- Fixed an issue with `sourcegraph/server` Docker deployments where syntax highlighting could produce `server closed idle connection` errors. [#4269](https://github.com/sourcegraph/sourcegraph/issues/4269) (this fix was intended to be in 3.4.3, but was in fact left out by accident)\n- Fix `repository.language` GraphQL field (previously returned empty for most repositories).", "## 3.4.4", "### Fixed", "- Fixed an out of bounds error in the GraphQL repository query. [#4426](https://github.com/sourcegraph/sourcegraph/issues/4426)", "## 3.4.3", "### Fixed", "- Improved performance of the /site-admin/repositories page significantly (prevents timeouts). [#4063](https://github.com/sourcegraph/sourcegraph/issues/4063)\n- Fixed an issue where Gitolite repositories would be inaccessible to non-admin users after upgrading to 3.3.0+ from an older version. [#4263](https://github.com/sourcegraph/sourcegraph/issues/4263)\n- Repository names are now treated as case-sensitive, fixing an issue where users saw `pq: duplicate key value violates unique constraint \\\"repo_name_unique\\\"` [#4283](https://github.com/sourcegraph/sourcegraph/issues/4283)\n- Repositories containing submodules not on Sourcegraph will now load without error [#2947](https://github.com/sourcegraph/sourcegraph/issues/2947)\n- HTTP metrics in Prometheus/Grafana now distinguish between different types of GraphQL requests.", "## 3.4.2", "### Fixed", "- Fixed incorrect wording in site-admin onboarding. [#4127](https://github.com/sourcegraph/sourcegraph/issues/4127)", "## 3.4.1", "### Added", "- You may now specify `DISABLE_CONFIG_UPDATES=true` on the management console to prevent updates to the critical configuration. This is useful when loading critical config via a file using `CRITICAL_CONFIG_FILE` on the frontend.", "### Changed", "- When `EXTSVC_CONFIG_FILE` or `SITE_CONFIG_FILE` are specified, updates to external services and the site config are now prevented.\n- Site admins will now see a warning if creating or updating an external service was successful but the process could not complete entirely due to an ephemeral error (such as GitHub API search queries running into timeouts and returning incomplete results).", "### Removed", "### Fixed", "- Fixed an issue where `EXTSVC_CONFIG_FILE` being specified would incorrectly cause a panic.\n- Fixed an issue where user/org/global settings from old Sourcegraph versions (2.x) could incorrectly be null, leading to various errors.\n- Fixed an issue where an ephemeral infrastructure error (`tar/archive: invalid tar header`) would fail a search.", "## 3.4.0", "### Added", "- When `repositoryPathPattern` is configured, paths from the full long name will redirect to the configured name. Extensions will function with the configured name. `repositoryPathPattern` allows administrators to configure \"nice names\". For example `sourcegraph.example.com/github.com/foo/bar` can configured to be `sourcegraph.example.com/gh/foo/bar` with `\"repositoryPathPattern\": \"gh/{nameWithOwner}\"`. (#462)\n- Admins can now turn off site alerts for patch version release updates using the `alerts.showPatchUpdates` setting. Alerts will still be shown for major and minor version updates.\n- The new `gitolite.exclude` setting in [Gitolite external service config](https://docs.sourcegraph.com/admin/external_service/gitolite#configuration) allows you to exclude specific repositories by their Gitolite name so that they won't be mirrored. Upon upgrading, previously \"disabled\" repositories will be automatically migrated to this exclusion list.\n- The new `aws_codecommit.exclude` setting in [AWS CodeCommit external service config](https://docs.sourcegraph.com/admin/external_service/aws_codecommit#configuration) allows you to exclude specific repositories by their AWS name or ID so that they won't be synced. Upon upgrading, previously \"disabled\" repositories will be automatically migrated to this exclusion list.\n- Added a new, _required_ `aws_codecommit.gitCredentials` setting to the [AWS CodeCommit external service config](https://docs.sourcegraph.com/admin/external_service/aws_codecommit#configuration). These Git credentials are required to create long-lived authenticated clone URLs for AWS CodeCommit repositories. For more information about Git credentials, see the AWS CodeCommit documentation: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_ssh-keys.html#git-credentials-code-commit. For detailed instructions on how to create the credentials in IAM, see this page: https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-gc.html\n- Added support for specifying a URL formatted `gitolite.host` setting in [Gitolite external service config](https://docs.sourcegraph.com/admin/external_service/gitolite#configuration) (e.g. `ssh://git@gitolite.example.org:2222/`), in addition to the already supported SCP like format (e.g `git@gitolite.example.org`)\n- Added support for overriding critical, site, and external service configurations via files. Specify `CRITICAL_CONFIG_FILE=critical.json`, `SITE_CONFIG_FILE=site.json`, and/or `EXTSVC_CONFIG_FILE=extsvc.json` on the `frontend` container to do this.", "### Changed", "- Kinds of external services in use are now included in [server pings](https://docs.sourcegraph.com/admin/pings).\n- Bitbucket Server: An actual Bitbucket icon is now used for the jump-to-bitbucket action on repository pages instead of the previously generic icon.\n- Default config for GitHub, GitHub Enterprise, GitLab, Bitbucket Server, and AWS Code Commit external services has been revised to make it easier for first time admins.", "### Removed", "- Fields related to Repository enablement have been deprecated. Mutations are now NOOPs, and for repositories returned the value is always true for Enabled. The enabled field and mutations will be removed in 3.6. Mutations: `setRepositoryEnabled`, `setAllRepositoriesEnabled`, `updateAllMirrorRepositories`, `deleteRepository`. Query parameters: `repositories.enabled`, `repositories.disabled`. Field: `Repository.enabled`.\n- Global saved searches are now deprecated. Any existing global saved searches have been assigned to the Sourcegraph instance's first site admin's user account.\n- The `search.savedQueries` configuration option is now deprecated. Existing entries remain in user and org settings for backward compatibility, but are unused as saved searches are now stored in the database.", "### Fixed", "- Fixed a bug where submitting a saved query without selecting the location would fail for non-site admins (#3628).\n- Fixed settings editors only having a few pixels height.\n- Fixed a bug where browser extension and code review integration usage stats were not being captured on the site-admin Usage Stats page.\n- Fixed an issue where in some rare cases PostgreSQL starting up slowly could incorrectly trigger a panic in the `frontend` service.\n- Fixed an issue where the management console password would incorrectly reset to a new secure one after a user account was created.\n- Fixed a bug where gitserver would leak file descriptors when performing common operations.\n- Substantially improved the performance of updating Bitbucket Server external service configurations on instances with thousands of repositories, going from e.g. several minutes to about a minute for ~20k repositories (#4037).\n- Fully resolved the search performance regression in v3.2.0, restoring performance of search back to the same levels it was before changes made in v3.2.0.\n- Fix a bug where using a repo search filter with the prefix `github.com` only searched for repos whose name starts with `github.com`, even though no `^` was specified in the search filter. (#4103)\n- Fixed an issue where files that fail syntax highlighting would incorrectly render an error instead of gracefully falling back to their plaintext form.", "## 3.3.9", "### Added", "- Syntax highlighting requests that fail are now logged and traced. A new Prometheus metric `src_syntax_highlighting_requests` allows monitoring and alerting. [#4877](https://github.com/sourcegraph/sourcegraph/issues/4877).", "## 3.3.8", "### Fixed", "- Fully resolved the search performance regression in v3.2.0, restoring performance of search back to the same levels it was before changes made in v3.2.0.\n- Fixed an issue where files that fail syntax highlighting would incorrectly render an error instead of gracefully falling back to their plaintext form.\n- Fixed an issue introduced in v3.3 where Sourcegraph would under specific circumstances incorrectly have to re-clone and re-index repositories from Bitbucket Server and AWS CodeCommit.", "## 3.3.7", "### Added", "- The `bitbucketserver.exclude` setting in [Bitbucket Server external service config](https://docs.sourcegraph.com/admin/external_service/bitbucketserver#configuration) additionally allows you to exclude repositories matched by a regular expression (so that they won't be synced).", "### Changed", "### Removed", "### Fixed", "- Fixed a major indexed search performance regression that occurred in v3.2.0. (#3685)\n- Fixed an issue where Sourcegraph would fail to update repositories on some instances (`pq: duplicate key value violates unique constraint \"repo_external_service_unique_idx\"`) (#3680)\n- Fixed an issue where Sourcegraph would not exclude unavailable Bitbucket Server repositories. (#3772)", "## 3.3.6", "## Changed", "- All 24 language extensions are enabled by default.", "## 3.3.5", "## Changed", "- Indexed search is now enabled by default for new Docker deployments. (#3540)", "### Removed", "- Removed smart-casing behavior from search.", "### Fixed", "- Removes corrupted archives in the searcher cache and tries to populate the cache again instead of returning an error.\n- Fixed a bug where search scopes would not get merged, and only the lowest-level list of search scopes would appear.\n- Fixed an issue where repo-updater was slower in performing its work which could sometimes cause other performance issues. https://github.com/sourcegraph/sourcegraph/pull/3633", "## 3.3.4", "### Fixed", "- Fixed bundling of the Phabricator integration assets in the Sourcegraph docker image.", "## 3.3.3", "### Fixed", "- Fixed bug that prevented \"Find references\" action from being completed in the activation checklist.", "## 3.3.2", "### Fixed", "- Fixed an issue where the default `bitbucketserver.repositoryQuery` would not be created on migration from older Sourcegraph versions. https://github.com/sourcegraph/sourcegraph/issues/3591\n- Fixed an issue where Sourcegraph would add deleted repositories to the external service configuration. https://github.com/sourcegraph/sourcegraph/issues/3588\n- Fixed an issue where a repo-updater migration would hit code host rate limits. https://github.com/sourcegraph/sourcegraph/issues/3582\n- The required `bitbucketserver.username` field of a [Bitbucket Server external service configuration](https://docs.sourcegraph.com/admin/external_service/bitbucketserver#configuration), if unset or empty, is automatically migrated to match the user part of the `url` (if defined). https://github.com/sourcegraph/sourcegraph/issues/3592\n- Fixed a panic that would occur in indexed search / the frontend when a search error ocurred. https://github.com/sourcegraph/sourcegraph/issues/3579\n- Fixed an issue where the repo-updater service could become deadlocked while performing a migration. https://github.com/sourcegraph/sourcegraph/issues/3590", "## 3.3.1", "### Fixed", "- Fixed a bug that prevented external service configurations specifying client certificates from working (#3523)", "## 3.3.0", "### Added", "- In search queries, treat `foo(` as `foo\\(` and `bar[` as `bar\\[` rather than failing with an error message.\n- Enterprise admins can now customize the appearance of the homepage and search icon.\n- A new settings property `notices` allows showing custom informational messages on the homepage and at the top of each page. The `motd` property is deprecated and its value is automatically migrated to the new `notices` property.\n- The new `gitlab.exclude` setting in [GitLab external service config](https://docs.sourcegraph.com/admin/external_service/gitlab#configuration) allows you to exclude specific repositories matched by `gitlab.projectQuery` and `gitlab.projects` (so that they won't be synced). Upon upgrading, previously \"disabled\" repositories will be automatically migrated to this exclusion list.\n- The new `gitlab.projects` setting in [GitLab external service config](https://docs.sourcegraph.com/admin/external_service/gitlab#configuration) allows you to select specific repositories to be synced.\n- The new `bitbucketserver.exclude` setting in [Bitbucket Server external service config](https://docs.sourcegraph.com/admin/external_service/bitbucketserver#configuration) allows you to exclude specific repositories matched by `bitbucketserver.repositoryQuery` and `bitbucketserver.repos` (so that they won't be synced). Upon upgrading, previously \"disabled\" repositories will be automatically migrated to this exclusion list.\n- The new `bitbucketserver.repos` setting in [Bitbucket Server external service config](https://docs.sourcegraph.com/admin/external_service/bitbucketserver#configuration) allows you to select specific repositories to be synced.\n- The new required `bitbucketserver.repositoryQuery` setting in [Bitbucket Server external service configuration](https://docs.sourcegraph.com/admin/external_service/bitbucketserver#configuration) allows you to use Bitbucket API repository search queries to select repos to be synced. Existing configurations will be migrate to have it set to `[\"?visibility=public\", \"?visibility=private\"]` which is equivalent to the previous implicit behaviour that this setting supersedes.\n- \"Quick configure\" buttons for common actions have been added to the config editor for all external services.\n- \"Quick configure\" buttons for common actions have been added to the management console.\n- Site-admins now receive an alert every day for the seven days before their license key expires.\n- The user menu (in global nav) now lists the user's organizations.\n- All users on an instance now see a non-dismissable alert when when there's no license key in use and the limit of free user accounts is exceeded.\n- All users will see a dismissible warning about limited search performance and accuracy on when using the sourcegraph/server Docker image with more than 100 repositories enabled.", "### Changed", "- Indexed searches that time out more consistently report a timeout instead of erroneously saying \"No results.\"\n- The symbols sidebar now only shows symbols defined in the current file or directory.\n- The dynamic filters on search results pages will now display `lang:` instead of `file:` filters for language/file-extension filter suggestions.\n- The default `github.repositoryQuery` of a [GitHub external service configuration](https://docs.sourcegraph.com/admin/external_service/github#configuration) has been changed to `[\"none\"]`. Existing configurations that had this field unset will be migrated to have the previous default explicitly set (`[\"affiliated\", \"public\"]`).\n- The default `gitlab.projectQuery` of a [GitLab external service configuration](https://docs.sourcegraph.com/admin/external_service/gitlab#configuration) has been changed to `[\"none\"]`. Existing configurations that had this field unset will be migrated to have the previous default explicitly set (`[\"?membership=true\"]`).\n- The default value of `maxReposToSearch` is now unlimited (was 500).\n- The default `github.repositoryQuery` of a [GitHub external service configuration](https://docs.sourcegraph.com/admin/external_service/github#configuration) has been changed to `[\"none\"]` and is now a required field. Existing configurations that had this field unset will be migrated to have the previous default explicitly set (`[\"affiliated\", \"public\"]`).\n- The default `gitlab.projectQuery` of a [GitLab external service configuration](https://docs.sourcegraph.com/admin/external_service/gitlab#configuration) has been changed to `[\"none\"]` and is now a required field. Existing configurations that had this field unset will be migrated to have the previous default explicitly set (`[\"?membership=true\"]`).\n- The `bitbucketserver.username` field of a [Bitbucket Server external service configuration](https://docs.sourcegraph.com/admin/external_service/bitbucketserver#configuration) is now **required**. This field is necessary to authenticate with the Bitbucket Server API with either `password` or `token`.\n- The settings and account pages for users and organizations are now combined into a single tab.", "### Removed", "- Removed the option to show saved searches on the Sourcegraph homepage.", "### Fixed", "- Fixed an issue where the site-admin repositories page `Cloning`, `Not Cloned`, `Needs Index` tabs were very slow on instances with thousands of repositories.\n- Fixed an issue where failing to syntax highlight a single file would take down the entire syntax highlighting service.", "## 3.2.6", "### Fixed", "- Fully resolved the search performance regression in v3.2.0, restoring performance of search back to the same levels it was before changes made in v3.2.0.", "## 3.2.5", "### Fixed", "- Fixed a major indexed search performance regression that occurred in v3.2.0. (#3685)", "## 3.2.4", "### Fixed", "- Fixed bundling of the Phabricator integration assets in the Sourcegraph docker image.", "## 3.2.3", "### Fixed", "- Fixed https://github.com/sourcegraph/sourcegraph/issues/3336.\n- Clearer error message when a repository sync fails due to the inability to clone a repository.\n- Rewrite '@' character in Gitolite repository names to '-', which permits them to be viewable in the UI.", "## 3.2.2", "### Changed", "- When using an external Zoekt instance (specified via the `ZOEKT_HOST` environment variable), sourcegraph/server no longer spins up a redundant internal Zoekt instance.", "## 3.2.1", "### Fixed", "- Jaeger tracing, once enabled, can now be configured via standard [environment variables](https://github.com/jaegertracing/jaeger-client-go/blob/v2.14.0/README.md#environment-variables).\n- Fixed an issue where some search and zoekt errors would not be logged.", "## 3.2.0", "### Added", "- Sourcegraph can now automatically use the system's theme.\n To enable, open the user menu in the top right and make sure the theme dropdown is set to \"System\".\n This is currently supported on macOS Mojave with Safari Technology Preview 68 and later.\n- The `github.exclude` setting was added to the [GitHub external service config](https://docs.sourcegraph.com/admin/external_service/github#configuration) to allow excluding repositories yielded by `github.repos` or `github.repositoryQuery` from being synced.", "### Changed", "- Symbols search is much faster now. After the initial indexing, you can expect code intelligence to be nearly instant no matter the size of your repository.\n- Massively reduced the number of code host API requests Sourcegraph performs, which caused rate limiting issues such as slow search result loading to appear.\n- The [`corsOrigin`](https://docs.sourcegraph.com/admin/config/site_config) site config property is no longer needed for integration with GitHub, GitLab, etc., via the [Sourcegraph browser extension](https://docs.sourcegraph.com/integration/browser_extension). Only the [Phabricator extension](https://github.com/sourcegraph/phabricator-extension) requires it.", "### Fixed", "- Fixed a bug where adding a search scope that adds a `repogroup` filter would cause invalid queries if `repogroup:sample` was already part of the query.\n- An issue where errors during displaying search results would not be displayed.", "### Removed", "- The `\"updateScheduler2\"` experiment is now the default and it's no longer possible to configure.", "## 3.1.2", "### Added", "- The `search.contextLines` setting was added to allow configuration of the number of lines of context to be displayed around search results.", "### Changed", "- Massively reduced the number of code host API requests Sourcegraph performs, which caused rate limiting issues such as slow search result loading to appear.\n- Improved logging in various situations where Sourcegraph would potentially hit code host API rate limits.", "### Fixed", "- Fixed an issue where search results loading slowly would display a `Cannot read property \"lastChild\" of undefined` error.", "## 3.1.1", "### Added", "- Query builder toggle (open/closed) state is now retained.", "### Fixed", "- Fixed an issue where single-term values entered into the \"Exact match\" field in the query builder were not getting wrapped in quotes.", "## 3.1.0", "### Added", "- Added Docker-specific help text when running the Sourcegraph docker image in an environment with an sufficient open file descriptor limit.\n- Added syntax highlighting for Kotlin and Dart.\n- Added a management console environment variable to disable HTTPS, see [the docs](https://docs.sourcegraph.com/admin/management_console.md#can-i-disable-https-on-the-management-console) for more information.\n- Added `auth.disableUsernameChanges` to critical configuration to prevent users from changing their usernames.\n- Site admins can query a user by email address or username from the GraphQL API.\n- Added a search query builder to the main search page. Click \"Use search query builder\" to open the query builder, which is a form with separate inputs for commonly used search keywords.", "### Changed", "- File match search results now show full repository name if there are results from mirrors on different code hosts (e.g. github.com/sourcegraph/sourcegraph and gitlab.com/sourcegraph/sourcegraph)\n- Search queries now use \"smart case\" by default. Searches are case insensitive unless you use uppercase letters. To explicitly set the case, you can still use the `case` field (e.g. `case:yes`, `case:no`). To explicitly set smart case, use `case:auto`.", "### Fixed", "- Fixed an issue where the management console would improperly regenerate the TLS cert/key unless `CUSTOM_TLS=true` was set. See the documentation for [how to use your own TLS certificate with the management console](https://docs.sourcegraph.com/admin/management_console.md#how-can-i-use-my-own-tls-certificates-with-the-management-console).", "## 3.0.1", "### Added", "- Symbol search now supports Elixir, Haskell, Kotlin, Scala, and Swift", "### Changed", "- Significantly optimized how file search suggestions are provided when using indexed search (cluster deployments).\n- Both the `sourcegraph/server` image and the [Kubernetes deployment](https://github.com/sourcegraph/deploy-sourcegraph) manifests ship with Postgres `11.1`. For maximum compatibility, however, the minimum supported version remains `9.6`. The upgrade procedure is mostly automated for existing deployments. Please refer to [this page](https://docs.sourcegraph.com/admin/postgres) for detailed instructions.", "### Removed", "- The deprecated `auth.disableAccessTokens` site config property was removed. Use `auth.accessTokens` instead.\n- The `disableBrowserExtension` site config property was removed. [Configure nginx](https://docs.sourcegraph.com/admin/nginx) instead to block clients (if needed).", "## 3.0.0", "See the changelog entries for 3.0.0 beta releases and our [3.0](https://docs.sourcegraph.com/admin/migration/3_0.md) upgrade guide if you are upgrading from 2.x.", "## 3.0.0-beta.4", "### Added", "- Basic code intelligence for the top 10 programming languages works out of the box without any configuration. [TypeScript/JavaScript](https://sourcegraph.com/extensions/sourcegraph/typescript), [Python](https://sourcegraph.com/extensions/sourcegraph/python), [Java](https://sourcegraph.com/extensions/sourcegraph/java), [Go](https://sourcegraph.com/extensions/sourcegraph/go), [C/C++](https://sourcegraph.com/extensions/sourcegraph/cpp), [Ruby](https://sourcegraph.com/extensions/sourcegraph/ruby), [PHP](https://sourcegraph.com/extensions/sourcegraph/php), [C#](https://sourcegraph.com/extensions/sourcegraph/csharp), [Shell](https://sourcegraph.com/extensions/sourcegraph/shell), and [Scala](https://sourcegraph.com/extensions/sourcegraph/scala) are enabled by default, and you can find more in the [extension registry](https://sourcegraph.com/extensions?query=category%3A\"Programming+languages\").", "## 3.0.0-beta.3", "- Fixed an issue where the site admin is redirected to the start page instead of being redirected to the repositories overview page after deleting a repo.", "## 3.0.0-beta", "### Added", "- Repositories can now be queried by a git clone URL through the GraphQL API.\n- A new Explore area is linked from the top navigation bar (when the `localStorage.explore=true;location.reload()` feature flag is enabled).\n- Authentication via GitHub is now supported. To enable, add an item to the `auth.providers` list with `type: \"github\"`. By default, GitHub identities must be linked to an existing Sourcegraph user account. To enable new account creation via GitHub, use the `allowSignup` option in the `GitHubConnection` config.\n- Authentication via GitLab is now supported. To enable, add an item to the `auth.providers` list with `type: \"gitlab\"`.\n- GitHub repository permissions are supported if authentication via GitHub is enabled. See the\n documentation for the `authorization` field of the `GitHubConnection` configuration.\n- The repository settings mirroring page now shows when a repo is next scheduled for an update (requires experiment `\"updateScheduler2\": \"enabled\"`).\n- Configured repositories are periodically scheduled for updates using a new algorithm. You can disable the new algorithm with the following site configuration: `\"experimentalFeatures\": { \"updateScheduler2\": \"disabled\" }`. If you do so, please file a public issue to describe why you needed to disable it.\n- When using HTTP header authentication, [`stripUsernameHeaderPrefix`](https://docs.sourcegraph.com/admin/auth/#username-header-prefixes) field lets an admin specify a prefix to strip from the HTTP auth header when converting the header value to a username.\n- Sourcegraph extensions whose package.json contains `\"wip\": true` are considered [work-in-progress extensions](https://docs.sourcegraph.com/extensions/authoring/publishing#wip-extensions) and are indicated as such to avoid users accidentally using them.\n- Information about user survey submissions and a chart showing weekly active users is now displayed on the site admin Overview page.\n- A new GraphQL API field `UserEmail.isPrimary` was added that indicates whether an email is the user's primary email.\n- The filters bar in the search results page can now display filters from extensions.\n- Extensions' `activate` functions now receive a `sourcegraph.ExtensionContext` parameter (i.e., `export function activate(ctx: sourcegraph.ExtensionContext): void { ... }`) to support deactivation and running multiple extensions in the same process.\n- Users can now request an Enterprise trial license from the site init page.\n- When searching, a filter button `case:yes` will now appear when relevant. This helps discovery and makes it easier to use our case-sensitive search syntax.\n- Extensions can now report progress in the UI through the `withProgress()` extension API.\n- When calling `editor.setDecorations()`, extensions must now provide an instance of `TextDocumentDecorationType` as first argument. This helps gracefully displaying decorations from several extensions.", "### Changed", "- The Postgres database backing Sourcegraph has been upgraded from 9.4 to 11.1. Existing Sourcegraph users must conduct an [upgrade procedure](https://docs.sourcegraph.com/admin/postgres_upgrade)\n- Code host configuration has moved out of the site config JSON into the \"External services\" area of the site admin web UI. Sourcegraph instances will automatically perform a one time migration of existing data in the site config JSON. After the migration these keys can be safely deleted from the site config JSON: `awsCodeCommit`, `bitbucketServer`, `github`, `gitlab`, `gitolite`, and `phabricator`.\n- Site and user usage statistics are now visible to all users. Previously only site admins (and users, for their own usage statistics) could view this information. The information consists of aggregate counts of actions such as searches, page views, etc.\n- The Git blame information shown at the end of a line is now provided by the [Git extras extension](https://sourcegraph.com/extensions/sourcegraph/git-extras). You must add that extension to continue using this feature.\n- The `appURL` site configuration option was renamed to `externalURL`.\n- The repository and directory pages now show all entries together instead of showing files and (sub)directories separately.\n- Extensions no longer can specify titles (in the `title` property in the `package.json` extension manifest). Their extension ID (such as `alice/myextension`) is used.", "### Fixed", "- Fixed an issue where the site admin License page showed a count of current users, rather than the max number of users over the life of the license.\n- Fixed number formatting issues on site admin Overview and Survey Response pages.\n- Fixed resolving of git clone URLs with `git+` prefix through the GraphQL API\n- Fixed an issue where the graphql Repositories endpoint would order by a field which was not indexed. Times on Sourcegraph.com went from 10s to 200ms.\n- Fixed an issue where whitespace was not handled properly in environment variable lists (`SYMBOLS_URL`, `SEARCHER_URL`).\n- Fixed an issue where clicking inside the repository popover or clicking \"Show more\" would dismiss the popover.", "### Removed", "- The `siteID` site configuration option was removed because it is no longer needed. If you previously specified this in site configuration, a new, random site ID will be generated upon server startup. You can safely remove the existing `siteID` value from your site configuration after upgrading.\n- The **Info** panel was removed. The information it presented can be viewed in the hover.\n- The top-level `repos.list` site configuration was removed in favour of each code-host's equivalent options,\n now configured via the new _External Services UI_ available at `/site-admin/external-services`. Equivalent options in code hosts configuration:\n - GitHub via [`github.repos`](https://docs.sourcegraph.com/admin/site_config/all#repos-array)\n - Gitlab via [`gitlab.projectQuery`](https://docs.sourcegraph.com/admin/site_config/all#projectquery-array)\n - Phabricator via [`phabricator.repos`](https://docs.sourcegraph.com/admin/site_config/all#phabricator-array)\n - [Other external services](https://docs.sourcegraph.com/admin/repo/add_from_other_external_services)\n- Removed the `httpStrictTransportSecurity` site configuration option. Use [nginx configuration](https://docs.sourcegraph.com/admin/nginx) for this instead.\n- Removed the `tls.letsencrypt` site configuration option. Use [nginx configuration](https://docs.sourcegraph.com/admin/nginx) for this instead.\n- Removed the `tls.cert` and `tls.key` site configuration options. Use [nginx configuration](https://docs.sourcegraph.com/admin/nginx) for this instead.\n- Removed the `httpToHttpsRedirect` and `experimentalFeatures.canonicalURLRedireect` site configuration options. Use [nginx configuration](https://docs.sourcegraph.com/admin/nginx) for these instead.\n- Sourcegraph no longer requires access to `/var/run/docker.sock`.", "## 2.13.6", "### Added", "- The `/-/editor` endpoint now accepts a `hostname_patterns` URL parameter, which specifies a JSON\n object mapping from hostname to repository name pattern. This serves as a hint to Sourcegraph when\n resolving git clone URLs to repository names. The name pattern is the same style as is used in\n code host configurations. The default value is `{hostname}/{path}`.", "## 2.13.5", "### Fixed", "- Fixed another issue where Sourcegraph would try to fetch more than the allowed number of repositories from AWS CodeCommit.", "## 2.13.4", "### Changed", "- The default for `experimentalFeatures.canonicalURLRedirect` in site config was changed back to `disabled` (to avoid [#807](https://github.com/sourcegraph/sourcegraph/issues/807)).", "## 2.13.3", "### Fixed", "- Fixed an issue that would cause the frontend health check endpoint `/healthz` to not respond. This only impacts Kubernetes deployments.\n- Fixed a CORS policy issue that caused requests to be rejected when they come from origins not in our [manifest.json](https://sourcegraph.com/github.com/sourcegraph/sourcegraph/-/blob/browser/src/extension/manifest.spec.json#L72) (i.e. requested via optional permissions by the user).\n- Fixed an issue that prevented `repositoryQuery` from working correctly on GitHub enterprise instances.", "## 2.13.2", "### Fixed", "- Fixed an issue where Sourcegraph would try to fetch more than the allowed number of repositories from AWS CodeCommit.", "## 2.13.1", "### Changed", "- The timeout when running `git ls-remote` to determine if a remote url is cloneable has been increased from 5s to 30s.\n- Git commands now use [version 2 of the Git wire protocol](https://opensource.googleblog.com/2018/05/introducing-git-protocol-version-2.html), which should speed up certain operations (e.g. `git ls-remote`, `git fetch`) when communicating with a v2 enabled server.", "## 2.13.0", "### Added", "- A new site config option `search.index.enabled` allows toggling on indexed search.\n- Search now uses [Sourcegraph extensions](https://docs.sourcegraph.com/extensions) that register `queryTransformer`s.\n- GitLab repository permissions are now supported. To enable this, you will need to set the `authz`\n field in the `GitLabConnection` configuration object and ensure that the access token set in the\n `token` field has both `sudo` and `api` scope.", "### Changed", "- When the `DEPLOY_TYPE` environment variable is incorrectly specified, Sourcegraph now shuts down and logs an error message.\n- The `experimentalFeatures.canonicalURLRedirect` site config property now defaults to `enabled`. Set it to `disabled` to disable redirection to the `appURL` from other hosts.\n- Updating `maxReposToSearch` site config no longer requires a server restart to take effect.\n- The update check page no longer shows an error if you are using an insiders build. Insiders builds will now notify site administrators that updates are available 40 days after the release date of the installed build.\n- The `github.repositoryQuery` site config property now accepts arbitrary GitHub repository searches.", "### Fixed", "- The user account sidebar \"Password\" link (to the change-password form) is now shown correctly.\n- Fixed an issue where GitHub rate limits were underutilized if the remaining\n rate limit dropped below 150.\n- Fixed an issue where GraphQL field `elapsedMilliseconds` returned invalid value on empty searches\n- Editor extensions now properly search the selection as a literal string, instead of incorrectly using regexp.\n- Fixed a bug where editing and deleting global saved searches was not possible.\n- In index search, if the search regex produces multiline matches, search results are still processed per line and highlighted correctly.\n- Go-To-GitHub and Go-To-GitLab buttons now link to the right branch, line and commit range.\n- Go-to-GitHub button links to default branch when no rev is given.\n- The close button in the panel header stays located on the top.\n- The Phabricator icon is now displayed correctly.\n- The view mode button in the BlobPage now shows the correct view mode to switch to.", "### Removed", "- The experimental feature flag to disable the new repo update scheduler has been removed.\n- The `experimentalFeatures.configVars` feature flag was removed.\n- The `experimentalFeatures.multipleAuthProviders` feature flag was removed because the feature is now always enabled.\n- The following deprecated auth provider configuration properties were removed: `auth.provider`, `auth.saml`, `auth.openIDConnect`, `auth.userIdentityHTTPHeader`, and `auth.allowSignup`. Use `auth.providers` for all auth provider configuration. (If you were still using the deprecated properties and had no `auth.providers` set, all access to your instance will be rejected until you manually set `auth.providers`.)\n- The deprecated site configuration properties `search.scopes` and `settings` were removed. Define search scopes and settings in global settings in the site admin area instead of in site configuration.\n- The `pendingContents` property has been removed from our GraphQL schema.\n- The **Explore** page was replaced with a **Repositories** search link in the top navigation bar.", "## 2.12.3", "### Fixed", "- Fixed an error that prevented users without emails from submitting satisfaction surveys.", "## 2.12.2", "### Fixed", "- Fixed an issue where private GitHub Enterprise repositories were not fetched.", "## 2.12.1", "### Fixed", "- We use GitHub's REST API to query affliated repositories. This API has wider support on older GitHub enterprise versions.\n- Fixed an issue that prevented users without email addresses from signing in (https://github.com/sourcegraph/sourcegraph/issues/426).", "## 2.12.0", "### Changed", "- Reduced the size of in-memory data structured used for storing search results. This should reduce the backend memory usage of large result sets.\n- Code intelligence is now provided by [Sourcegraph extensions](https://docs.sourcegraph.com/extensions). The extension for each language in the site configuration `langservers` property is automatically enabled.\n- Support for multiple authentication providers is now enabled by default. To disable it, set the `experimentalFeatures.multipleAuthProviders` site config option to `\"disabled\"`. This only applies to Sourcegraph Enterprise.\n- When using the `http-header` auth provider, valid auth cookies (from other auth providers that are currently configured or were previously configured) are now respected and will be used for authentication. These auth cookies also take precedence over the `http-header` auth. Previously, the `http-header` auth took precedence.\n- Bitbucket Server username configuration is now used to clone repositories if the Bitbucket Server API does not set a username.\n- Code discussions: On Sourcegraph.com / when `discussions.abuseProtection` is enabled in the site config, rate limits to thread creation, comment creation, and @mentions are now applied.", "### Added", "- Search syntax for filtering archived repositories. `archived:no` will exclude archived repositories from search results, `archived:only` will search over archived repositories only. This applies for GitHub and GitLab repositories.\n- A Bitbucket Server option to exclude personal repositories in the event that you decide to give an admin-level Bitbucket access token to Sourcegraph and do not want to create a bot account. See https://docs.sourcegraph.com/integration/bitbucket_server#excluding-personal-repositories for more information.\n- Site admins can now see when users of their Sourcegraph instance last used it via a code host integration (e.g. Sourcegraph browser extensions). Visit the site admin Analytics page (e.g. https://sourcegraph.example.com/site-admin/analytics) to view this information.\n- A new site config option `extensions.allowRemoteExtensions` lets you explicitly specify the remote extensions (from, e.g., Sourcegraph.com) that are allowed.\n- Pings now include a total count of user accounts.", "### Fixed", "- Files with the gitattribute `export-ignore` are no longer excluded for language analysis and search.\n- \"Discard changes?\" confirmation popup doesn't pop up every single time you try to navigate to a new page after editting something in the site settings page anymore.\n- Fixed an issue where Git repository URLs would sometimes be logged, potentially containing e.g. basic auth tokens.\n- Fixed date formatting on the site admin Analytics page.\n- File names of binary and large files are included in search results.", "### Removed", "- The deprecated environment variables `SRC_SESSION_STORE_REDIS` and `REDIS_MASTER_ENDPOINT` are no longer used to configure alternative redis endpoints. For more information, see \"[using external services with Sourcegraph](https://docs.sourcegraph.com/admin/external_services)\".", "## 2.11.1", "### Added", "- A new site config option `git.cloneURLToRepositoryName` specifies manual mapping from Git clone URLs to Sourcegraph repository names. This is useful, for example, for Git submodules that have local clone URLs.", "### Fixed", "- Slack notifications for saved searches have been fixed.", "## 2.11.0", "### Changed", "### Added", "- Support for ACME \"tls-alpn-01\" challenges to obtain LetsEncrypt certificates. Previously Sourcegraph only supported ACME \"http-01\" challenges which required port 80 to be accessible.\n- gitserver periodically removes stale lock files that git can leave behind.\n- Commits with empty trees no longer return 404.\n- Clients (browser/editor extensions) can now query configuration details from the `ClientConfiguration` GraphQL API.\n- The config field `auth.accessTokens.allow` allows or restricts use of access tokens. It can be set to one of three values: \"all-users-create\" (the default), \"none\" (all access tokens are disabled), and \"site-admin-create\" (access tokens are enabled, but only site admins can create new access tokens). The field `auth.disableAccessTokens` is now deprecated in favor of this new field.\n- A webhook endpoint now exists to trigger repository updates. For example, `curl -XPOST -H 'Authorization: token $ACCESS_TOKEN' $SOURCEGRAPH_ORIGIN/.api/repos/$REPO_URI/-/refresh`.\n- Git submodules entries in the file tree now link to the submodule repository.", "### Fixed", "- An issue / edge case where the Code Intelligence management admin page would incorrectly show language servers as `Running` when they had been removed from Docker.\n- Log level is respected in lsp-proxy logs.\n- Fixed an error where text searches could be routed to a faulty search worker.\n- Gitolite integration should correctly detect names which Gitolite would consider to be patterns, and not treat them as repositories.\n- repo-updater backs off fetches on a repo that's failing to fetch.\n- Attempts to add a repo with an empty string for the name are checked for and ignored.\n- Fixed an issue where non-site-admin authenticated users could modify global settings (not site configuration), other organizations' settings, and other users' settings.\n- Search results are rendered more eagerly, resulting in fewer blank file previews\n- An issue where automatic code intelligence would fail to connect to the underlying `lsp` network, leading to `dial tcp: lookup lang on 0.0.0.0:53: no such host` errors.\n- More useful error messages from lsp-proxy when a language server can't get a requested revision of a repository.\n- Creation of a new user with the same name as an existing organization (and vice versa) is prevented.", "### Removed", "## 2.10.5", "### Fixed", "- Slack notifications for saved searches have been fixed.", "## 2.10.4", "### Fixed", "- Fixed an issue that caused the frontend to return a HTTP 500 and log an error message like:\n ```\n lvl=eror msg=\"ui HTTP handler error response\" method=GET status_code=500 error=\"Post http://127.0.0.1:3182/repo-lookup: context canceled\"\n ```", "## 2.10.3", "### Fixed", "- The SAML AuthnRequest signature when using HTTP redirect binding is now computed using a URL query string with correct ordering of parameters. Previously, the ordering was incorrect and caused errors when the IdP was configured to check the signature in the AuthnRequest.", "## 2.10.2", "### Fixed", "- SAML IdP-initiated login previously failed with the IdP set a RelayState value. This now works.", "## 2.10.1", "### Changed", "- Most `experimentalFeatures` in the site configuration now respond to configuration changes live, without requiring a server restart. As usual, you will be prompted for a restart after saving your configuration changes if one is required.\n- Gravatar image avatars are no longer displayed for committers.", "## 2.10.0", "### Changed", "- In the file tree, if a directory that contains only a single directory is expanded, its child directory is now expanded automatically.", "### Fixed", "- Fixed an issue where `sourcegraph/server` would not start code intelligence containers properly when the `sourcegraph/server` container was shut down non-gracefully.\n- Fixed an issue where the file tree would return an error when navigating between repositories.", "## 2.9.4", "### Changed", "- Repo-updater has a new and improved scheduler for periodic repo fetches. If you have problems with it, you can revert to the old behavior by adding `\"experimentalFeatures\": { \"updateScheduler\": \"disabled\" }` to your `config.json`.\n- A once-off migration will run changing the layout of cloned repos on disk. This should only affect installations created January 2018 or before. There should be no user visible changes.\n- Experimental feature flag \"updateScheduler\" enables a smarter and less spammy algorithm for automatic repository updates.\n- It is no longer possible to disable code intelligence by unsetting the LSP_PROXY environment variable. Instead, code intelligence can be disabled per language on the site admin page (e.g. https://sourcegraph.example.com/site-admin/code-intelligence).\n- Bitbucket API requests made by Sourcegraph are now under a self-enforced API rate limit (since Bitbucket Server does not have a concept of rate limiting yet). This will reduce any chance of Sourcegraph slowing down or causing trouble for Bitbucket Server instances connected to it. The limits are: 7,200 total requests/hr, with a bucket size / maximum burst size of 500 requests.\n- Global, org, and user settings are now validated against the schema, so invalid settings will be shown in the settings editor with a red squiggly line.\n- The `http-header` auth provider now supports being used with other auth providers (still only when `experimentalFeatures.multipleAuthProviders` is `true`).\n- Periodic fetches of Gitolite-hosted repositories are now handled internally by repo-updater.", "### Added", "- The `log.sentry.dsn` field in the site config makes Sourcegraph log application errors to a Sentry instance.\n- Two new repository page hotkeys were added: <kbd>r</kbd> to open the repositories menu and <kbd>v</kbd> to open the revision selector.\n- Repositories are periodically (~45 days) recloned from the codehost. The codehost can be relied on to give an efficient packing. This is an alternative to running a memory and CPU intensive git gc and git prune.\n- The `auth.sessionExpiry` field sets the session expiration age in seconds (defaults to 90 days).", "### Fixed", "- Fixed a bug in the API console that caused it to display as a blank page in some cases.\n- Fixed cases where GitHub rate limit wasn't being respected.\n- Fixed a bug where scrolling in references, history, etc. file panels was not possible in Firefox.\n- Fixed cases where gitserver directory structure migration could fail/crash.\n- Fixed \"Generate access token\" link on user settings page. Previously, this link would 404.\n- Fixed a bug where the search query was not updated in the search bar when searching from the homepage.\n- Fixed a possible crash in github-proxy.\n- Fixed a bug where file matching for diff search was case sensitive by default.", "### Removed", "- `SOURCEGRAPH_CONFIG` environment variable has been removed. Site configuration is always read from and written to disk. You can configure the location by providing `SOURCEGRAPH_CONFIG_FILE`. The default path is `/etc/sourcegraph/config.json`.", "## 2.9.3", "### Changed", "- The search results page will merge duplicated lines of context.\n- The following deprecated site configuration properties have been removed: `github[].preemptivelyClone`, `gitOriginMap`, `phabricatorURL`, `githubPersonalAccessToken`, `githubEnterpriseURL`, `githubEnterpriseCert`, and `githubEnterpriseAccessToken`.\n- The `settings` field in the site config file is deprecated and will not be supported in a future release. Site admins should move those settings (if any) to global settings (in the site admin UI). Global settings are preferred to site config file settings because the former can be applied without needing to restart/redeploy the Sourcegraph server or cluster.", "### Fixed", "- Fixed a goroutine leak which occurs when search requests are canceled.\n- Console output should have fewer spurious line breaks.\n- Fixed an issue where it was not possible to override the `StrictHostKeyChecking` SSH option in the SSH configuration.\n- Cross-repository code intelligence indexing for non-Go languages is now working again (originally broken in 2.9.2).", "## 2.9.1", "### Fixed", "- Fixed an issue where saving an organization's configuration would hang indefinitely.", "## 2.9.0", "### Changed", "- Hover tooltips were rewritten to fix a couple of issues and are now much more robust, received a new design and show more information.\n- The `max:` search flag was renamed to `count:` in 2.8.8, but for backward compatibility `max:` has been added back as a deprecated alias for `count:`.\n- Drastically improved the performance / load time of the Code Intelligence site admin page.", "### Added", "- The site admin code intelligence page now displays an error or reason whenever language servers are unable to be managed from the UI or Sourcegraph API.\n- The ability to directly specify the root import path of a repository via `.sourcegraph/config.json` in the repo root, instead of relying on the heuristics of the Go language server to detect it.", "### Fixed", "- Configuring Bitbucket Server now correctly suppresses the the toast message \"Configure repositories and code hosts to add to Sourcegraph.\"\n- A bug where canonical import path comments would not be detected by the Go language server's heuristics under `cmd/` folders.\n- Fixed an issue where a repository would only be refreshed on demand by certain user actions (such as a page reload) and would otherwise not be updated when expected.\n- If a code host returned a repository-not-found or unauthorized error (to `repo-updater`) for a repository that previously was known to Sourcegraph, then in some cases a misleading \"Empty repository\" screen was shown. Now the repository is displayed as though it still existed, using cached data; site admins must explicitly delete repositories on Sourcegraph after they have been deleted on the code host.\n- Improved handling of GitHub API rate limit exhaustion cases. Cached repository metadata and Git data will be used to provide full functionality during this time, and log messages are more informative. Previously, in some cases, repositories would become inaccessible.\n- Fixed an issue where indexed search would sometimes not indicate that there were more results to show for a given file.\n- Fixed an issue where the code intelligence admin page would never finish loading language servers.", "## 2.9.0-pre0", "### Changed", "- Search scopes have been consolidated into the \"Filters\" bar on the search results page.\n- Usernames and organization names of up to 255 characters are allowed. Previously the max length was 38.", "### Fixed", "- The target commit ID of a Git tag object (i.e., not lightweight Git tag refs) is now dereferenced correctly. Previously the tag object's OID was given.\n- Fixed an issue where AWS Code Commit would hit the rate limit.\n- Fixed an issue where dismissing the search suggestions dropdown did not unfocus previously highlighted suggestions.\n- Fixed an issue where search suggestions would appear twice.\n- Indexed searches now return partial results if they timeout.\n- Git repositories with files whose paths contain `.git` path components are now usable (via indexed and non-indexed search and code intelligence). These corrupt repositories are rare and generally were created by converting some other VCS repository to Git (the Git CLI will forbid creation of such paths).\n- Various diff search performance improvements and bug fixes.\n- New Phabricator extension versions would used cached stylesheets instead of the upgraded version.\n- Fixed an issue where hovers would show an error for Rust and C/C++ files.", "### Added", "- The `sourcegraph/server` container now emits the most recent log message when redis terminates to make it easier to debug why redis stopped.\n- Organization invites (which allow users to invite other users to join organizations) are significantly improved. A new accept-invitation page was added.\n- The new help popover allows users to easily file issues in the Sourcegraph public issue tracker and view documentation.\n- An issue where Java files would be highlighted incorrectly if they contained JavaDoc blocks with an uneven number of opening/closing `*`s.", "### Removed", "- The `secretKey` site configuration value is no longer needed. It was only used for generating tokens for inviting a user to an organization. The invitation is now stored in the database associated with the recipient, so a secret token is no longer needed.\n- The `experimentalFeatures.searchTimeoutParameter` site configuration value has been removed. It defaulted to `enabled` in 2.8 and it is no longer possible to disable.", "### Added", "- Syntax highlighting for:\n - TOML files (including Go `Gopkg.lock` and Rust `Cargo.lock` files).\n - Rust files.\n - GraphQL files.\n - Protobuf files.\n - `.editorconfig` files.", "## 2.8.9", "### Changed", "- The \"invite user\" site admin page was moved to a sub-page of the users page (`/site-admin/users/new`).\n- It is now possible for a site admin to create a new user without providing an email address.", "### Fixed", "- Checks for whether a repo is cloned will no longer exhaust open file pools over time.", "### Added", "- The Phabricator extension shows code intelligence status and supports enabling / disabling code intelligence for files.", "## 2.8.8", "### Changed", "- Queries for repositories (in the explore, site admin repositories, and repository header dropdown) are matched on case-insensitive substrings, not using fuzzy matching logic.\n- HTTP Authorization headers with an unrecognized scheme are ignored; they no longer cause the HTTP request to be rejected with HTTP 401 Unauthorized and an \"Invalid Authorization header.\" error.\n- Renamed the `max` search flag to `count`. Searches that specify `count:` will fetch at least that number of results, or the full result set.\n- Bumped `lsp-proxy`'s `initialize` timeout to 3 minutes for every language.\n- Search results are now sorted by repository and file name.\n- More easily accessible \"Show more\" button at the top of the search results page.\n- Results from user satisfaction surveys are now always hosted locally and visible to admins. The `\"experimentalFeatures\": { \"hostSurveysLocally\" }` config option has been deprecated.\n- If the OpenID Connect authentication provider reports that a user's email address is not verified, the authentication attempt will fail.", "### Fixed", "- Fixed an issue where the search results page would not update its title.\n- The session cookie name is now `sgs` (not `sg-session`) so that Sourcegraph 2.7 and Sourcegraph 2.8 can be run side-by-side temporarily during a rolling update without clearing each other's session cookies.\n- Fixed the default hostnames of the C# and R language servers\n- Fixed an issue where deleting an organization prevented the creation of organizations with the name of the deleted organization.\n- Non-UTF8 encoded files (e.g. ISO-8859-1/Latin1, UTF16, etc) are now displayed as text properly rather than being detected as binary files.\n- Improved error message when lsp-proxy's initalize timeout occurs\n- Fixed compatibility issues and added [instructions for using Microsoft ADFS 2.1 and 3.0 for SAML authentication](https://docs.sourcegraph.com/admin/auth/saml_with_microsoft_adfs).\n- Fixed an issue where external accounts associated with deleted user accounts would still be returned by the GraphQL API. This caused the site admin external accounts page to fail to render in some cases.\n- Significantly reduced the number of code host requests for non github.com or gitlab.com repositories.", "### Added", "- The repository revisions popover now shows the target commit's last-committed/authored date for branches and tags.\n- Setting the env var `INSECURE_SAML_LOG_TRACES=1` on the server (or the `sourcegraph-frontend` pod in Kubernetes) causes all SAML requests and responses to be logged, which helps with debugging SAML.\n- Site admins can now view user satisfaction surveys grouped by user, in addition to chronological order, and aggregate summary values (including the average score and the net promoter score over the last 30 days) are now displayed.\n- The site admin overview page displays the site ID, the primary admin email, and premium feature usage information.\n- Added Haskell as an experimental language server on the code intelligence admin page.", "## 2.8.0", "### Changed", "- `gitMaxConcurrentClones` now also limits the concurrency of updates to repos in addition to the initial clone.\n- In the GraphQL API, `site.users` has been renamed to `users`, `site.orgs` has been renamed to `organizations`, and `site.repositories` has been renamed to `repositories`.\n- An authentication provider must be set in site configuration (see [authentication provider documentation](https://docs.sourcegraph.com/admin/auth)). Previously the server defaulted to builtin auth if none was set.\n- If a process dies inside the Sourcegraph container the whole container will shut down. We suggest operators configure a [Docker Restart Policy](https://docs.docker.com/config/containers/start-containers-automatically/#restart-policy-details) or a [Kubernetes Restart Policy](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy). Previously the container would operate in a degraded mode if a process died.\n- Changes to the `auth.public` site config are applied immediately in `sourcegraph/server` (no restart needed).\n- The new search timeout behavior is now enabled by default. Set `\"experimentalFeatures\": {\"searchTimeoutParameter\": \"disabled\"}` in site config to disable it.\n- Search includes files up to 1MB (previous limit was 512KB for unindexed search and 128KB for indexed search).\n- Usernames and email addresses reported by OpenID Connect and SAML auth providers are now trusted, and users will sign into existing Sourcegraph accounts that match on the auth provider's reported username or email.\n- The repository sidebar file tree is much, much faster on massive repositories (200,000+ files)\n- The SAML authentication provider was significantly improved. Users who were signed in using SAML previously will need to reauthenticate via SAML next time they visit Sourcegraph.\n- The SAML `serviceProviderCertificate` and `serviceProviderPrivateKey` site config properties are now optional.", "### Fixed", "- Fixed an issue where Index Search status page failed to render.\n- User data on the site admin Analytics page is now paginated, filterable by a user's recent activity, and searchable.\n- The link to the root of a repository in the repository header now preserves the revision you're currently viewing.\n- When using the `http-header` auth provider, signin/signup/signout links are now hidden.\n- Repository paths beginning with `go/` are no longer reservered by Sourcegraph.\n- Interpret `X-Forwarded-Proto` HTTP header when `httpToHttpsRedirect` is set to `load-balanced`.\n- Deleting a user account no longer prevents the creation of a new user account with the same username and/or association with authentication provider account (SAML/OpenID/etc.)\n- It is now possible for a user to verify an email address that was previously associated with now-deleted user account.\n- Diff searches over empty repositories no longer fail (this was not an issue for Sourcegraph cluster deployments).\n- Stray `tmp_pack_*` files from interrupted fetches should now go away.\n- When multiple `repo:` tokens match the same repo, process @revspec requirements from all of them, not just the first one in the search.", "### Removed", "- The `ssoUserHeader` site config property (deprecated since January 2018) has been removed. The functionality was moved to the `http-header` authentication provider.\n- The experiment flag `showMissingReposEnabled`, which defaulted to enabled, has been removed so it is no longer possible to disable this feature.\n- Event-level telemetry has been completely removed from self-hosted Sourcegraph instances. As a result, the `disableTelemetry` site configuration option has been deprecated. The new site-admin Pings page clarifies the only high-level telemetry being sent to Sourcegraph.com.\n- The deprecated `adminUsernames` site config property (deprecated since January 2018) has been removed because it is no longer necessary. Site admins can designate other users as site admins in the site admin area, and the first user to sign into a new instance always becomes a site admin (even when using an external authentication provider).", "### Added", "- The new repository contributors page (linked from the repository homepage) displays the top Git commit authors in a repository, with filtering options.\n- Custom language servers in the site config may now specify a `metadata` property containing things like homepage/docs/issues URLs for the language server project, as well as whether or not the language server should be considered experimental (not ready for prime-time). This `metadata` will be displayed in the UI to better communicate the status of a language server project.\n- Access tokens now have scopes (which define the set of operations they permit). All access tokens still provide full control of all resources associated with the user account (the `user:all` scope, which is now explicitly displayed).\n- The new access token scope `site-admin:sudo` allows the holder to perform any action as any other user. Only site admins may create this token.\n- Links to Sourcegraph's changelog have been added to the site admin Updates page and update alert.\n- If the site configuration is invalid or uses deprecated properties, a global alert will be shown to all site admins.\n- There is now a code intelligence status indicator when viewing files. It contains information about the capabailities of the language server that is providing code intelligence for the file.\n- Java code intelligence can now be enabled for repositories that aren't automatically supported using a\n `javaconfig.json` file. For Gradle plugins, this file can be generated using\n the [Javaconfig Gradle plugin](https://docs.sourcegraph.com/extensions/language_servers/java#gradle-execution).\n- The new `auth.providers` site config is an array of authentication provider objects. Currently only 1 auth provider is supported. The singular `auth.provider` is deprecated.\n- Users authenticated with OpenID Connect are now able to sign out of Sourcegraph (if the provider supports token revocation or the end-session endpoint).\n- Users can now specify the number of days, weeks, and months of site activity to query through the GraphQL API.\n- Added 14 new experimental language servers on the code intelligence admin page.\n- Added `httpStrictTransportSecurity` site configuration option to customize the Strict-Transport-Security HTTP header. It defaults to `max-age=31536000` (one year).\n- Added `nameIDFormat` in the `saml` auth provider to set the SAML NameID format. The default changed from transient to persistent.\n- (This feature has been removed.) Experimental env var expansion in site config JSON: set `SOURCEGRAPH_EXPAND_CONFIG_VARS=1` to replace `${var}` or `$var` (based on environment variables) in any string value in site config JSON (except for JSON object property names).\n- The new (optional) SAML `serviceProviderIssuer` site config property (in an `auth.providers` array entry with `{\"type\":\"saml\", ...}`) allows customizing the SAML Service Provider issuer name.\n- The site admin area now has an \"Auth\" section that shows the enabled authentication provider(s) and users' external accounts.", "## 2.7.6", "### Fixed", "- If a user's account is deleted, session cookies for that user are no longer considered valid.", "## 2.7.5", "### Changed", "- When deploying Sourcegraph to Kubernetes, RBAC is now used by default. Most Kubernetes clusters require it. See the Kubernetes installation instructions for more information (including disabling if needed).\n- Increased git ssh connection timeout to 30s from 7s.\n- The Phabricator integration no longer requires staging areas, but using them is still recommended because it improves performance.", "### Fixed", "- Fixed an issue where language servers that were not enabled would display the \"Restart\" button in the Code Intelligence management panel.\n- Fixed an issue where the \"Update\" button in the Code Intelligence management panel would be displayed inconsistently.\n- Fixed an issue where toggling a dynamic search scope would not also remove `@rev` (if specified)\n- Fixed an issue where where modes that can only be determined by the full filename (not just the file extension) of a path weren't supported (Dockerfiles are the first example of this).\n- Fixed an issue where the GraphiQL console failed when variables are specified.\n- Indexed search no longer maintains its own git clones. For Kubernetes cluster deployments, this significantly reduces disk size requirements for the indexed-search pod.\n- Fixed an issue where language server Docker containers would not be automatically restarted if they crashed (`sourcegraph/server` only).\n- Fixed an issue where if the first user on a site authenticated via SSO, the site would remain stuck in uninitialized mode.", "### Added", "- More detailed progress information is displayed on pages that are waiting for repositories to clone.\n- Admins can now see charts with daily, weekly, and monthly unique user counts by visiting the site-admin Analytics page.\n- Admins can now host and see results from Sourcegraph user satisfaction surveys locally by setting the `\"experimentalFeatures\": { \"hostSurveysLocally\": \"enabled\"}` site config option. This feature will be enabled for all instances once stable.\n- Access tokens are now supported for all authentication providers (including OpenID Connect and SAML, which were previously not supported).\n- The new `motd` setting (in global, organization, and user settings) displays specified messages at the top of all pages.\n- Site admins may now view all access tokens site-wide (for all users) and revoke tokens from the new access tokens page in the site admin area.", "## 2.7.0", "### Changed", "- Missing repositories no longer appear as search results. Instead, a count of repositories that were not found is displayed above the search results. Hovering over the count will reveal the names of the missing repositories.\n- \"Show more\" on the search results page will now reveal results that have already been fetched (if such results exist) without needing to do a new query.\n- The bottom panel (on a file) now shows more tabs, including docstrings, multiple definitions, references (as before), external references grouped by repository, implementations (if supported by the language server), and file history.\n- The repository sidebar file tree is much faster on massive repositories (200,000+ files)", "### Fixed", "- Searches no longer block if the index is unavailable (e.g. after the index pod restarts). Instead, it respects the normal search timeout and reports the situation to the user if the index is not yet available.\n- Repository results are no longer returned for filters that are not supported (e.g. if `file:` is part of the search query)\n- Fixed an issue where file tree elements may be scrolled out of view on page load.\n- Fixed an issue that caused \"Could not ensure repository updated\" log messages when trying to update a large number of repositories from gitolite.\n- When using an HTTP authentication proxy (`\"auth.provider\": \"http-header\"`), usernames are now properly normalized (special characters including `.` replaced with `-`). This fixes an issue preventing users from signing in if their username contained these special characters.\n- Fixed an issue where the site-admin Updates page would incorrectly report that update checking was turned off when `telemetryDisabled` was set, even as it continued to report new updates.\n- `repo:` filters that match multiple repositories and contain a revision specifier now correctly return partial results even if some of the matching repositories don't have a matching revision.\n- Removed hardcoded list of supported languages for code intelligence. Any language can work now and support is determined from the server response.\n- Fixed an issue where modifying `config.json` on disk would not correctly mark the server as needing a restart.\n- Fixed an issue where certain diff searches (with very sparse matches in a repository's history) would incorrectly report no results found.\n- Fixed an issue where the `langservers` field in the site-configuration didn't require both the `language` and `address` field to be specified for each entry", "### Added", "- Users (and site admins) may now create and manage access tokens to authenticate API clients. The site config `auth.disableAccessTokens` (renamed to `auth.accessTokens` in 2.11) disables this new feature. Access tokens are currently only supported when using the `builtin` and `http-header` authentication providers (not OpenID Connect or SAML).\n- User and site admin management capabilities for user email addresses are improved.\n- The user and organization management UI has been greatly improved. Site admins may now administer all organizations (even those they aren't a member of) and may edit profile info and configuration for all users.\n- If SSO is enabled (via OpenID Connect or SAML) and the SSO system provides user avatar images and/or display names, those are now used by Sourcegraph.\n- Enable new search timeout behavior by setting `\"experimentalFeatures\": { \"searchTimeoutParameter\": \"enabled\"}` in your site config.\n - Adds a new `timeout:` parameter to customize the timeout for searches. It defaults to 10s and may not be set higher than 1m.\n - The value of the `timeout:` parameter is a string that can be parsed by [time.Duration](https://golang.org/pkg/time/#ParseDuration) (e.g. \"100ms\", \"2s\").\n - When `timeout:` is not provided, search optimizes for retuning results as soon as possible and will include slower kinds of results (e.g. symbols) only if they are found quickly.\n - When `timeout:` is provided, all result kinds are given the full timeout to complete.\n- A new user settings tokens page was added that allows users to obtain a token that they can use to authenticate to the Sourcegraph API.\n- Code intelligence indexes are now built for all repositories in the background, regardless of whether or not they are visited directly by a user.\n- Language servers are now automatically enabled when visiting a repository. For example, visiting a Go repository will now automatically download and run the relevant Docker container for Go code intelligence.\n - This change only affects when Sourcegraph is deployed using the `sourcegraph/server` Docker image (not using Kubernetes).\n - You will need to use the new `docker run` command at https://docs.sourcegraph.com/#quick-install in order for this feature to be enabled. Otherwise, you will receive errors in the log about `/var/run/docker.sock` and things will work just as they did before. See https://docs.sourcegraph.com/extensions/language_servers for more information.\n- The site admin Analytics page will now display the number of \"Code Intelligence\" actions each user has made, including hovers, jump to definitions, and find references, on the Sourcegraph webapp or in a code host integration or extension.\n- An experimental cross repository jump to definition which consults the OSS index on Sourcegraph.com. This is disabled by default; use `\"experimentalFeatures\": { \"jumpToDefOSSIndex\": \"enabled\" }` in your site configuration to enable it.\n- Users can now view Git branches, tags, and commits, and compare Git branches and revisions on Sourcegraph. (The code host icon in the header takes you to the commit on the code host.)\n- A new admin panel allows you to view and manage language servers. For Docker deployments, it allows you to enable/disable/update/restart language servers at the click of a button. For cluster deployments, it shows the current status of language servers.\n- Users can now tweet their feedback about Sourcegraph when clicking on the feedback smiley located in the navbar and filling out a Twitter feedback form.\n- A new button in the repository header toggles on/off the Git history panel for the current file.", "## 2.6.8", "### Bug fixes", "- Searches of `type:repo` now work correctly with \"Show more\" and the `max` parameter.\n- Fixes an issue where the server would crash if the DB was not available upon startup.", "## 2.6.7", "### Added", "- The duration that the frontend waits for the PostgreSQL database to become available is now configurable with the `DB_STARTUP_TIMEOUT` env var (the value is any valid Go duration string).\n- Dynamic search filters now suggest exclusions of Go test files, vendored files and node_modules files.", "## 2.6.6", "### Added", "- Authentication to Bitbucket Server using username-password credentials is now supported (in the `bitbucketServer` site config `username`/`password` options), for servers running Bitbucket Server version 2.4 and older (which don't support personal access tokens).", "## 2.6.5", "### Added", "- The externally accessible URL path `/healthz` performs a basic application health check, returning HTTP 200 on success and HTTP 500 on failure.", "### Behavior changes", "- Read-only forks on GitHub are no longer synced by default. If you want to add a readonly fork, navigate directly to the repository page on Sourcegraph to add it (e.g. https://sourcegraph.mycompany.internal/github.com/owner/repo). This prevents your repositories list from being cluttered with a large number of private forks of a private repository that you have access to. One notable example is https://github.com/EpicGames/UnrealEngine.\n- SAML cookies now expire after 90 days. The previous behavior was every 1 hour, which was unintentionally low.", "## 2.6.4", "### Added", "- Improve search timeout error messages\n- Performance improvements for searching regular expressions that do not start with a literal.", "## 2.6.3", "### Bug fixes", "- Symbol results are now only returned for searches that contain `type:symbol`", "## 2.6.2", "### Added", "- More detailed logging to help diagnose errors with third-party authentication providers.\n- Anchors (such as `#my-section`) in rendered Markdown files are now supported.\n- Instrumentation section for admins. For each service we expose pprof, prometheus metrics and traces.", "### Bug fixes", "- Applies a 1s timeout to symbol search if invoked without specifying `type:` to not block plain text results. No change of behaviour if `type:symbol` is given explicitly.\n- Only show line wrap toggle for code-view-rendered files.", "## 2.6.1", "### Bug fixes", "- Fixes a bug where typing in the search query field would modify the expanded state of file search results.\n- Fixes a bug where new logins via OpenID Connect would fail with the error `SSO error: ID Token verification failed`.", "## 2.6.0", "### Added", "- Support for [Bitbucket Server](https://www.atlassian.com/software/bitbucket/server) as a codehost. Configure via the `bitbucketServer` site config field.\n- Prometheus gauges for git clone queue depth (`src_gitserver_clone_queue`) and git ls-remote queue depth (`src_gitserver_lsremote_queue`).\n- Slack notifications for saved searches may now be added for individual users (not just organizations).\n- The new search filter `lang:` filters results by programming language (example: `foo lang:go` or `foo -lang:clojure`).\n- Dynamic filters: filters generated from your search results to help refine your results.\n- Search queries that consist only of `file:` now show files whose path matches the filters (instead of no results).\n- Sourcegraph now automatically detects basic `$GOPATH` configurations found in `.envrc` files in the root of repositories.\n- You can now configure the effective `$GOPATH`s of a repository by adding a `.sourcegraph/config.json` file to your repository with the contents `{\"go\": {\"GOPATH\": [\"mygopath\"]}}`.\n- A new `\"blacklistGoGet\": [\"mydomain.org,myseconddomain.com\"]` offers users a quick escape hatch in the event that Sourcegraph is making unwanted `go get` or `git clone` requests to their website due to incorrectly-configured monorepos. Most users will never use this option.\n- Search suggestions and results now include symbol results. The new filter `type:symbol` causes only symbol results to be shown.\n Additionally, symbols for a repository can be browsed in the new symbols sidebar.\n- You can now expand and collapse all items on a search results page or selectively expand and collapse individual items.", "### Configuration changes", "- Reduced the `gitMaxConcurrentClones` site config option's default value from 100 to 5, to help prevent too many concurrent clones from causing issues on code hosts.\n- Changes to some site configuration options are now automatically detected and no longer require a server restart. After hitting Save in the UI, you will be informed if a server restart is required, per usual.\n- Saved search notifications are now only sent to the owner of a saved search (all of an organization's members for an organization-level saved search, or a single user for a user-level saved search). The `notifyUsers` and `notifyOrganizations` properties underneath `search.savedQueries` have been removed.\n- Slack webhook URLs are now defined in user/organization JSON settings, not on the organization profile page. Previously defined organization Slack webhook URLs are automatically migrated to the organization's JSON settings.\n- The \"unlimited\" value for `maxReposToSearch` is now `-1` instead of `0`, and `0` now means to use the default.\n- `auth.provider` must be set (`builtin`, `openidconnect`, `saml`, `http-header`, etc.) to configure an authentication provider. Previously you could just set the detailed configuration property (`\"auth.openIDConnect\": {...}`, etc.) and it would implicitly enable that authentication provider.\n- The `autoRepoAdd` site configuration property was removed. Site admins can add repositories via site configuration.", "### Bug fixes", "- Only cross reference index enabled repositories.\n- Fixed an issue where search would return results with empty file contents for matches in submodules with indexing enabled. Searching over submodules is not supported yet, so these (empty) results have been removed.\n- Fixed an issue where match highlighting would be incorrect on lines that contained multibyte characters.\n- Fixed an issue where search suggestions would always link to master (and 404) even if the file only existed on a branch. Now suggestions always link to the revision that is being searched over.\n- Fixed an issue where all file and repository links on the search results page (for all search results types) would always link to master branch, even if the results only existed in another branch. Now search results links always link to the revision that is being searched over.\n- The first user to sign up for a (not-yet-initialized) server is made the site admin, even if they signed up using SSO. Previously if the first user signed up using SSO, they would not be a site admin and no site admin could be created.\n- Fixed an issue where our code intelligence archive cache (in `lsp-proxy`) would not evict items from the disk. This would lead to disks running out of free space.", "## 2.5.16, 2.5.17", "- Version bump to keep deployment variants in sync.", "## 2.5.15", "### Bug fixes", "- Fixed issue where a Sourcegraph cluster would incorrectly show \"An update is available\".\n- Fixed Phabricator links to repositories\n- Searches over a single repository are now less likely to immediately time out the first time they are searched.\n- Fixed a bug where `auth.provider == \"http-header\"` would incorrectly require builtin authentication / block site access when `auth.public == \"false\"`.", "### Phabricator Integration Changes", "We now display a \"View on Phabricator\" link rather than a \"View on other code host\" link if you are using Phabricator and hosting on GitHub or another code host with a UI. Commit links also will point to Phabricator.", "### Improvements to SAML authentication", "You may now optionally provide the SAML Identity Provider metadata XML file contents directly, with the `auth.saml` `identityProviderMetadata` site configuration property. (Previously, you needed to specify the URL where that XML file was available; that is still possible and is more common.) The new option is useful for organizations whose SAML metadata is not web-accessible or while testing SAML metadata configuration changes.", "## 2.5.13", "### Improvements to builtin authentication", "When using `auth.provider == \"builtin\"`, two new important changes mean that a Sourcegraph server will be locked down and only accessible to users who are invited by an admin user (previously, we advised users to place their own auth proxy in front of Sourcegraph servers).", "1. When `auth.provider == \"builtin\"` Sourcegraph will now by default require an admin to invite users instead of allowing anyone who can visit the site to sign up. Set `auth.allowSignup == true` to retain the old behavior of allowing anyone who can access the site to signup.\n2. When `auth.provider == \"builtin\"`, Sourcegraph will now respects a new `auth.public` site configuration option (default value: `false`). When `auth.public == false`, Sourcegraph will not allow anyone to access the site unless they have an account and are signed in.", "## 2.4.3", "### Added", "- Code Intelligence support\n- Custom links to code hosts with the `links:` config options in `repos.list`", "### Changed", "- Search by file path enabled by default", "## 2.4.2", "### Added", "- Repository settings mirror/cloning diagnostics page", "### Changed", "- Repositories added from GitHub are no longer enabled by default. The site admin UI for enabling/disabling repositories is improved.", "## 2.4.0", "### Added", "- Search files by name by including `type:path` in a search query\n- Global alerts for configuration-needed and cloning-in-progress\n- Better list interfaces for repositories, users, organizations, and threads\n- Users can change their own password in settings\n- Repository groups can now be specified in settings by site admins, organizations, and users. Then `repogroup:foo` in a search query will search over only those repositories specified for the `foo` repository group.", "### Changed", "- Log messages are much quieter by default", "## 2.3.11", "### Added", "- Added site admin updates page and update checking\n- Added site admin telemetry page", "### Changed", "- Enhanced site admin panel\n- Changed repo- and SSO-related site config property names to be consistent, updated documentation", "## 2.3.10", "### Added", "- Online site configuration editing and reloading", "### Changed", "- Site admins are now configured in the site admin area instead of in the `adminUsernames` config key or `ADMIN_USERNAMES` env var. Users specified in those deprecated configs will be designated as site admins in the database upon server startup until those configs are removed in a future release.", "## 2.3.9", "### Fixed", "- An issue that prevented creation and deletion of saved queries", "## 2.3.8", "### Added", "- Built-in authentication: you can now sign up without an SSO provider.\n- Faster default branch code search via indexing.", "### Fixed", "- Many performance improvements to search.\n- Much log spam has been eliminated.", "### Changed", "- We optionally read `SOURCEGRAPH_CONFIG` from `$DATA_DIR/config.json`.\n- SSH key required to clone repositories from GitHub Enterprise when using a self-signed certificate.", "## 0.3 - 13 December 2017", "The last version without a CHANGELOG." ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [26, 1516, 36, 537], "buggy_code_start_loc": [26, 39, 33, 537], "filenames": ["CHANGELOG.md", "cmd/frontend/graphqlbackend/search_results.go", "dev/gqltest/README.md", "dev/gqltest/search_test.go"], "fixing_code_end_loc": [35, 1518, 36, 544], "fixing_code_start_loc": [27, 40, 33, 538], "message": "Sourcegraph is a code search and navigation engine. Sourcegraph prior to version 3.33.2 is vulnerable to a side-channel attack where strings in private source code could be guessed by an authenticated but unauthorized actor. This issue affects the Saved Searches and Code Monitoring features. A successful attack would require an authenticated bad actor to create many Saved Searches or Code Monitors to receive confirmation that a specific string exists. This could allow an attacker to guess formatted tokens in source code, such as API keys. This issue was patched in version 3.33.2 and any future versions of Sourcegraph. We strongly encourage upgrading to secure versions. If you are unable to, you may disable Saved Searches and Code Monitors.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sourcegraph:sourcegraph:*:*:*:*:*:*:*:*", "matchCriteriaId": "8AC67147-DAE3-4326-9027-0DEB53C55D32", "versionEndExcluding": "3.33.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Sourcegraph is a code search and navigation engine. Sourcegraph prior to version 3.33.2 is vulnerable to a side-channel attack where strings in private source code could be guessed by an authenticated but unauthorized actor. This issue affects the Saved Searches and Code Monitoring features. A successful attack would require an authenticated bad actor to create many Saved Searches or Code Monitors to receive confirmation that a specific string exists. This could allow an attacker to guess formatted tokens in source code, such as API keys. This issue was patched in version 3.33.2 and any future versions of Sourcegraph. We strongly encourage upgrading to secure versions. If you are unable to, you may disable Saved Searches and Code Monitors."}, {"lang": "es", "value": "Sourcegraph es un motor de b\u00fasqueda y navegaci\u00f3n de c\u00f3digo. Sourcegraph versiones anteriores a 3.33.2 es vulnerable a un ataque de canal lateral en el que las cadenas del c\u00f3digo fuente privado podr\u00edan ser adivinadas por un actor autenticado pero no autorizado. Este problema afecta a las funciones de B\u00fasquedas Guardadas y Monitorizaci\u00f3n de C\u00f3digo. Un ataque con \u00e9xito requerir\u00eda que un actor malo autenticado creara muchas B\u00fasquedas Guardadas o Monitores de C\u00f3digo para recibir la confirmaci\u00f3n de que una cadena espec\u00edfica esta presente. Esto podr\u00eda permitir a un atacante adivinar los tokens formateados en el c\u00f3digo fuente, como las claves de la API. Este problema ha sido parcheado en la versi\u00f3n 3.33.2 y en las futuras versiones de Sourcegraph. Recomendamos encarecidamente que se actualice a las versiones seguras. Si no puede hacerlo, puede deshabilitar las B\u00fasquedas Guardadas y los Monitores de C\u00f3digo"}], "evaluatorComment": null, "id": "CVE-2021-43823", "lastModified": "2021-12-16T15:00:25.970", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Primary"}]}, "published": "2021-12-13T20:15:07.813", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/sourcegraph/sourcegraph/commit/a88d90a8302c492282186d39718cd8fb093c14fa"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/sourcegraph/sourcegraph/security/advisories/GHSA-cpq7-hmvv-29w9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-203"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/sourcegraph/sourcegraph/commit/a88d90a8302c492282186d39718cd8fb093c14fa"}, "type": "CWE-203"}
326
Determine whether the {function_name} code is vulnerable or not.
[ "package graphqlbackend", "import (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"math\"\n\t\"path\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"", "\t\"github.com/cockroachdb/errors\"\n\t\"github.com/inconshreveable/log15\"\n\t\"github.com/neelance/parallel\"\n\t\"github.com/opentracing/opentracing-go\"\n\t\"github.com/opentracing/opentracing-go/ext\"\n\totlog \"github.com/opentracing/opentracing-go/log\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promauto\"", "\t\"github.com/sourcegraph/sourcegraph/cmd/frontend/envvar\"\n\tsearchlogs \"github.com/sourcegraph/sourcegraph/cmd/frontend/internal/search/logs\"\n\t\"github.com/sourcegraph/sourcegraph/internal/actor\"\n\t\"github.com/sourcegraph/sourcegraph/internal/api\"\n\t\"github.com/sourcegraph/sourcegraph/internal/conf\"\n\t\"github.com/sourcegraph/sourcegraph/internal/database\"\n\t\"github.com/sourcegraph/sourcegraph/internal/database/dbutil\"\n\t\"github.com/sourcegraph/sourcegraph/internal/deviceid\"\n\t\"github.com/sourcegraph/sourcegraph/internal/featureflag\"\n\t\"github.com/sourcegraph/sourcegraph/internal/goroutine\"\n\t\"github.com/sourcegraph/sourcegraph/internal/honey\"\n\t\"github.com/sourcegraph/sourcegraph/internal/rcache\"\n\t\"github.com/sourcegraph/sourcegraph/internal/search\"\n\t\"github.com/sourcegraph/sourcegraph/internal/search/commit\"\n\t\"github.com/sourcegraph/sourcegraph/internal/search/filter\"\n\t\"github.com/sourcegraph/sourcegraph/internal/search/query\"", "", "\tsearchrepos \"github.com/sourcegraph/sourcegraph/internal/search/repos\"\n\t\"github.com/sourcegraph/sourcegraph/internal/search/result\"\n\t\"github.com/sourcegraph/sourcegraph/internal/search/run\"\n\t\"github.com/sourcegraph/sourcegraph/internal/search/searchcontexts\"\n\t\"github.com/sourcegraph/sourcegraph/internal/search/streaming\"\n\t\"github.com/sourcegraph/sourcegraph/internal/search/unindexed\"\n\t\"github.com/sourcegraph/sourcegraph/internal/trace\"\n\t\"github.com/sourcegraph/sourcegraph/internal/trace/ot\"\n\t\"github.com/sourcegraph/sourcegraph/internal/types\"\n\t\"github.com/sourcegraph/sourcegraph/internal/usagestats\"\n\t\"github.com/sourcegraph/sourcegraph/internal/vcs/git\"\n\t\"github.com/sourcegraph/sourcegraph/schema\"\n)", "func (c *SearchResultsResolver) LimitHit() bool {\n\treturn c.Stats.IsLimitHit || (c.limit > 0 && len(c.Matches) > c.limit)\n}", "func (c *SearchResultsResolver) Repositories() []*RepositoryResolver {\n\trepos := c.Stats.Repos\n\tresolvers := make([]*RepositoryResolver, 0, len(repos))\n\tfor _, r := range repos {\n\t\tresolvers = append(resolvers, NewRepositoryResolver(c.db, r.ToRepo()))\n\t}\n\tsort.Slice(resolvers, func(a, b int) bool {\n\t\treturn resolvers[a].ID() < resolvers[b].ID()\n\t})\n\treturn resolvers\n}", "func (c *SearchResultsResolver) RepositoriesCount() int32 {\n\treturn int32(len(c.Stats.Repos))\n}", "func (c *SearchResultsResolver) repositoryResolvers(mask search.RepoStatus) []*RepositoryResolver {\n\tvar resolvers []*RepositoryResolver\n\tc.Stats.Status.Filter(mask, func(id api.RepoID) {\n\t\tif r, ok := c.Stats.Repos[id]; ok {\n\t\t\tresolvers = append(resolvers, NewRepositoryResolver(c.db, r.ToRepo()))\n\t\t}\n\t})\n\tsort.Slice(resolvers, func(a, b int) bool {\n\t\treturn resolvers[a].ID() < resolvers[b].ID()\n\t})\n\treturn resolvers\n}", "func (c *SearchResultsResolver) Cloning() []*RepositoryResolver {\n\treturn c.repositoryResolvers(search.RepoStatusCloning)\n}", "func (c *SearchResultsResolver) Missing() []*RepositoryResolver {\n\treturn c.repositoryResolvers(search.RepoStatusMissing)\n}", "func (c *SearchResultsResolver) Timedout() []*RepositoryResolver {\n\treturn c.repositoryResolvers(search.RepoStatusTimedout)\n}", "func (c *SearchResultsResolver) IndexUnavailable() bool {\n\treturn c.Stats.IsIndexUnavailable\n}", "// SearchResultsResolver is a resolver for the GraphQL type `SearchResults`\ntype SearchResultsResolver struct {\n\tdb dbutil.DB\n\t*SearchResults", "\t// limit is the maximum number of SearchResults to send back to the user.\n\tlimit int", "\t// The time it took to compute all results.\n\telapsed time.Duration", "\t// cache for user settings. Ideally this should be set just once in the code path\n\t// by an upstream resolver\n\tUserSettings *schema.Settings\n}", "type SearchResults struct {\n\tMatches []result.Match\n\tStats streaming.Stats\n\tAlert *searchAlert\n}", "// Results are the results found by the search. It respects the limits set. To\n// access all results directly access the SearchResults field.\nfunc (sr *SearchResultsResolver) Results() []SearchResultResolver {\n\tlimited := sr.Matches\n\tif sr.limit > 0 && sr.limit < len(sr.Matches) {\n\t\tlimited = sr.Matches[:sr.limit]\n\t}", "\treturn matchesToResolvers(sr.db, limited)\n}", "func matchesToResolvers(db dbutil.DB, matches []result.Match) []SearchResultResolver {\n\ttype repoKey struct {\n\t\tName types.RepoName\n\t\tRev string\n\t}\n\trepoResolvers := make(map[repoKey]*RepositoryResolver, 10)\n\tgetRepoResolver := func(repoName types.RepoName, rev string) *RepositoryResolver {\n\t\tif existing, ok := repoResolvers[repoKey{repoName, rev}]; ok {\n\t\t\treturn existing\n\t\t}\n\t\tresolver := NewRepositoryResolver(db, repoName.ToRepo())\n\t\tresolver.RepoMatch.Rev = rev\n\t\trepoResolvers[repoKey{repoName, rev}] = resolver\n\t\treturn resolver\n\t}", "\tresolvers := make([]SearchResultResolver, 0, len(matches))\n\tfor _, match := range matches {\n\t\tswitch v := match.(type) {\n\t\tcase *result.FileMatch:\n\t\t\tresolvers = append(resolvers, &FileMatchResolver{\n\t\t\t\tdb: db,\n\t\t\t\tFileMatch: *v,\n\t\t\t\tRepoResolver: getRepoResolver(v.Repo, \"\"),\n\t\t\t})\n\t\tcase *result.RepoMatch:\n\t\t\tresolvers = append(resolvers, getRepoResolver(v.RepoName(), v.Rev))\n\t\tcase *result.CommitMatch:\n\t\t\tresolvers = append(resolvers, &CommitSearchResultResolver{\n\t\t\t\tdb: db,\n\t\t\t\tCommitMatch: *v,\n\t\t\t})\n\t\t}\n\t}\n\treturn resolvers\n}", "func (sr *SearchResultsResolver) MatchCount() int32 {\n\tvar totalResults int\n\tfor _, result := range sr.Matches {\n\t\ttotalResults += result.ResultCount()\n\t}\n\treturn int32(totalResults)\n}", "// Deprecated. Prefer MatchCount.\nfunc (sr *SearchResultsResolver) ResultCount() int32 { return sr.MatchCount() }", "func (sr *SearchResultsResolver) ApproximateResultCount() string {\n\tcount := sr.MatchCount()\n\tif sr.LimitHit() || sr.Stats.Status.Any(search.RepoStatusCloning|search.RepoStatusTimedout) {\n\t\treturn fmt.Sprintf(\"%d+\", count)\n\t}\n\treturn strconv.Itoa(int(count))\n}", "func (sr *SearchResultsResolver) Alert() *searchAlert { return sr.SearchResults.Alert }", "func (sr *SearchResultsResolver) ElapsedMilliseconds() int32 {\n\treturn int32(sr.elapsed.Milliseconds())\n}", "func (sr *SearchResultsResolver) DynamicFilters(ctx context.Context) []*searchFilterResolver {\n\ttr, ctx := trace.New(ctx, \"DynamicFilters\", \"\", trace.Tag{Key: \"resolver\", Value: \"SearchResultsResolver\"})\n\tdefer func() {\n\t\ttr.Finish()\n\t}()", "\tglobbing := false\n\t// For search, sr.userSettings is set in (r *searchResolver) Results(ctx\n\t// context.Context). However we might regress on that or call DynamicFilters from\n\t// other code paths. Hence we fallback to accessing the user settings directly.\n\tif sr.UserSettings != nil {\n\t\tglobbing = getBoolPtr(sr.UserSettings.SearchGlobbing, false)\n\t} else {\n\t\tsettings, err := decodedViewerFinalSettings(ctx, sr.db)\n\t\tif err != nil {\n\t\t\tlog15.Warn(\"DynamicFilters: could not get user settings from database\")\n\t\t} else {\n\t\t\tglobbing = getBoolPtr(settings.SearchGlobbing, false)\n\t\t}\n\t}\n\ttr.LogFields(otlog.Bool(\"globbing\", globbing))", "\tfilters := streaming.SearchFilters{\n\t\tGlobbing: globbing,\n\t}\n\tfilters.Update(streaming.SearchEvent{\n\t\tResults: sr.Matches,\n\t\tStats: sr.Stats,\n\t})", "\tvar resolvers []*searchFilterResolver\n\tfor _, f := range filters.Compute() {\n\t\tresolvers = append(resolvers, &searchFilterResolver{filter: *f})\n\t}\n\treturn resolvers\n}", "type searchFilterResolver struct {\n\tfilter streaming.Filter\n}", "func (sf *searchFilterResolver) Value() string {\n\treturn sf.filter.Value\n}", "func (sf *searchFilterResolver) Label() string {\n\treturn sf.filter.Label\n}", "func (sf *searchFilterResolver) Count() int32 {\n\treturn int32(sf.filter.Count)\n}", "func (sf *searchFilterResolver) LimitHit() bool {\n\treturn sf.filter.IsLimitHit\n}", "func (sf *searchFilterResolver) Kind() string {\n\treturn sf.filter.Kind\n}", "// blameFileMatch blames the specified file match to produce the time at which\n// the first line match inside of it was authored.\nfunc (sr *SearchResultsResolver) blameFileMatch(ctx context.Context, fm *result.FileMatch) (t time.Time, err error) {\n\tspan, ctx := ot.StartSpanFromContext(ctx, \"blameFileMatch\")\n\tdefer func() {\n\t\tif err != nil {\n\t\t\text.Error.Set(span, true)\n\t\t\tspan.SetTag(\"err\", err.Error())\n\t\t}\n\t\tspan.Finish()\n\t}()", "\t// Blame the first line match.\n\tif len(fm.LineMatches) == 0 {\n\t\t// No line match\n\t\treturn time.Time{}, nil\n\t}\n\tlm := fm.LineMatches[0]\n\thunks, err := git.BlameFile(ctx, fm.Repo.Name, fm.Path, &git.BlameOptions{\n\t\tNewestCommit: fm.CommitID,\n\t\tStartLine: int(lm.LineNumber),\n\t\tEndLine: int(lm.LineNumber),\n\t})\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}", "\treturn hunks[0].Author.Date, nil\n}", "func (sr *SearchResultsResolver) Sparkline(ctx context.Context) (sparkline []int32, err error) {\n\tvar (\n\t\tdays = 30 // number of days the sparkline represents\n\t\tmaxBlame = 100 // maximum number of file results to blame for date/time information.\n\t\trun = parallel.NewRun(8) // number of concurrent blame ops\n\t)", "\tvar (\n\t\tsparklineMu sync.Mutex\n\t\tblameOps = 0\n\t)\n\tsparkline = make([]int32, days)\n\taddPoint := func(t time.Time) {\n\t\t// Check if the author date of the search result is inside of our sparkline\n\t\t// timerange.\n\t\tnow := time.Now()\n\t\tif t.Before(now.Add(-time.Duration(len(sparkline)) * 24 * time.Hour)) {\n\t\t\t// Outside the range of the sparkline.\n\t\t\treturn\n\t\t}\n\t\tsparklineMu.Lock()\n\t\tdefer sparklineMu.Unlock()\n\t\tfor n := range sparkline {\n\t\t\td1 := now.Add(-time.Duration(n) * 24 * time.Hour)\n\t\t\td2 := now.Add(-time.Duration(n-1) * 24 * time.Hour)\n\t\t\tif t.After(d1) && t.Before(d2) {\n\t\t\t\tsparkline[n]++ // on the nth day\n\t\t\t}\n\t\t}\n\t}", "\t// Consider all of our search results as a potential data point in our\n\t// sparkline.\nloop:\n\tfor _, r := range sr.Matches {\n\t\tr := r // shadow so it doesn't change in the goroutine\n\t\tswitch m := r.(type) {\n\t\tcase *result.RepoMatch:\n\t\t\t// We don't care about repo results here.\n\t\t\tcontinue\n\t\tcase *result.CommitMatch:\n\t\t\t// Diff searches are cheap, because we implicitly have author date info.\n\t\t\taddPoint(m.Commit.Author.Date)\n\t\tcase *result.FileMatch:\n\t\t\t// File match searches are more expensive, because we must blame the\n\t\t\t// (first) line in order to know its placement in our sparkline.\n\t\t\tblameOps++\n\t\t\tif blameOps > maxBlame {\n\t\t\t\t// We have exceeded our budget of blame operations for\n\t\t\t\t// calculating this sparkline, so don't do any more file match\n\t\t\t\t// blaming.\n\t\t\t\tcontinue loop\n\t\t\t}", "\t\t\trun.Acquire()\n\t\t\tgoroutine.Go(func() {\n\t\t\t\tdefer run.Release()", "\t\t\t\t// Blame the file match in order to retrieve date informatino.\n\t\t\t\tvar err error\n\t\t\t\tt, err := sr.blameFileMatch(ctx, m)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog15.Warn(\"failed to blame fileMatch during sparkline generation\", \"error\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\taddPoint(t)\n\t\t\t})\n\t\tdefault:\n\t\t\tpanic(\"SearchResults.Sparkline unexpected union type state\")\n\t\t}\n\t}\n\tspan := opentracing.SpanFromContext(ctx)\n\tspan.SetTag(\"blame_ops\", blameOps)\n\treturn sparkline, nil\n}", "var (\n\tsearchResponseCounter = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"src_graphql_search_response\",\n\t\tHelp: \"Number of searches that have ended in the given status (success, error, timeout, partial_timeout).\",\n\t}, []string{\"status\", \"alert_type\", \"source\", \"request_name\"})", "\tsearchLatencyHistogram = promauto.NewHistogramVec(prometheus.HistogramOpts{\n\t\tName: \"src_search_response_latency_seconds\",\n\t\tHelp: \"Search response latencies in seconds that have ended in the given status (success, error, timeout, partial_timeout).\",\n\t\tBuckets: []float64{0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 30},\n\t}, []string{\"status\", \"alert_type\", \"source\", \"request_name\"})\n)", "// LogSearchLatency records search durations in the event database. This\n// function may only be called after a search result is performed, because it\n// relies on the invariant that query and pattern error checking has already\n// been performed.\nfunc LogSearchLatency(ctx context.Context, db dbutil.DB, si *run.SearchInputs, durationMs int32) {\n\ttr, ctx := trace.New(ctx, \"LogSearchLatency\", \"\")\n\tdefer func() {\n\t\ttr.Finish()\n\t}()\n\tvar types []string\n\tresultTypes, _ := si.Query.StringValues(query.FieldType)\n\tfor _, typ := range resultTypes {\n\t\tswitch typ {\n\t\tcase \"repo\", \"symbol\", \"diff\", \"commit\":\n\t\t\ttypes = append(types, typ)\n\t\tcase \"path\":\n\t\t\t// Map type:path to file\n\t\t\ttypes = append(types, \"file\")\n\t\tcase \"file\":\n\t\t\tswitch {\n\t\t\tcase si.PatternType == query.SearchTypeStructural:\n\t\t\t\ttypes = append(types, \"structural\")\n\t\t\tcase si.PatternType == query.SearchTypeLiteral:\n\t\t\t\ttypes = append(types, \"literal\")\n\t\t\tcase si.PatternType == query.SearchTypeRegex:\n\t\t\t\ttypes = append(types, \"regexp\")\n\t\t\t}\n\t\t}\n\t}", "\t// Don't record composite searches that specify more than one type:\n\t// because we can't break down the search timings into multiple\n\t// categories.\n\tif len(types) > 1 {\n\t\treturn\n\t}", "\tq, err := query.ToBasicQuery(si.Query)\n\tif err != nil {\n\t\t// Can't convert to a basic query, can't guarantee accurate reporting.\n\t\treturn\n\t}\n\tif !query.IsPatternAtom(q) {\n\t\t// Not an atomic pattern, can't guarantee accurate reporting.\n\t\treturn\n\t}", "\t// If no type: was explicitly specified, infer the result type.\n\tif len(types) == 0 {\n\t\t// If a pattern was specified, a content search happened.\n\t\tif q.IsLiteral() {\n\t\t\ttypes = append(types, \"literal\")\n\t\t} else if q.IsRegexp() {\n\t\t\ttypes = append(types, \"regexp\")\n\t\t} else if q.IsStructural() {\n\t\t\ttypes = append(types, \"structural\")\n\t\t} else if len(si.Query.Fields()[\"file\"]) > 0 {\n\t\t\t// No search pattern specified and file: is specified.\n\t\t\ttypes = append(types, \"file\")\n\t\t} else {\n\t\t\t// No search pattern or file: is specified, assume repo.\n\t\t\t// This includes accounting for searches of fields that\n\t\t\t// specify repohasfile: and repohascommitafter:.\n\t\t\ttypes = append(types, \"repo\")\n\t\t}\n\t}", "\t// Only log the time if we successfully resolved one search type.\n\tif len(types) == 1 {\n\t\ta := actor.FromContext(ctx)\n\t\tif a.IsAuthenticated() {\n\t\t\tvalue := fmt.Sprintf(`{\"durationMs\": %d}`, durationMs)\n\t\t\teventName := fmt.Sprintf(\"search.latencies.%s\", types[0])\n\t\t\tfeatureFlags := featureflag.FromContext(ctx)\n\t\t\tgo func() {\n\t\t\t\terr := usagestats.LogBackendEvent(db, a.UID, deviceid.FromContext(ctx), eventName, json.RawMessage(value), json.RawMessage(value), featureFlags, nil)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog15.Warn(\"Could not log search latency\", \"err\", err)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t}\n}", "func (r *searchResolver) toRepoOptions(q query.Q, opts resolveRepositoriesOpts) search.RepoOptions {\n\trepoFilters, minusRepoFilters := q.Repositories()\n\tif opts.effectiveRepoFieldValues != nil {\n\t\trepoFilters = opts.effectiveRepoFieldValues\n\t}\n\trepoGroupFilters, _ := q.StringValues(query.FieldRepoGroup)", "\tvar settingForks, settingArchived bool\n\tif v := r.UserSettings.SearchIncludeForks; v != nil {\n\t\tsettingForks = *v\n\t}\n\tif v := r.UserSettings.SearchIncludeArchived; v != nil {\n\t\tsettingArchived = *v\n\t}", "\tfork := query.No\n\tif searchrepos.ExactlyOneRepo(repoFilters) || settingForks {\n\t\t// fork defaults to No unless either of:\n\t\t// (1) exactly one repo is being searched, or\n\t\t// (2) user/org/global setting includes forks\n\t\tfork = query.Yes\n\t}\n\tif setFork := q.Fork(); setFork != nil {\n\t\tfork = *setFork\n\t}", "\tarchived := query.No\n\tif searchrepos.ExactlyOneRepo(repoFilters) || settingArchived {\n\t\t// archived defaults to No unless either of:\n\t\t// (1) exactly one repo is being searched, or\n\t\t// (2) user/org/global setting includes archives in all searches\n\t\tarchived = query.Yes\n\t}\n\tif setArchived := q.Archived(); setArchived != nil {\n\t\tarchived = *setArchived\n\t}", "\tvisibilityStr, _ := q.StringValue(query.FieldVisibility)\n\tvisibility := query.ParseVisibility(visibilityStr)", "\tcommitAfter, _ := q.StringValue(query.FieldRepoHasCommitAfter)\n\tsearchContextSpec, _ := q.StringValue(query.FieldContext)", "\tvar versionContextName string\n\tif r.VersionContext != nil {\n\t\tversionContextName = *r.VersionContext\n\t}", "\tvar CacheLookup bool\n\tif len(opts.effectiveRepoFieldValues) == 0 && opts.limit == 0 {\n\t\t// indicates resolving repositories should cache DB lookups\n\t\tCacheLookup = true\n\t}", "\treturn search.RepoOptions{\n\t\tRepoFilters: repoFilters,\n\t\tMinusRepoFilters: minusRepoFilters,\n\t\tRepoGroupFilters: repoGroupFilters,\n\t\tVersionContextName: versionContextName,\n\t\tSearchContextSpec: searchContextSpec,\n\t\tUserSettings: r.UserSettings,\n\t\tOnlyForks: fork == query.Only,\n\t\tNoForks: fork == query.No,\n\t\tOnlyArchived: archived == query.Only,\n\t\tNoArchived: archived == query.No,\n\t\tVisibility: visibility,\n\t\tCommitAfter: commitAfter,\n\t\tQuery: q,\n\t\tRanked: true,\n\t\tLimit: opts.limit,\n\t\tCacheLookup: CacheLookup,\n\t}\n}", "func withMode(args search.TextParameters, st query.SearchType, versionContext *string) search.TextParameters {\n\tisGlobalSearch := func() bool {\n\t\tif st == query.SearchTypeStructural {\n\t\t\treturn false\n\t\t}\n\t\tif versionContext != nil && *versionContext != \"\" {\n\t\t\treturn false\n\t\t}", "\t\treturn query.ForAll(args.Query, func(node query.Node) bool {\n\t\t\tn, ok := node.(query.Parameter)\n\t\t\tif !ok {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tswitch n.Field {\n\t\t\tcase query.FieldContext:\n\t\t\t\treturn searchcontexts.IsGlobalSearchContextSpec(n.Value)\n\t\t\tcase query.FieldRepo:\n\t\t\t\t// We allow -repo: in global search.\n\t\t\t\treturn n.Negated\n\t\t\tcase\n\t\t\t\tquery.FieldRepoGroup,\n\t\t\t\tquery.FieldRepoHasFile:\n\t\t\t\treturn false\n\t\t\tdefault:\n\t\t\t\treturn true\n\t\t\t}\n\t\t})\n\t}", "\thasGlobalSearchResultType := args.ResultTypes.Has(result.TypeFile | result.TypePath | result.TypeSymbol)\n\tisIndexedSearch := args.PatternInfo.Index != query.No\n\tisEmpty := args.PatternInfo.Pattern == \"\" && args.PatternInfo.ExcludePattern == \"\" && len(args.PatternInfo.IncludePatterns) == 0\n\tif isGlobalSearch() && isIndexedSearch && hasGlobalSearchResultType && !isEmpty {\n\t\targs.Mode = search.ZoektGlobalSearch\n\t}\n\tif isEmpty {\n\t\targs.Mode = search.SkipUnindexed\n\t}\n\treturn args\n}", "// toSearchInputs converts a query parse tree to the _internal_ representation\n// needed to run a search. To understand why this conversion matters, think\n// about the fact that the query parse tree doesn't know anything about our\n// backends or architecture. It doesn't decide certain defaults, like whether we\n// should return multiple result types (pattern matches content, or a file name,\n// or a repo name). If we want to optimize a Sourcegraph query parse tree for a\n// particular backend (e.g., skip repository resolution and just run a Zoekt\n// query on all indexed repositories) then we need to convert our tree to\n// Zoekt's internal inputs and representation. These concerns are all handled by\n// toSearchInputs.\n//\n// toSearchInputs returns a tuple (args, jobs). `args` represents a large,\n// generic object with many values that drive search logic all over the backend.\n// `jobs` represent search objects with a Run() method that directly runs the\n// search job in question, and the job object comprises only the state to run\n// that search. Currently, both return values may be used to evaluate a search.\n// In time, it is expected that toSearchInputs migrates to return _only_ jobs,\n// where each job contains its separate state for that kind of search and\n// backend. To complete the migration to jobs in phases, `args` is kept\n// backwards compatibility and represents a generic search.\nfunc (r *searchResolver) toSearchInputs(q query.Q) (*search.TextParameters, []run.Job, error) {\n\tb, err := query.ToBasicQuery(q)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tp := search.ToTextPatternInfo(b, r.protocol(), query.Identity)", "\tforceResultTypes := result.TypeEmpty\n\tif r.PatternType == query.SearchTypeStructural {\n\t\tif p.Pattern == \"\" {\n\t\t\t// Fallback to literal search for searching repos and files if\n\t\t\t// the structural search pattern is empty.\n\t\t\tr.PatternType = query.SearchTypeLiteral\n\t\t\tp.IsStructuralPat = false\n\t\t\tforceResultTypes = result.Types(0)\n\t\t} else {\n\t\t\tforceResultTypes = result.TypeStructural\n\t\t}\n\t}", "\targs := search.TextParameters{\n\t\tPatternInfo: p,\n\t\tQuery: q,\n\t\tTimeout: search.TimeoutDuration(b),", "\t\t// UseFullDeadline if timeout: set or we are streaming.\n\t\tUseFullDeadline: q.Timeout() != nil || q.Count() != nil || r.stream != nil,", "\t\tZoekt: r.zoekt,\n\t\tSearcherURLs: r.searcherURLs,\n\t}\n\targs = withResultTypes(args, forceResultTypes)\n\targs = withMode(args, r.PatternType, r.VersionContext)", "\tvar jobs []run.Job\n\t{\n\t\t// This code block creates search jobs under specific\n\t\t// conditions, and depending on generic process of `args` above.\n\t\t// It which specializes search logic in doResults. In time, all\n\t\t// of the above logic should be used to create search jobs\n\t\t// across all of Sourcegraph.\n\t\tif r.PatternType == query.SearchTypeStructural && p.Pattern != \"\" {\n\t\t\tjobs = append(jobs, &unindexed.StructuralSearch{\n\t\t\t\tRepoFetcher: unindexed.NewRepoFetcher(r.stream, &args),\n\t\t\t\tMode: args.Mode,\n\t\t\t\tSearcherArgs: search.SearcherParameters{\n\t\t\t\t\tSearcherURLs: args.SearcherURLs,\n\t\t\t\t\tPatternInfo: args.PatternInfo,\n\t\t\t\t\tUseFullDeadline: args.UseFullDeadline,\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t}\n\treturn &args, jobs, nil\n}", "// evaluateLeaf performs a single search operation and corresponds to the\n// evaluation of leaf expression in a query.\nfunc (r *searchResolver) evaluateLeaf(ctx context.Context, args *search.TextParameters, jobs []run.Job) (_ *SearchResults, err error) {\n\ttr, ctx := trace.New(ctx, \"evaluateLeaf\", \"\")\n\tdefer func() {\n\t\ttr.SetError(err)\n\t\ttr.Finish()\n\t}()", "\treturn r.resultsWithTimeoutSuggestion(ctx, args, jobs)\n}", "// union returns the union of two sets of search results and merges common search data.\nfunc union(left, right *SearchResults) *SearchResults {\n\tif right == nil {\n\t\treturn left\n\t}\n\tif left == nil {\n\t\treturn right\n\t}", "\tif left.Matches != nil && right.Matches != nil {\n\t\tleft.Matches = result.Union(left.Matches, right.Matches)\n\t\tleft.Stats.Update(&right.Stats)\n\t\treturn left\n\t} else if right.Matches != nil {\n\t\treturn right\n\t}\n\treturn left\n}", "// intersect returns the intersection of two sets of search result content\n// matches, based on whether a single file path contains content matches in both sets.\nfunc intersect(left, right *SearchResults) *SearchResults {\n\tif left == nil || right == nil {\n\t\treturn nil\n\t}\n\tleft.Matches = result.Intersect(left.Matches, right.Matches)\n\tleft.Stats.Update(&right.Stats)\n\treturn left\n}", "// evaluateAnd performs set intersection on result sets. It collects results for\n// all expressions that are ANDed together by searching for each subexpression\n// and then intersects those results that are in the same repo/file path. To\n// collect N results for count:N, we need to opportunistically ask for more than\n// N results for each subexpression (since intersect can never yield more than N,\n// and likely yields fewer than N results). If the intersection does not yield N\n// results, and is not exhaustive for every expression, we rerun the search by\n// doubling count again.\nfunc (r *searchResolver) evaluateAnd(ctx context.Context, q query.Basic) (*SearchResults, error) {\n\tstart := time.Now()", "\t// Invariant: this function is only reachable from callers that\n\t// guarantee a root node with one or more operands.\n\toperands := q.Pattern.(query.Operator).Operands", "\tvar (\n\t\terr error\n\t\tresult *SearchResults\n\t\ttermResult *SearchResults\n\t)", "\t// The number of results we want. Note that for intersect, this number\n\t// corresponds to documents, not line matches. By default, we ask for at\n\t// least 5 documents to fill the result page.\n\twant := 5\n\t// The fraction of file matches two terms share on average\n\taverageIntersection := 0.05\n\t// When we retry, cap the max search results we request for each expression\n\t// if search continues to not be exhaustive. Alert if exceeded.\n\tmaxTryCount := 40000", "\t// Set an overall timeout in addition to the timeouts that are set for leaf-requests.\n\tctx, cancel := context.WithTimeout(ctx, search.TimeoutDuration(q))\n\tdefer cancel()", "\tif count := q.GetCount(); count != \"\" {\n\t\twant, _ = strconv.Atoi(count) // Invariant: count is validated.\n\t} else {\n\t\tq = q.AddCount(want)\n\t}", "\t// tryCount starts small but grows exponentially with the number of operands. It is capped at maxTryCount.\n\ttryCount := int(math.Floor(float64(want) / math.Pow(averageIntersection, float64(len(operands)-1))))\n\tif tryCount > maxTryCount {\n\t\ttryCount = maxTryCount\n\t}", "\tvar exhausted bool\n\tfor {\n\t\tq = q.MapCount(tryCount)\n\t\tresult, err = r.evaluatePatternExpression(ctx, q.MapPattern(operands[0]))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif result == nil {\n\t\t\treturn &SearchResults{}, nil\n\t\t}\n\t\tif len(result.Matches) == 0 {\n\t\t\t// result might contain an alert.\n\t\t\treturn result, nil\n\t\t}\n\t\texhausted = !result.Stats.IsLimitHit\n\t\tfor _, term := range operands[1:] {\n\t\t\t// check if we exceed the overall time limit before running the next query.\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tusedTime := time.Since(start)\n\t\t\t\tsuggestTime := longer(2, usedTime)\n\t\t\t\treturn alertForTimeout(usedTime, suggestTime, r).wrapResults(), nil\n\t\t\tdefault:\n\t\t\t}", "\t\t\ttermResult, err = r.evaluatePatternExpression(ctx, q.MapPattern(term))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif termResult == nil {\n\t\t\t\treturn &SearchResults{}, nil\n\t\t\t}\n\t\t\tif len(termResult.Matches) == 0 {\n\t\t\t\t// termResult might contain an alert.\n\t\t\t\treturn termResult, nil\n\t\t\t}\n\t\t\texhausted = exhausted && !termResult.Stats.IsLimitHit\n\t\t\tresult = intersect(result, termResult)\n\t\t}\n\t\tif exhausted {\n\t\t\tbreak\n\t\t}\n\t\tif len(result.Matches) >= want {\n\t\t\tbreak\n\t\t}\n\t\t// If the result size set is not big enough, and we haven't\n\t\t// exhausted search on all expressions, double the tryCount and search more.\n\t\ttryCount *= 2\n\t\tif tryCount > maxTryCount {\n\t\t\t// We've capped out what we're willing to do, throw alert.\n\t\t\treturn alertForCappedAndExpression().wrapResults(), nil\n\t\t}\n\t}\n\tresult.Stats.IsLimitHit = !exhausted\n\treturn result, nil\n}", "// evaluateOr performs set union on result sets. It collects results for all\n// expressions that are ORed together by searching for each subexpression. If\n// the maximum number of results are reached after evaluating a subexpression,\n// we shortcircuit and return results immediately.\nfunc (r *searchResolver) evaluateOr(ctx context.Context, q query.Basic) (*SearchResults, error) {\n\t// Invariant: this function is only reachable from callers that\n\t// guarantee a root node with one or more operands.\n\toperands := q.Pattern.(query.Operator).Operands", "\twantCount := defaultMaxSearchResults\n\tif count := q.GetCount(); count != \"\" {\n\t\twantCount, _ = strconv.Atoi(count) // Invariant: count is already validated\n\t}", "\tresult := &SearchResults{}\n\tfor _, term := range operands {\n\t\tnew, err := r.evaluatePatternExpression(ctx, q.MapPattern(term))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif new != nil {\n\t\t\tresult = union(result, new)\n\t\t\t// Do not rely on result.Stats.resultCount because it may\n\t\t\t// count non-content matches and there's no easy way to know.\n\t\t\tif len(result.Matches) > wantCount {\n\t\t\t\tresult.Matches = result.Matches[:wantCount]\n\t\t\t\treturn result, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn result, nil\n}", "// invalidateCache invalidates the repo cache if we are preparing to evaluate\n// subexpressions that require resolving potentially disjoint repository data.\nfunc (r *searchResolver) invalidateCache() {\n\tif r.invalidateRepoCache {\n\t\tr.resolved.RepoRevs = nil\n\t\tr.resolved.MissingRepoRevs = nil\n\t\tr.repoErr = nil\n\t}\n}", "// evaluatePatternExpression evaluates a search pattern containing and/or expressions.\nfunc (r *searchResolver) evaluatePatternExpression(ctx context.Context, q query.Basic) (*SearchResults, error) {\n\tswitch term := q.Pattern.(type) {\n\tcase query.Operator:\n\t\tif len(term.Operands) == 0 {\n\t\t\treturn &SearchResults{}, nil\n\t\t}", "\t\tswitch term.Kind {\n\t\tcase query.And:\n\t\t\treturn r.evaluateAnd(ctx, q)\n\t\tcase query.Or:\n\t\t\treturn r.evaluateOr(ctx, q)\n\t\tcase query.Concat:\n\t\t\tr.invalidateCache()\n\t\t\targs, jobs, err := r.toSearchInputs(q.ToParseTree())\n\t\t\tif err != nil {\n\t\t\t\treturn &SearchResults{}, err\n\t\t\t}\n\t\t\treturn r.evaluateLeaf(ctx, args, jobs)\n\t\t}\n\tcase query.Pattern:\n\t\tr.invalidateCache()\n\t\targs, jobs, err := r.toSearchInputs(q.ToParseTree())\n\t\tif err != nil {\n\t\t\treturn &SearchResults{}, err\n\t\t}\n\t\treturn r.evaluateLeaf(ctx, args, jobs)\n\tcase query.Parameter:\n\t\t// evaluatePatternExpression does not process Parameter nodes.\n\t\treturn &SearchResults{}, nil\n\t}\n\t// Unreachable.\n\treturn nil, errors.Errorf(\"unrecognized type %T in evaluatePatternExpression\", q.Pattern)\n}", "// evaluate evaluates all expressions of a search query.\nfunc (r *searchResolver) evaluate(ctx context.Context, q query.Basic) (*SearchResults, error) {\n\tif q.Pattern == nil {\n\t\tr.invalidateCache()\n\t\targs, jobs, err := r.toSearchInputs(query.ToNodes(q.Parameters))\n\t\tif err != nil {\n\t\t\treturn &SearchResults{}, err\n\t\t}\n\t\treturn r.evaluateLeaf(ctx, args, jobs)\n\t}\n\treturn r.evaluatePatternExpression(ctx, q)\n}", "// shouldInvalidateRepoCache returns whether resolved repos should be invalidated when\n// evaluating subexpressions. If a query contains more than one repo, revision,\n// or repogroup field, we should invalidate resolved repos, since multiple\n// repos, revisions, or repogroups imply that different repos may need to be\n// resolved.\nfunc shouldInvalidateRepoCache(plan query.Plan) bool {\n\tvar seenRepo, seenRevision, seenRepoGroup, seenContext int\n\tquery.VisitParameter(plan.ToParseTree(), func(field, _ string, _ bool, _ query.Annotation) {\n\t\tswitch field {\n\t\tcase query.FieldRepo:\n\t\t\tseenRepo += 1\n\t\tcase query.FieldRev:\n\t\t\tseenRevision += 1\n\t\tcase query.FieldRepoGroup:\n\t\t\tseenRepoGroup += 1\n\t\tcase query.FieldContext:\n\t\t\tseenContext += 1\n\t\t}\n\t})\n\treturn seenRepo+seenRepoGroup > 1 || seenRevision > 1 || seenContext > 1\n}", "func logPrometheusBatch(status, alertType, requestSource, requestName string, elapsed time.Duration) {\n\tsearchResponseCounter.WithLabelValues(\n\t\tstatus,\n\t\talertType,\n\t\trequestSource,\n\t\trequestName,\n\t).Inc()", "\tsearchLatencyHistogram.WithLabelValues(\n\t\tstatus,\n\t\talertType,\n\t\trequestSource,\n\t\trequestName,\n\t).Observe(elapsed.Seconds())\n}", "func (r *searchResolver) logBatch(ctx context.Context, srr *SearchResultsResolver, start time.Time, err error) {\n\telapsed := time.Since(start)\n\tif srr != nil {\n\t\tsrr.elapsed = elapsed\n\t\tLogSearchLatency(ctx, r.db, r.SearchInputs, srr.ElapsedMilliseconds())\n\t}", "\tvar status, alertType string\n\tstatus = DetermineStatusForLogs(srr, err)\n\tif srr != nil && srr.SearchResults.Alert != nil {\n\t\talertType = srr.SearchResults.Alert.PrometheusType()\n\t}\n\trequestSource := string(trace.RequestSource(ctx))\n\trequestName := trace.GraphQLRequestName(ctx)\n\tlogPrometheusBatch(status, alertType, requestSource, requestName, elapsed)", "\tisSlow := time.Since(start) > searchlogs.LogSlowSearchesThreshold()\n\tif honey.Enabled() || isSlow {\n\t\tvar n int\n\t\tif srr != nil {\n\t\t\tn = len(srr.Matches)\n\t\t}\n\t\tev := honey.SearchEvent(ctx, honey.SearchEventArgs{\n\t\t\tOriginalQuery: r.rawQuery(),\n\t\t\tTyp: requestName,\n\t\t\tSource: requestSource,\n\t\t\tStatus: status,\n\t\t\tAlertType: alertType,\n\t\t\tDurationMs: elapsed.Milliseconds(),\n\t\t\tResultSize: n,\n\t\t\tError: err,\n\t\t})", "\t\tif honey.Enabled() {\n\t\t\t_ = ev.Send()\n\t\t}", "\t\tif isSlow {\n\t\t\tlog15.Warn(\"slow search request\", searchlogs.MapToLog15Ctx(ev.Fields())...)\n\t\t}\n\t}\n}", "func (r *searchResolver) resultsBatch(ctx context.Context) (*SearchResultsResolver, error) {\n\tstart := time.Now()\n\tsr, err := r.resultsRecursive(ctx, r.Plan)\n\tsrr := r.resultsToResolver(sr)\n\tr.logBatch(ctx, srr, start, err)\n\treturn srr, err\n}", "func (r *searchResolver) resultsStreaming(ctx context.Context) (*SearchResultsResolver, error) {\n\tif !query.IsStreamingCompatible(r.Plan) {\n\t\t// The query is not streaming compatible, but we still want to\n\t\t// use the streaming endpoint. Run a batch search then send the\n\t\t// results back on the stream.\n\t\tendpoint := r.stream\n\t\tr.stream = nil // Disables streaming: backends may not use the endpoint.\n\t\tsrr, err := r.resultsBatch(ctx)\n\t\tif srr != nil {\n\t\t\tendpoint.Send(streaming.SearchEvent{\n\t\t\t\tResults: srr.Matches,\n\t\t\t\tStats: srr.Stats,\n\t\t\t})\n\t\t}\n\t\treturn srr, err\n\t}\n\tif sp, _ := r.Plan.ToParseTree().StringValue(query.FieldSelect); sp != \"\" {\n\t\t// Ensure downstream events sent on the stream are processed by `select:`.\n\t\tselectPath, _ := filter.SelectPathFromString(sp) // Invariant: error already checked\n\t\tr.stream = streaming.WithSelect(r.stream, selectPath)\n\t}\n\tsr, err := r.resultsRecursive(ctx, r.Plan)\n\tsrr := r.resultsToResolver(sr)\n\treturn srr, err\n}", "func (r *searchResolver) resultsToResolver(results *SearchResults) *SearchResultsResolver {\n\tif results == nil {\n\t\tresults = &SearchResults{}\n\t}\n\treturn &SearchResultsResolver{\n\t\tSearchResults: results,\n\t\tlimit: r.MaxResults(),\n\t\tdb: r.db,\n\t\tUserSettings: r.UserSettings,\n\t}\n}", "func (r *searchResolver) Results(ctx context.Context) (*SearchResultsResolver, error) {\n\tif r.stream == nil {\n\t\treturn r.resultsBatch(ctx)\n\t}\n\treturn r.resultsStreaming(ctx)\n}", "// DetermineStatusForLogs determines the final status of a search for logging\n// purposes.\nfunc DetermineStatusForLogs(srr *SearchResultsResolver, err error) string {\n\tswitch {\n\tcase err == context.DeadlineExceeded:\n\t\treturn \"timeout\"\n\tcase err != nil:\n\t\treturn \"error\"\n\tcase srr.Stats.Status.All(search.RepoStatusTimedout) && srr.Stats.Status.Len() == len(srr.Stats.Repos):\n\t\treturn \"timeout\"\n\tcase srr.Stats.Status.Any(search.RepoStatusTimedout):\n\t\treturn \"partial_timeout\"\n\tcase srr.SearchResults.Alert != nil:\n\t\treturn \"alert\"\n\tdefault:\n\t\treturn \"success\"\n\t}\n}", "func (r *searchResolver) resultsRecursive(ctx context.Context, plan query.Plan) (sr *SearchResults, err error) {\n\ttr, ctx := trace.New(ctx, \"Results\", \"\")\n\tdefer func() {\n\t\ttr.SetError(err)\n\t\ttr.Finish()\n\t}()", "\tif shouldInvalidateRepoCache(plan) {\n\t\tr.invalidateRepoCache = true\n\t}", "\twantCount := defaultMaxSearchResults\n\tif count := r.Query.Count(); count != nil {\n\t\twantCount = *count\n\t}", "\tfor _, q := range plan {\n\t\tpredicatePlan, err := substitutePredicates(q, func(pred query.Predicate) (*SearchResults, error) {\n\t\t\t// Disable streaming for subqueries so we can use\n\t\t\t// the results rather than sending them back to the caller\n\t\t\torig := r.stream\n\t\t\tr.stream = nil\n\t\t\tdefer func() { r.stream = orig }()", "\t\t\tr.invalidateRepoCache = true\n\t\t\tplan, err := pred.Plan(q)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn r.resultsRecursive(ctx, plan)\n\t\t})\n\t\tif errors.Is(err, ErrPredicateNoResults) {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\t// Fail if predicate processing fails.\n\t\t\treturn nil, err\n\t\t}\n\t\tif predicatePlan != nil {\n\t\t\t// If a predicate filter generated a new plan, evaluate that plan.\n\t\t\treturn r.resultsRecursive(ctx, predicatePlan)\n\t\t}", "\t\tnewResult, err := r.evaluate(ctx, q)\n\t\tif err != nil {\n\t\t\t// Fail if any subexpression fails.\n\t\t\treturn nil, err\n\t\t}", "\t\tif newResult != nil {\n\t\t\tnewResult.Matches = result.Select(newResult.Matches, q)\n\t\t\tsr = union(sr, newResult)\n\t\t\tif len(sr.Matches) > wantCount {\n\t\t\t\tsr.Matches = sr.Matches[:wantCount]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}", "\tif sr != nil {\n\t\tr.sortResults(sr.Matches)\n\t}\n\treturn sr, err\n}", "// searchResultsToRepoNodes converts a set of search results into repository nodes\n// such that they can be used to replace a repository predicate\nfunc searchResultsToRepoNodes(matches []result.Match) ([]query.Node, error) {\n\tnodes := make([]query.Node, 0, len(matches))\n\tfor _, match := range matches {\n\t\trepoMatch, ok := match.(*result.RepoMatch)\n\t\tif !ok {\n\t\t\treturn nil, errors.Errorf(\"expected type %T, but got %T\", &result.RepoMatch{}, match)\n\t\t}", "\t\tnodes = append(nodes, query.Parameter{\n\t\t\tField: query.FieldRepo,\n\t\t\tValue: \"^\" + regexp.QuoteMeta(string(repoMatch.Name)) + \"$\",\n\t\t})\n\t}", "\treturn nodes, nil\n}", "// searchResultsToFileNodes converts a set of search results into repo/file nodes so that they\n// can replace a file predicate\nfunc searchResultsToFileNodes(matches []result.Match) ([]query.Node, error) {\n\tnodes := make([]query.Node, 0, len(matches))\n\tfor _, match := range matches {\n\t\tfileMatch, ok := match.(*result.FileMatch)\n\t\tif !ok {\n\t\t\treturn nil, errors.Errorf(\"expected type %T, but got %T\", &result.FileMatch{}, match)\n\t\t}", "\t\t// We create AND nodes to match both the repo and the file at the same time so\n\t\t// we don't get files of the same name from different repositories.\n\t\tnodes = append(nodes, query.Operator{\n\t\t\tKind: query.And,\n\t\t\tOperands: []query.Node{\n\t\t\t\tquery.Parameter{\n\t\t\t\t\tField: query.FieldRepo,\n\t\t\t\t\tValue: \"^\" + regexp.QuoteMeta(string(fileMatch.Repo.Name)) + \"$\",\n\t\t\t\t},\n\t\t\t\tquery.Parameter{\n\t\t\t\t\tField: query.FieldFile,\n\t\t\t\t\tValue: \"^\" + regexp.QuoteMeta(fileMatch.Path) + \"$\",\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t}", "\treturn nodes, nil\n}", "// resultsWithTimeoutSuggestion calls doResults, and in case of deadline\n// exceeded returns a search alert with a did-you-mean link for the same\n// query with a longer timeout.\nfunc (r *searchResolver) resultsWithTimeoutSuggestion(ctx context.Context, args *search.TextParameters, jobs []run.Job) (*SearchResults, error) {\n\tstart := time.Now()\n\trr, err := r.doResults(ctx, args, jobs)", "\t// We have an alert for context timeouts and we have a progress\n\t// notification for timeouts. We don't want to show both, so we only show\n\t// it if no repos are marked as timedout. This somewhat couples us to how\n\t// progress notifications work, but this is the third attempt at trying to\n\t// fix this behaviour so we are accepting that.\n\tif errors.Is(err, context.DeadlineExceeded) {\n\t\tif rr == nil || !rr.Stats.Status.Any(search.RepoStatusTimedout) {\n\t\t\tusedTime := time.Since(start)\n\t\t\tsuggestTime := longer(2, usedTime)\n\t\t\treturn alertForTimeout(usedTime, suggestTime, r).wrapResults(), nil\n\t\t} else {\n\t\t\terr = nil\n\t\t}\n\t}", "\treturn rr, err\n}", "// substitutePredicates replaces all the predicates in a query with their expanded form. The predicates\n// are expanded using the doExpand function.\nfunc substitutePredicates(q query.Basic, evaluate func(query.Predicate) (*SearchResults, error)) (query.Plan, error) {\n\tvar topErr error\n\tsuccess := false\n\tnewQ := query.MapParameter(q.ToParseTree(), func(field, value string, neg bool, ann query.Annotation) query.Node {\n\t\torig := query.Parameter{\n\t\t\tField: field,\n\t\t\tValue: value,\n\t\t\tNegated: neg,\n\t\t\tAnnotation: ann,\n\t\t}", "\t\tif !ann.Labels.IsSet(query.IsPredicate) {\n\t\t\treturn orig\n\t\t}", "\t\tif topErr != nil {\n\t\t\treturn orig\n\t\t}", "\t\tname, params := query.ParseAsPredicate(value)\n\t\tpredicate := query.DefaultPredicateRegistry.Get(field, name)\n\t\tpredicate.ParseParams(params)\n\t\tsrr, err := evaluate(predicate)\n\t\tif err != nil {\n\t\t\ttopErr = err\n\t\t\treturn nil\n\t\t}", "\t\tvar nodes []query.Node\n\t\tswitch predicate.Field() {\n\t\tcase query.FieldRepo:\n\t\t\tnodes, err = searchResultsToRepoNodes(srr.Matches)\n\t\t\tif err != nil {\n\t\t\t\ttopErr = err\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase query.FieldFile:\n\t\t\tnodes, err = searchResultsToFileNodes(srr.Matches)\n\t\t\tif err != nil {\n\t\t\t\ttopErr = err\n\t\t\t\treturn nil\n\t\t\t}\n\t\tdefault:\n\t\t\ttopErr = errors.Errorf(\"unsupported predicate result type %q\", predicate.Field())\n\t\t\treturn nil\n\t\t}", "\t\t// If no results are returned, we need to return a sentinel error rather\n\t\t// than an empty expansion because an empty expansion means \"everything\"\n\t\t// rather than \"nothing\".\n\t\tif len(nodes) == 0 {\n\t\t\ttopErr = ErrPredicateNoResults\n\t\t\treturn nil\n\t\t}", "\t\t// A predicate was successfully evaluated and has results.\n\t\tsuccess = true", "\t\t// No need to return an operator for only one result\n\t\tif len(nodes) == 1 {\n\t\t\treturn nodes[0]\n\t\t}", "\t\treturn query.Operator{\n\t\t\tKind: query.Or,\n\t\t\tOperands: nodes,\n\t\t}\n\t})", "\tif topErr != nil || !success {\n\t\treturn nil, topErr\n\t}\n\tplan, err := query.ToPlan(query.Dnf(newQ))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn plan, nil\n}", "var ErrPredicateNoResults = errors.New(\"no results returned for predicate\")", "// longer returns a suggested longer time to wait if the given duration wasn't long enough.\nfunc longer(n int, dt time.Duration) time.Duration {\n\tdt2 := func() time.Duration {\n\t\tNdt := time.Duration(n) * dt\n\t\tdceil := func(x float64) time.Duration {\n\t\t\treturn time.Duration(math.Ceil(x))\n\t\t}\n\t\tswitch {\n\t\tcase math.Floor(Ndt.Hours()) > 0:\n\t\t\treturn dceil(Ndt.Hours()) * time.Hour\n\t\tcase math.Floor(Ndt.Minutes()) > 0:\n\t\t\treturn dceil(Ndt.Minutes()) * time.Minute\n\t\tcase math.Floor(Ndt.Seconds()) > 0:\n\t\t\treturn dceil(Ndt.Seconds()) * time.Second\n\t\tdefault:\n\t\t\treturn 0\n\t\t}\n\t}()\n\tlowest := 2 * time.Second\n\tif dt2 < lowest {\n\t\treturn lowest\n\t}\n\treturn dt2\n}", "type searchResultsStats struct {\n\tJApproximateResultCount string\n\tJSparkline []int32", "\tsr *searchResolver", "\tonce sync.Once\n\tsrs *SearchResultsResolver\n\tsrsErr error\n}", "func (srs *searchResultsStats) ApproximateResultCount() string { return srs.JApproximateResultCount }\nfunc (srs *searchResultsStats) Sparkline() []int32 { return srs.JSparkline }", "var (\n\tsearchResultsStatsCache = rcache.NewWithTTL(\"search_results_stats\", 3600) // 1h\n\tsearchResultsStatsCounter = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"src_graphql_search_results_stats_cache_hit\",\n\t\tHelp: \"Counts cache hits and misses for search results stats (e.g. sparklines).\",\n\t}, []string{\"type\"})\n)", "func (r *searchResolver) Stats(ctx context.Context) (stats *searchResultsStats, err error) {\n\t// Override user context to ensure that stats for this query are cached\n\t// regardless of the user context's cancellation. For example, if\n\t// stats/sparklines are slow to load on the homepage and all users navigate\n\t// away from that page before they load, no user would ever see them and we\n\t// would never cache them. This fixes that by ensuring the first request\n\t// 'kicks off loading' and places the result into cache regardless of\n\t// whether or not the original querier of this information still wants it.\n\toriginalCtx := ctx\n\tctx = context.Background()\n\tctx = opentracing.ContextWithSpan(ctx, opentracing.SpanFromContext(originalCtx))", "\tcacheKey := r.rawQuery()\n\t// Check if value is in the cache.\n\tjsonRes, ok := searchResultsStatsCache.Get(cacheKey)\n\tif ok {\n\t\tsearchResultsStatsCounter.WithLabelValues(\"hit\").Inc()\n\t\tif err := json.Unmarshal(jsonRes, &stats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstats.sr = r\n\t\treturn stats, nil\n\t}", "\t// Calculate value from scratch.\n\tsearchResultsStatsCounter.WithLabelValues(\"miss\").Inc()\n\tattempts := 0\n\tvar v *SearchResultsResolver\n\tfor {\n\t\t// Query search results.\n\t\tvar err error\n\t\targs, jobs, err := r.toSearchInputs(r.Query)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresults, err := r.doResults(ctx, args, jobs)\n\t\tif err != nil {\n\t\t\treturn nil, err // do not cache errors.\n\t\t}\n\t\tv = r.resultsToResolver(results)\n\t\tif v.MatchCount() > 0 {\n\t\t\tbreak\n\t\t}", "\t\tcloning := len(v.Cloning())\n\t\ttimedout := len(v.Timedout())\n\t\tif cloning == 0 && timedout == 0 {\n\t\t\tbreak // zero results, but no cloning or timed out repos. No point in retrying.\n\t\t}", "\t\tif attempts > 5 {\n\t\t\tlog15.Error(\"failed to generate sparkline due to cloning or timed out repos\", \"cloning\", len(v.Cloning()), \"timedout\", len(v.Timedout()))\n\t\t\treturn nil, errors.Errorf(\"failed to generate sparkline due to %d cloning %d timedout repos\", len(v.Cloning()), len(v.Timedout()))\n\t\t}", "\t\t// We didn't find any search results. Some repos are cloning or timed\n\t\t// out, so try again in a few seconds.\n\t\tattempts++\n\t\tlog15.Warn(\"sparkline generation found 0 search results due to cloning or timed out repos (retrying in 5s)\", \"cloning\", len(v.Cloning()), \"timedout\", len(v.Timedout()))\n\t\ttime.Sleep(5 * time.Second)\n\t}", "\tsparkline, err := v.Sparkline(ctx)\n\tif err != nil {\n\t\treturn nil, err // sparkline generation failed, so don't cache.\n\t}\n\tstats = &searchResultsStats{\n\t\tJApproximateResultCount: v.ApproximateResultCount(),\n\t\tJSparkline: sparkline,\n\t\tsr: r,\n\t}", "\t// Store in the cache if we got non-zero results. If we got zero results,\n\t// it should be quick and caching is not desired because e.g. it could be\n\t// a query for a repo that has not been added by the user yet.\n\tif v.ResultCount() > 0 {\n\t\tjsonRes, err = json.Marshal(stats)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsearchResultsStatsCache.Set(cacheKey, jsonRes)\n\t}\n\treturn stats, nil\n}", "// withResultTypes populates the ResultTypes field of args, which drives the kind\n// of search to run (e.g., text search, symbol search).\nfunc withResultTypes(args search.TextParameters, forceTypes result.Types) search.TextParameters {\n\tvar rts result.Types\n\tif forceTypes != 0 {\n\t\trts = forceTypes\n\t} else {\n\t\tstringTypes, _ := args.Query.StringValues(query.FieldType)\n\t\tif len(stringTypes) == 0 {\n\t\t\trts = result.TypeFile | result.TypePath | result.TypeRepo\n\t\t} else {\n\t\t\tfor _, stringType := range stringTypes {\n\t\t\t\trts = rts.With(result.TypeFromString[stringType])\n\t\t\t}\n\t\t}\n\t}", "\tif rts.Has(result.TypeFile) {\n\t\targs.PatternInfo.PatternMatchesContent = true\n\t}", "\tif rts.Has(result.TypePath) {\n\t\targs.PatternInfo.PatternMatchesPath = true\n\t}\n\targs.ResultTypes = rts\n\treturn args\n}", "// doResults is one of the highest level search functions that handles finding results.\n//\n// If forceOnlyResultType is specified, only results of the given type are returned,\n// regardless of what `type:` is specified in the query string.\n//\n// Partial results AND an error may be returned.\nfunc (r *searchResolver) doResults(ctx context.Context, args *search.TextParameters, jobs []run.Job) (res *SearchResults, err error) {\n\ttr, ctx := trace.New(ctx, \"doResults\", r.rawQuery())\n\tdefer func() {\n\t\ttr.SetError(err)\n\t\tif res != nil {\n\t\t\ttr.LazyPrintf(\"matches=%d %s\", len(res.Matches), &res.Stats)\n\t\t}\n\t\ttr.Finish()\n\t}()", "\tstart := time.Now()", "\tctx, cancel := context.WithTimeout(ctx, args.Timeout)\n\tdefer cancel()", "\tlimit := r.MaxResults()\n\ttr.LazyPrintf(\"resultTypes: %s\", args.ResultTypes)\n\tvar (\n\t\trequiredWg sync.WaitGroup\n\t\toptionalWg sync.WaitGroup\n\t)", "\twaitGroup := func(required bool) *sync.WaitGroup {\n\t\tif args.UseFullDeadline {\n\t\t\t// When a custom timeout is specified, all searches are required and get the full timeout.\n\t\t\treturn &requiredWg\n\t\t}\n\t\tif required {\n\t\t\treturn &requiredWg\n\t\t}\n\t\treturn &optionalWg\n\t}", "\t// For streaming search we want to limit based on all results, not just\n\t// per backend. This works better than batch based since we have higher\n\t// defaults.\n\tstream := r.stream\n\tif stream != nil {\n\t\tvar cancelOnLimit context.CancelFunc\n\t\tctx, stream, cancelOnLimit = streaming.WithLimit(ctx, stream, limit)\n\t\tdefer cancelOnLimit()\n\t}", "\tagg := run.NewAggregator(r.db, stream)", "\t// This ensures we properly cleanup in the case of an early return. In\n\t// particular we want to cancel global searches before returning early.\n\thasStartedAllBackends := false\n\tdefer func() {\n\t\tif hasStartedAllBackends {\n\t\t\treturn\n\t\t}\n\t\tcancel()\n\t\trequiredWg.Wait()\n\t\toptionalWg.Wait()\n\t\t_, _, _, _ = agg.Get()\n\t}()", "\targs.RepoOptions = r.toRepoOptions(args.Query, resolveRepositoriesOpts{})", "\t// performance optimization: call zoekt early, resolve repos concurrently, filter\n\t// search results with resolved repos.\n\tif args.Mode == search.ZoektGlobalSearch {\n\t\targsIndexed := *args", "\t\tuserID := int32(0)\n\t\tif envvar.SourcegraphDotComMode() {\n\t\t\tif a := actor.FromContext(ctx); a != nil {\n\t\t\t\tuserID = a.UID\n\t\t\t}\n\t\t}", "\t\t// Get all private repos for the the current actor. On sourcegraph.com, those are\n\t\t// only the repos directly added by the user. Otherwise it's all repos the user has\n\t\t// access to on all connected code hosts / external services.\n\t\tuserPrivateRepos, err := database.Repos(r.db).ListRepoNames(ctx, database.ReposListOptions{", "\t\t\tUserID: userID, // Zero valued when not in sourcegraph.com mode\n\t\t\tOnlyPrivate: true,\n\t\t\tLimitOffset: &database.LimitOffset{Limit: search.SearchLimits(conf.Get()).MaxRepos + 1},\n\t\t\tOnlyForks: args.RepoOptions.OnlyForks,\n\t\t\tNoForks: args.RepoOptions.NoForks,\n\t\t\tOnlyArchived: args.RepoOptions.OnlyArchived,\n\t\t\tNoArchived: args.RepoOptions.NoArchived,", "\t\t})", "\t\tif err != nil {\n\t\t\tlog15.Error(\"doResults: failed to list user private repos\", \"error\", err, \"user-id\", userID)\n\t\t\ttr.LazyPrintf(\"error resolving user private repos: %v\", err)\n\t\t} else {\n\t\t\targsIndexed.UserPrivateRepos = userPrivateRepos\n\t\t}", "\t\twg := waitGroup(true)\n\t\tif args.ResultTypes.Has(result.TypeFile | result.TypePath) {\n\t\t\twg.Add(1)\n\t\t\tgoroutine.Go(func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\t_ = agg.DoFilePathSearch(ctx, &argsIndexed)\n\t\t\t})\n\t\t}", "\t\tif args.ResultTypes.Has(result.TypeSymbol) {\n\t\t\twg.Add(1)\n\t\t\tgoroutine.Go(func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\t_ = agg.DoSymbolSearch(ctx, &argsIndexed, limit)\n\t\t\t})\n\t\t}", "\t\t// On sourcegraph.com and for unscoped queries, determineRepos returns the subset\n\t\t// of indexed default searchrepos. No need to call searcher, because\n\t\t// len(searcherRepos) will always be 0.\n\t\tif envvar.SourcegraphDotComMode() {\n\t\t\targs.Mode = search.SkipUnindexed\n\t\t} else {\n\t\t\targs.Mode = search.SearcherOnly\n\t\t}\n\t}", "\tresolved, err := r.resolveRepositories(ctx, args.RepoOptions)\n\tif err != nil {\n\t\tif alert, err := errorToAlert(err); alert != nil {\n\t\t\treturn alert.wrapResults(), err\n\t\t}\n\t\t// Don't surface context errors to the user.\n\t\tif errors.Is(err, context.Canceled) {\n\t\t\ttr.LazyPrintf(\"context canceled during repo resolution: %v\", err)\n\t\t\toptionalWg.Wait()\n\t\t\trequiredWg.Wait()\n\t\t\treturn r.toSearchResults(ctx, agg)\n\t\t}\n\t\treturn nil, err\n\t}\n\targs.Repos = resolved.RepoRevs", "\ttr.LazyPrintf(\"searching %d repos, %d missing\", len(args.Repos), len(resolved.MissingRepoRevs))\n\tif len(args.Repos) == 0 {\n\t\treturn r.alertForNoResolvedRepos(ctx, args.Query).wrapResults(), nil\n\t}", "\tif len(resolved.MissingRepoRevs) > 0 {\n\t\tagg.Error(&missingRepoRevsError{Missing: resolved.MissingRepoRevs})\n\t\ttr.LazyPrintf(\"adding error for missing repo revs - done\")\n\t}", "\tagg.Send(streaming.SearchEvent{\n\t\tStats: streaming.Stats{\n\t\t\tRepos: resolved.RepoSet,\n\t\t\tExcludedForks: resolved.ExcludedRepos.Forks,\n\t\t\tExcludedArchived: resolved.ExcludedRepos.Archived,\n\t\t},\n\t})\n\ttr.LazyPrintf(\"sending first stats (repos %d, excluded repos %+v) - done\", len(resolved.RepoSet), resolved.ExcludedRepos)", "\tif args.ResultTypes.Has(result.TypeRepo) {\n\t\twg := waitGroup(true)\n\t\twg.Add(1)\n\t\tgoroutine.Go(func() {\n\t\t\tdefer wg.Done()\n\t\t\t_ = agg.DoRepoSearch(ctx, args, int32(limit))\n\t\t})", "\t}", "\tif args.ResultTypes.Has(result.TypeSymbol) && args.PatternInfo.Pattern != \"\" {\n\t\tif args.Mode != search.SkipUnindexed {\n\t\t\twg := waitGroup(args.ResultTypes.Without(result.TypeSymbol) == 0)\n\t\t\twg.Add(1)\n\t\t\tgoroutine.Go(func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\t_ = agg.DoSymbolSearch(ctx, args, limit)\n\t\t\t})\n\t\t}\n\t}", "\tif args.ResultTypes.Has(result.TypeFile | result.TypePath) {\n\t\tif args.Mode != search.SkipUnindexed {\n\t\t\twg := waitGroup(true)\n\t\t\twg.Add(1)\n\t\t\tgoroutine.Go(func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\t_ = agg.DoFilePathSearch(ctx, args)\n\t\t\t})\n\t\t}\n\t}", "\tif featureflag.FromContext(ctx).GetBoolOr(\"cc_commit_search\", false) {\n\t\taddCommitSearch := func(diff bool) {\n\t\t\tj, err := commit.NewSearchJob(args.Query, args.Repos, diff, int(args.PatternInfo.FileMatchLimit))\n\t\t\tif err != nil {\n\t\t\t\tagg.Error(err)\n\t\t\t\treturn\n\t\t\t}", "\t\t\tif err := j.ExpandUsernames(ctx, r.db); err != nil {\n\t\t\t\tagg.Error(err)\n\t\t\t\treturn\n\t\t\t}", "\t\t\tjobs = append(jobs, j)\n\t\t}", "\t\tif args.ResultTypes.Has(result.TypeCommit) {\n\t\t\taddCommitSearch(false)\n\t\t}", "\t\tif args.ResultTypes.Has(result.TypeDiff) {\n\t\t\taddCommitSearch(true)\n\t\t}\n\t} else {\n\t\tif args.ResultTypes.Has(result.TypeDiff) {\n\t\t\twg := waitGroup(args.ResultTypes.Without(result.TypeDiff) == 0)\n\t\t\twg.Add(1)\n\t\t\tgoroutine.Go(func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\t_ = agg.DoDiffSearch(ctx, args)\n\t\t\t})\n\t\t}", "\t\tif args.ResultTypes.Has(result.TypeCommit) {\n\t\t\twg := waitGroup(args.ResultTypes.Without(result.TypeCommit) == 0)\n\t\t\twg.Add(1)\n\t\t\tgoroutine.Go(func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\t_ = agg.DoCommitSearch(ctx, args)\n\t\t\t})", "\t\t}\n\t}", "\twgForJob := func(job run.Job) *sync.WaitGroup {\n\t\tswitch job.Name() {\n\t\tcase \"Diff\":\n\t\t\treturn waitGroup(args.ResultTypes.Without(result.TypeDiff) == 0)\n\t\tcase \"Commit\":\n\t\t\treturn waitGroup(args.ResultTypes.Without(result.TypeCommit) == 0)\n\t\tcase \"Structural\":\n\t\t\treturn waitGroup(true)\n\t\tdefault:\n\t\t\tpanic(\"unknown job name \" + job.Name())\n\t\t}\n\t}", "\t// Start all specific search jobs, if any.\n\tfor _, job := range jobs {\n\t\twg := wgForJob(job)\n\t\twg.Add(1)\n\t\tgoroutine.Go(func() {\n\t\t\tdefer wg.Done()\n\t\t\t_ = agg.DoSearch(ctx, job, args.Mode)\n\t\t})\n\t}", "\thasStartedAllBackends = true", "\t// Wait for required searches.\n\trequiredWg.Wait()", "\t// Give optional searches some minimum budget in case required searches return quickly.\n\t// Cancel all remaining searches after this minimum budget.\n\tbudget := 100 * time.Millisecond\n\telapsed := time.Since(start)\n\ttimer := time.AfterFunc(budget-elapsed, cancel)", "\t// Wait for remaining optional searches to finish or get cancelled.\n\toptionalWg.Wait()", "\ttimer.Stop()", "\treturn r.toSearchResults(ctx, agg)\n}", "// toSearchResults converts an Aggregator to SearchResults.\n//\n// toSearchResults relies on all WaitGroups being done since it relies on\n// collecting from the streams.\nfunc (r *searchResolver) toSearchResults(ctx context.Context, agg *run.Aggregator) (*SearchResults, error) {\n\tmatches, common, matchCount, aggErrs := agg.Get()", "\tif aggErrs == nil {\n\t\treturn nil, errors.New(\"aggErrs should never be nil\")\n\t}", "\tao := alertObserver{\n\t\tInputs: r.SearchInputs,\n\t\thasResults: matchCount > 0,\n\t}\n\tfor _, err := range aggErrs.Errors {\n\t\tao.Error(ctx, err)\n\t}\n\talert, err := ao.Done(&common)", "\tr.sortResults(matches)", "\treturn &SearchResults{\n\t\tMatches: matches,\n\t\tStats: common,\n\t\tAlert: alert,\n\t}, err\n}", "// isContextError returns true if ctx.Err() is not nil or if err\n// is an error caused by context cancelation or timeout.\nfunc isContextError(ctx context.Context, err error) bool {\n\treturn ctx.Err() != nil || errors.IsAny(err, context.Canceled, context.DeadlineExceeded)\n}", "// SearchResultResolver is a resolver for the GraphQL union type `SearchResult`.\n//\n// Supported types:\n//\n// - *RepositoryResolver // repo name match\n// - *fileMatchResolver // text match\n// - *commitSearchResultResolver // diff or commit match\n//\n// Note: Any new result types added here also need to be handled properly in search_results.go:301 (sparklines)\ntype SearchResultResolver interface {\n\tToRepository() (*RepositoryResolver, bool)\n\tToFileMatch() (*FileMatchResolver, bool)\n\tToCommitSearchResult() (*CommitSearchResultResolver, bool)", "\tResultCount() int32\n}", "// compareFileLengths sorts file paths such that they appear earlier if they\n// match file: patterns in the query exactly.\nfunc compareFileLengths(left, right string, exactFilePatterns map[string]struct{}) bool {\n\t_, aMatch := exactFilePatterns[path.Base(left)]\n\t_, bMatch := exactFilePatterns[path.Base(right)]\n\tif aMatch || bMatch {\n\t\tif aMatch && bMatch {\n\t\t\t// Prefer shorter file names (ie root files come first)\n\t\t\tif len(left) != len(right) {\n\t\t\t\treturn len(left) < len(right)\n\t\t\t}\n\t\t\treturn left < right\n\t\t}\n\t\t// Prefer exact match\n\t\treturn aMatch\n\t}\n\treturn left < right\n}", "func compareDates(left, right *time.Time) bool {\n\tif left == nil || right == nil {\n\t\treturn left != nil // Place the value that is defined first.\n\t}\n\treturn left.After(*right)\n}", "// compareSearchResults sorts repository matches, file matches, and commits.\n// Repositories and filenames are sorted alphabetically. As a refinement, if any\n// filename matches a value in a non-empty set exactFilePatterns, then such\n// filenames are listed earlier.\n//\n// Commits are sorted by date. Commits are not associated with searchrepos, and\n// will always list after repository or file match results, if any.\nfunc compareSearchResults(left, right result.Match, exactFilePatterns map[string]struct{}) bool {\n\tsortKeys := func(match result.Match) (string, string, *time.Time) {\n\t\tswitch r := match.(type) {\n\t\tcase *result.RepoMatch:\n\t\t\treturn string(r.Name), \"\", nil\n\t\tcase *result.FileMatch:\n\t\t\treturn string(r.Repo.Name), r.Path, nil\n\t\tcase *result.CommitMatch:\n\t\t\t// Commits are relatively sorted by date, and after repo\n\t\t\t// or path names. We use ~ as the key for repo and\n\t\t\t// paths,lexicographically last in ASCII.\n\t\t\treturn \"~\", \"~\", &r.Commit.Author.Date\n\t\t}\n\t\t// Unreachable.\n\t\tpanic(\"unreachable: compareSearchResults expects RepositoryResolver, FileMatchResolver, or CommitSearchResultResolver\")\n\t}", "\tarepo, afile, adate := sortKeys(left)\n\tbrepo, bfile, bdate := sortKeys(right)", "\tif arepo == brepo {\n\t\tif len(exactFilePatterns) == 0 {\n\t\t\tif afile != bfile {\n\t\t\t\treturn afile < bfile\n\t\t\t}\n\t\t\treturn compareDates(adate, bdate)\n\t\t}\n\t\treturn compareFileLengths(afile, bfile, exactFilePatterns)\n\t}\n\treturn arepo < brepo\n}", "func (r *searchResolver) sortResults(results []result.Match) {\n\tvar exactPatterns map[string]struct{}\n\tif getBoolPtr(r.UserSettings.SearchGlobbing, false) {\n\t\texactPatterns = r.getExactFilePatterns()\n\t}\n\tsort.Slice(results, func(i, j int) bool { return compareSearchResults(results[i], results[j], exactPatterns) })\n}", "// getExactFilePatterns returns the set of file patterns without glob syntax.\nfunc (r *searchResolver) getExactFilePatterns() map[string]struct{} {\n\tm := map[string]struct{}{}\n\tquery.VisitField(\n\t\tr.Query,\n\t\tquery.FieldFile,\n\t\tfunc(value string, negated bool, annotation query.Annotation) {\n\t\t\toriginalValue := r.OriginalQuery[annotation.Range.Start.Column+len(query.FieldFile)+1 : annotation.Range.End.Column]\n\t\t\tif !negated && query.ContainsNoGlobSyntax(originalValue) {\n\t\t\t\tm[originalValue] = struct{}{}\n\t\t\t}\n\t\t})\n\treturn m\n}" ]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [26, 1516, 36, 537], "buggy_code_start_loc": [26, 39, 33, 537], "filenames": ["CHANGELOG.md", "cmd/frontend/graphqlbackend/search_results.go", "dev/gqltest/README.md", "dev/gqltest/search_test.go"], "fixing_code_end_loc": [35, 1518, 36, 544], "fixing_code_start_loc": [27, 40, 33, 538], "message": "Sourcegraph is a code search and navigation engine. Sourcegraph prior to version 3.33.2 is vulnerable to a side-channel attack where strings in private source code could be guessed by an authenticated but unauthorized actor. This issue affects the Saved Searches and Code Monitoring features. A successful attack would require an authenticated bad actor to create many Saved Searches or Code Monitors to receive confirmation that a specific string exists. This could allow an attacker to guess formatted tokens in source code, such as API keys. This issue was patched in version 3.33.2 and any future versions of Sourcegraph. We strongly encourage upgrading to secure versions. If you are unable to, you may disable Saved Searches and Code Monitors.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sourcegraph:sourcegraph:*:*:*:*:*:*:*:*", "matchCriteriaId": "8AC67147-DAE3-4326-9027-0DEB53C55D32", "versionEndExcluding": "3.33.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Sourcegraph is a code search and navigation engine. Sourcegraph prior to version 3.33.2 is vulnerable to a side-channel attack where strings in private source code could be guessed by an authenticated but unauthorized actor. This issue affects the Saved Searches and Code Monitoring features. A successful attack would require an authenticated bad actor to create many Saved Searches or Code Monitors to receive confirmation that a specific string exists. This could allow an attacker to guess formatted tokens in source code, such as API keys. This issue was patched in version 3.33.2 and any future versions of Sourcegraph. We strongly encourage upgrading to secure versions. If you are unable to, you may disable Saved Searches and Code Monitors."}, {"lang": "es", "value": "Sourcegraph es un motor de b\u00fasqueda y navegaci\u00f3n de c\u00f3digo. Sourcegraph versiones anteriores a 3.33.2 es vulnerable a un ataque de canal lateral en el que las cadenas del c\u00f3digo fuente privado podr\u00edan ser adivinadas por un actor autenticado pero no autorizado. Este problema afecta a las funciones de B\u00fasquedas Guardadas y Monitorizaci\u00f3n de C\u00f3digo. Un ataque con \u00e9xito requerir\u00eda que un actor malo autenticado creara muchas B\u00fasquedas Guardadas o Monitores de C\u00f3digo para recibir la confirmaci\u00f3n de que una cadena espec\u00edfica esta presente. Esto podr\u00eda permitir a un atacante adivinar los tokens formateados en el c\u00f3digo fuente, como las claves de la API. Este problema ha sido parcheado en la versi\u00f3n 3.33.2 y en las futuras versiones de Sourcegraph. Recomendamos encarecidamente que se actualice a las versiones seguras. Si no puede hacerlo, puede deshabilitar las B\u00fasquedas Guardadas y los Monitores de C\u00f3digo"}], "evaluatorComment": null, "id": "CVE-2021-43823", "lastModified": "2021-12-16T15:00:25.970", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Primary"}]}, "published": "2021-12-13T20:15:07.813", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/sourcegraph/sourcegraph/commit/a88d90a8302c492282186d39718cd8fb093c14fa"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/sourcegraph/sourcegraph/security/advisories/GHSA-cpq7-hmvv-29w9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-203"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/sourcegraph/sourcegraph/commit/a88d90a8302c492282186d39718cd8fb093c14fa"}, "type": "CWE-203"}
326
Determine whether the {function_name} code is vulnerable or not.
[ "package graphqlbackend", "import (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"math\"\n\t\"path\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"", "\t\"github.com/cockroachdb/errors\"\n\t\"github.com/inconshreveable/log15\"\n\t\"github.com/neelance/parallel\"\n\t\"github.com/opentracing/opentracing-go\"\n\t\"github.com/opentracing/opentracing-go/ext\"\n\totlog \"github.com/opentracing/opentracing-go/log\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promauto\"", "\t\"github.com/sourcegraph/sourcegraph/cmd/frontend/envvar\"\n\tsearchlogs \"github.com/sourcegraph/sourcegraph/cmd/frontend/internal/search/logs\"\n\t\"github.com/sourcegraph/sourcegraph/internal/actor\"\n\t\"github.com/sourcegraph/sourcegraph/internal/api\"\n\t\"github.com/sourcegraph/sourcegraph/internal/conf\"\n\t\"github.com/sourcegraph/sourcegraph/internal/database\"\n\t\"github.com/sourcegraph/sourcegraph/internal/database/dbutil\"\n\t\"github.com/sourcegraph/sourcegraph/internal/deviceid\"\n\t\"github.com/sourcegraph/sourcegraph/internal/featureflag\"\n\t\"github.com/sourcegraph/sourcegraph/internal/goroutine\"\n\t\"github.com/sourcegraph/sourcegraph/internal/honey\"\n\t\"github.com/sourcegraph/sourcegraph/internal/rcache\"\n\t\"github.com/sourcegraph/sourcegraph/internal/search\"\n\t\"github.com/sourcegraph/sourcegraph/internal/search/commit\"\n\t\"github.com/sourcegraph/sourcegraph/internal/search/filter\"\n\t\"github.com/sourcegraph/sourcegraph/internal/search/query\"", "\t\"github.com/sourcegraph/sourcegraph/internal/search/repos\"", "\tsearchrepos \"github.com/sourcegraph/sourcegraph/internal/search/repos\"\n\t\"github.com/sourcegraph/sourcegraph/internal/search/result\"\n\t\"github.com/sourcegraph/sourcegraph/internal/search/run\"\n\t\"github.com/sourcegraph/sourcegraph/internal/search/searchcontexts\"\n\t\"github.com/sourcegraph/sourcegraph/internal/search/streaming\"\n\t\"github.com/sourcegraph/sourcegraph/internal/search/unindexed\"\n\t\"github.com/sourcegraph/sourcegraph/internal/trace\"\n\t\"github.com/sourcegraph/sourcegraph/internal/trace/ot\"\n\t\"github.com/sourcegraph/sourcegraph/internal/types\"\n\t\"github.com/sourcegraph/sourcegraph/internal/usagestats\"\n\t\"github.com/sourcegraph/sourcegraph/internal/vcs/git\"\n\t\"github.com/sourcegraph/sourcegraph/schema\"\n)", "func (c *SearchResultsResolver) LimitHit() bool {\n\treturn c.Stats.IsLimitHit || (c.limit > 0 && len(c.Matches) > c.limit)\n}", "func (c *SearchResultsResolver) Repositories() []*RepositoryResolver {\n\trepos := c.Stats.Repos\n\tresolvers := make([]*RepositoryResolver, 0, len(repos))\n\tfor _, r := range repos {\n\t\tresolvers = append(resolvers, NewRepositoryResolver(c.db, r.ToRepo()))\n\t}\n\tsort.Slice(resolvers, func(a, b int) bool {\n\t\treturn resolvers[a].ID() < resolvers[b].ID()\n\t})\n\treturn resolvers\n}", "func (c *SearchResultsResolver) RepositoriesCount() int32 {\n\treturn int32(len(c.Stats.Repos))\n}", "func (c *SearchResultsResolver) repositoryResolvers(mask search.RepoStatus) []*RepositoryResolver {\n\tvar resolvers []*RepositoryResolver\n\tc.Stats.Status.Filter(mask, func(id api.RepoID) {\n\t\tif r, ok := c.Stats.Repos[id]; ok {\n\t\t\tresolvers = append(resolvers, NewRepositoryResolver(c.db, r.ToRepo()))\n\t\t}\n\t})\n\tsort.Slice(resolvers, func(a, b int) bool {\n\t\treturn resolvers[a].ID() < resolvers[b].ID()\n\t})\n\treturn resolvers\n}", "func (c *SearchResultsResolver) Cloning() []*RepositoryResolver {\n\treturn c.repositoryResolvers(search.RepoStatusCloning)\n}", "func (c *SearchResultsResolver) Missing() []*RepositoryResolver {\n\treturn c.repositoryResolvers(search.RepoStatusMissing)\n}", "func (c *SearchResultsResolver) Timedout() []*RepositoryResolver {\n\treturn c.repositoryResolvers(search.RepoStatusTimedout)\n}", "func (c *SearchResultsResolver) IndexUnavailable() bool {\n\treturn c.Stats.IsIndexUnavailable\n}", "// SearchResultsResolver is a resolver for the GraphQL type `SearchResults`\ntype SearchResultsResolver struct {\n\tdb dbutil.DB\n\t*SearchResults", "\t// limit is the maximum number of SearchResults to send back to the user.\n\tlimit int", "\t// The time it took to compute all results.\n\telapsed time.Duration", "\t// cache for user settings. Ideally this should be set just once in the code path\n\t// by an upstream resolver\n\tUserSettings *schema.Settings\n}", "type SearchResults struct {\n\tMatches []result.Match\n\tStats streaming.Stats\n\tAlert *searchAlert\n}", "// Results are the results found by the search. It respects the limits set. To\n// access all results directly access the SearchResults field.\nfunc (sr *SearchResultsResolver) Results() []SearchResultResolver {\n\tlimited := sr.Matches\n\tif sr.limit > 0 && sr.limit < len(sr.Matches) {\n\t\tlimited = sr.Matches[:sr.limit]\n\t}", "\treturn matchesToResolvers(sr.db, limited)\n}", "func matchesToResolvers(db dbutil.DB, matches []result.Match) []SearchResultResolver {\n\ttype repoKey struct {\n\t\tName types.RepoName\n\t\tRev string\n\t}\n\trepoResolvers := make(map[repoKey]*RepositoryResolver, 10)\n\tgetRepoResolver := func(repoName types.RepoName, rev string) *RepositoryResolver {\n\t\tif existing, ok := repoResolvers[repoKey{repoName, rev}]; ok {\n\t\t\treturn existing\n\t\t}\n\t\tresolver := NewRepositoryResolver(db, repoName.ToRepo())\n\t\tresolver.RepoMatch.Rev = rev\n\t\trepoResolvers[repoKey{repoName, rev}] = resolver\n\t\treturn resolver\n\t}", "\tresolvers := make([]SearchResultResolver, 0, len(matches))\n\tfor _, match := range matches {\n\t\tswitch v := match.(type) {\n\t\tcase *result.FileMatch:\n\t\t\tresolvers = append(resolvers, &FileMatchResolver{\n\t\t\t\tdb: db,\n\t\t\t\tFileMatch: *v,\n\t\t\t\tRepoResolver: getRepoResolver(v.Repo, \"\"),\n\t\t\t})\n\t\tcase *result.RepoMatch:\n\t\t\tresolvers = append(resolvers, getRepoResolver(v.RepoName(), v.Rev))\n\t\tcase *result.CommitMatch:\n\t\t\tresolvers = append(resolvers, &CommitSearchResultResolver{\n\t\t\t\tdb: db,\n\t\t\t\tCommitMatch: *v,\n\t\t\t})\n\t\t}\n\t}\n\treturn resolvers\n}", "func (sr *SearchResultsResolver) MatchCount() int32 {\n\tvar totalResults int\n\tfor _, result := range sr.Matches {\n\t\ttotalResults += result.ResultCount()\n\t}\n\treturn int32(totalResults)\n}", "// Deprecated. Prefer MatchCount.\nfunc (sr *SearchResultsResolver) ResultCount() int32 { return sr.MatchCount() }", "func (sr *SearchResultsResolver) ApproximateResultCount() string {\n\tcount := sr.MatchCount()\n\tif sr.LimitHit() || sr.Stats.Status.Any(search.RepoStatusCloning|search.RepoStatusTimedout) {\n\t\treturn fmt.Sprintf(\"%d+\", count)\n\t}\n\treturn strconv.Itoa(int(count))\n}", "func (sr *SearchResultsResolver) Alert() *searchAlert { return sr.SearchResults.Alert }", "func (sr *SearchResultsResolver) ElapsedMilliseconds() int32 {\n\treturn int32(sr.elapsed.Milliseconds())\n}", "func (sr *SearchResultsResolver) DynamicFilters(ctx context.Context) []*searchFilterResolver {\n\ttr, ctx := trace.New(ctx, \"DynamicFilters\", \"\", trace.Tag{Key: \"resolver\", Value: \"SearchResultsResolver\"})\n\tdefer func() {\n\t\ttr.Finish()\n\t}()", "\tglobbing := false\n\t// For search, sr.userSettings is set in (r *searchResolver) Results(ctx\n\t// context.Context). However we might regress on that or call DynamicFilters from\n\t// other code paths. Hence we fallback to accessing the user settings directly.\n\tif sr.UserSettings != nil {\n\t\tglobbing = getBoolPtr(sr.UserSettings.SearchGlobbing, false)\n\t} else {\n\t\tsettings, err := decodedViewerFinalSettings(ctx, sr.db)\n\t\tif err != nil {\n\t\t\tlog15.Warn(\"DynamicFilters: could not get user settings from database\")\n\t\t} else {\n\t\t\tglobbing = getBoolPtr(settings.SearchGlobbing, false)\n\t\t}\n\t}\n\ttr.LogFields(otlog.Bool(\"globbing\", globbing))", "\tfilters := streaming.SearchFilters{\n\t\tGlobbing: globbing,\n\t}\n\tfilters.Update(streaming.SearchEvent{\n\t\tResults: sr.Matches,\n\t\tStats: sr.Stats,\n\t})", "\tvar resolvers []*searchFilterResolver\n\tfor _, f := range filters.Compute() {\n\t\tresolvers = append(resolvers, &searchFilterResolver{filter: *f})\n\t}\n\treturn resolvers\n}", "type searchFilterResolver struct {\n\tfilter streaming.Filter\n}", "func (sf *searchFilterResolver) Value() string {\n\treturn sf.filter.Value\n}", "func (sf *searchFilterResolver) Label() string {\n\treturn sf.filter.Label\n}", "func (sf *searchFilterResolver) Count() int32 {\n\treturn int32(sf.filter.Count)\n}", "func (sf *searchFilterResolver) LimitHit() bool {\n\treturn sf.filter.IsLimitHit\n}", "func (sf *searchFilterResolver) Kind() string {\n\treturn sf.filter.Kind\n}", "// blameFileMatch blames the specified file match to produce the time at which\n// the first line match inside of it was authored.\nfunc (sr *SearchResultsResolver) blameFileMatch(ctx context.Context, fm *result.FileMatch) (t time.Time, err error) {\n\tspan, ctx := ot.StartSpanFromContext(ctx, \"blameFileMatch\")\n\tdefer func() {\n\t\tif err != nil {\n\t\t\text.Error.Set(span, true)\n\t\t\tspan.SetTag(\"err\", err.Error())\n\t\t}\n\t\tspan.Finish()\n\t}()", "\t// Blame the first line match.\n\tif len(fm.LineMatches) == 0 {\n\t\t// No line match\n\t\treturn time.Time{}, nil\n\t}\n\tlm := fm.LineMatches[0]\n\thunks, err := git.BlameFile(ctx, fm.Repo.Name, fm.Path, &git.BlameOptions{\n\t\tNewestCommit: fm.CommitID,\n\t\tStartLine: int(lm.LineNumber),\n\t\tEndLine: int(lm.LineNumber),\n\t})\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}", "\treturn hunks[0].Author.Date, nil\n}", "func (sr *SearchResultsResolver) Sparkline(ctx context.Context) (sparkline []int32, err error) {\n\tvar (\n\t\tdays = 30 // number of days the sparkline represents\n\t\tmaxBlame = 100 // maximum number of file results to blame for date/time information.\n\t\trun = parallel.NewRun(8) // number of concurrent blame ops\n\t)", "\tvar (\n\t\tsparklineMu sync.Mutex\n\t\tblameOps = 0\n\t)\n\tsparkline = make([]int32, days)\n\taddPoint := func(t time.Time) {\n\t\t// Check if the author date of the search result is inside of our sparkline\n\t\t// timerange.\n\t\tnow := time.Now()\n\t\tif t.Before(now.Add(-time.Duration(len(sparkline)) * 24 * time.Hour)) {\n\t\t\t// Outside the range of the sparkline.\n\t\t\treturn\n\t\t}\n\t\tsparklineMu.Lock()\n\t\tdefer sparklineMu.Unlock()\n\t\tfor n := range sparkline {\n\t\t\td1 := now.Add(-time.Duration(n) * 24 * time.Hour)\n\t\t\td2 := now.Add(-time.Duration(n-1) * 24 * time.Hour)\n\t\t\tif t.After(d1) && t.Before(d2) {\n\t\t\t\tsparkline[n]++ // on the nth day\n\t\t\t}\n\t\t}\n\t}", "\t// Consider all of our search results as a potential data point in our\n\t// sparkline.\nloop:\n\tfor _, r := range sr.Matches {\n\t\tr := r // shadow so it doesn't change in the goroutine\n\t\tswitch m := r.(type) {\n\t\tcase *result.RepoMatch:\n\t\t\t// We don't care about repo results here.\n\t\t\tcontinue\n\t\tcase *result.CommitMatch:\n\t\t\t// Diff searches are cheap, because we implicitly have author date info.\n\t\t\taddPoint(m.Commit.Author.Date)\n\t\tcase *result.FileMatch:\n\t\t\t// File match searches are more expensive, because we must blame the\n\t\t\t// (first) line in order to know its placement in our sparkline.\n\t\t\tblameOps++\n\t\t\tif blameOps > maxBlame {\n\t\t\t\t// We have exceeded our budget of blame operations for\n\t\t\t\t// calculating this sparkline, so don't do any more file match\n\t\t\t\t// blaming.\n\t\t\t\tcontinue loop\n\t\t\t}", "\t\t\trun.Acquire()\n\t\t\tgoroutine.Go(func() {\n\t\t\t\tdefer run.Release()", "\t\t\t\t// Blame the file match in order to retrieve date informatino.\n\t\t\t\tvar err error\n\t\t\t\tt, err := sr.blameFileMatch(ctx, m)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog15.Warn(\"failed to blame fileMatch during sparkline generation\", \"error\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\taddPoint(t)\n\t\t\t})\n\t\tdefault:\n\t\t\tpanic(\"SearchResults.Sparkline unexpected union type state\")\n\t\t}\n\t}\n\tspan := opentracing.SpanFromContext(ctx)\n\tspan.SetTag(\"blame_ops\", blameOps)\n\treturn sparkline, nil\n}", "var (\n\tsearchResponseCounter = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"src_graphql_search_response\",\n\t\tHelp: \"Number of searches that have ended in the given status (success, error, timeout, partial_timeout).\",\n\t}, []string{\"status\", \"alert_type\", \"source\", \"request_name\"})", "\tsearchLatencyHistogram = promauto.NewHistogramVec(prometheus.HistogramOpts{\n\t\tName: \"src_search_response_latency_seconds\",\n\t\tHelp: \"Search response latencies in seconds that have ended in the given status (success, error, timeout, partial_timeout).\",\n\t\tBuckets: []float64{0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 30},\n\t}, []string{\"status\", \"alert_type\", \"source\", \"request_name\"})\n)", "// LogSearchLatency records search durations in the event database. This\n// function may only be called after a search result is performed, because it\n// relies on the invariant that query and pattern error checking has already\n// been performed.\nfunc LogSearchLatency(ctx context.Context, db dbutil.DB, si *run.SearchInputs, durationMs int32) {\n\ttr, ctx := trace.New(ctx, \"LogSearchLatency\", \"\")\n\tdefer func() {\n\t\ttr.Finish()\n\t}()\n\tvar types []string\n\tresultTypes, _ := si.Query.StringValues(query.FieldType)\n\tfor _, typ := range resultTypes {\n\t\tswitch typ {\n\t\tcase \"repo\", \"symbol\", \"diff\", \"commit\":\n\t\t\ttypes = append(types, typ)\n\t\tcase \"path\":\n\t\t\t// Map type:path to file\n\t\t\ttypes = append(types, \"file\")\n\t\tcase \"file\":\n\t\t\tswitch {\n\t\t\tcase si.PatternType == query.SearchTypeStructural:\n\t\t\t\ttypes = append(types, \"structural\")\n\t\t\tcase si.PatternType == query.SearchTypeLiteral:\n\t\t\t\ttypes = append(types, \"literal\")\n\t\t\tcase si.PatternType == query.SearchTypeRegex:\n\t\t\t\ttypes = append(types, \"regexp\")\n\t\t\t}\n\t\t}\n\t}", "\t// Don't record composite searches that specify more than one type:\n\t// because we can't break down the search timings into multiple\n\t// categories.\n\tif len(types) > 1 {\n\t\treturn\n\t}", "\tq, err := query.ToBasicQuery(si.Query)\n\tif err != nil {\n\t\t// Can't convert to a basic query, can't guarantee accurate reporting.\n\t\treturn\n\t}\n\tif !query.IsPatternAtom(q) {\n\t\t// Not an atomic pattern, can't guarantee accurate reporting.\n\t\treturn\n\t}", "\t// If no type: was explicitly specified, infer the result type.\n\tif len(types) == 0 {\n\t\t// If a pattern was specified, a content search happened.\n\t\tif q.IsLiteral() {\n\t\t\ttypes = append(types, \"literal\")\n\t\t} else if q.IsRegexp() {\n\t\t\ttypes = append(types, \"regexp\")\n\t\t} else if q.IsStructural() {\n\t\t\ttypes = append(types, \"structural\")\n\t\t} else if len(si.Query.Fields()[\"file\"]) > 0 {\n\t\t\t// No search pattern specified and file: is specified.\n\t\t\ttypes = append(types, \"file\")\n\t\t} else {\n\t\t\t// No search pattern or file: is specified, assume repo.\n\t\t\t// This includes accounting for searches of fields that\n\t\t\t// specify repohasfile: and repohascommitafter:.\n\t\t\ttypes = append(types, \"repo\")\n\t\t}\n\t}", "\t// Only log the time if we successfully resolved one search type.\n\tif len(types) == 1 {\n\t\ta := actor.FromContext(ctx)\n\t\tif a.IsAuthenticated() {\n\t\t\tvalue := fmt.Sprintf(`{\"durationMs\": %d}`, durationMs)\n\t\t\teventName := fmt.Sprintf(\"search.latencies.%s\", types[0])\n\t\t\tfeatureFlags := featureflag.FromContext(ctx)\n\t\t\tgo func() {\n\t\t\t\terr := usagestats.LogBackendEvent(db, a.UID, deviceid.FromContext(ctx), eventName, json.RawMessage(value), json.RawMessage(value), featureFlags, nil)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog15.Warn(\"Could not log search latency\", \"err\", err)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t}\n}", "func (r *searchResolver) toRepoOptions(q query.Q, opts resolveRepositoriesOpts) search.RepoOptions {\n\trepoFilters, minusRepoFilters := q.Repositories()\n\tif opts.effectiveRepoFieldValues != nil {\n\t\trepoFilters = opts.effectiveRepoFieldValues\n\t}\n\trepoGroupFilters, _ := q.StringValues(query.FieldRepoGroup)", "\tvar settingForks, settingArchived bool\n\tif v := r.UserSettings.SearchIncludeForks; v != nil {\n\t\tsettingForks = *v\n\t}\n\tif v := r.UserSettings.SearchIncludeArchived; v != nil {\n\t\tsettingArchived = *v\n\t}", "\tfork := query.No\n\tif searchrepos.ExactlyOneRepo(repoFilters) || settingForks {\n\t\t// fork defaults to No unless either of:\n\t\t// (1) exactly one repo is being searched, or\n\t\t// (2) user/org/global setting includes forks\n\t\tfork = query.Yes\n\t}\n\tif setFork := q.Fork(); setFork != nil {\n\t\tfork = *setFork\n\t}", "\tarchived := query.No\n\tif searchrepos.ExactlyOneRepo(repoFilters) || settingArchived {\n\t\t// archived defaults to No unless either of:\n\t\t// (1) exactly one repo is being searched, or\n\t\t// (2) user/org/global setting includes archives in all searches\n\t\tarchived = query.Yes\n\t}\n\tif setArchived := q.Archived(); setArchived != nil {\n\t\tarchived = *setArchived\n\t}", "\tvisibilityStr, _ := q.StringValue(query.FieldVisibility)\n\tvisibility := query.ParseVisibility(visibilityStr)", "\tcommitAfter, _ := q.StringValue(query.FieldRepoHasCommitAfter)\n\tsearchContextSpec, _ := q.StringValue(query.FieldContext)", "\tvar versionContextName string\n\tif r.VersionContext != nil {\n\t\tversionContextName = *r.VersionContext\n\t}", "\tvar CacheLookup bool\n\tif len(opts.effectiveRepoFieldValues) == 0 && opts.limit == 0 {\n\t\t// indicates resolving repositories should cache DB lookups\n\t\tCacheLookup = true\n\t}", "\treturn search.RepoOptions{\n\t\tRepoFilters: repoFilters,\n\t\tMinusRepoFilters: minusRepoFilters,\n\t\tRepoGroupFilters: repoGroupFilters,\n\t\tVersionContextName: versionContextName,\n\t\tSearchContextSpec: searchContextSpec,\n\t\tUserSettings: r.UserSettings,\n\t\tOnlyForks: fork == query.Only,\n\t\tNoForks: fork == query.No,\n\t\tOnlyArchived: archived == query.Only,\n\t\tNoArchived: archived == query.No,\n\t\tVisibility: visibility,\n\t\tCommitAfter: commitAfter,\n\t\tQuery: q,\n\t\tRanked: true,\n\t\tLimit: opts.limit,\n\t\tCacheLookup: CacheLookup,\n\t}\n}", "func withMode(args search.TextParameters, st query.SearchType, versionContext *string) search.TextParameters {\n\tisGlobalSearch := func() bool {\n\t\tif st == query.SearchTypeStructural {\n\t\t\treturn false\n\t\t}\n\t\tif versionContext != nil && *versionContext != \"\" {\n\t\t\treturn false\n\t\t}", "\t\treturn query.ForAll(args.Query, func(node query.Node) bool {\n\t\t\tn, ok := node.(query.Parameter)\n\t\t\tif !ok {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tswitch n.Field {\n\t\t\tcase query.FieldContext:\n\t\t\t\treturn searchcontexts.IsGlobalSearchContextSpec(n.Value)\n\t\t\tcase query.FieldRepo:\n\t\t\t\t// We allow -repo: in global search.\n\t\t\t\treturn n.Negated\n\t\t\tcase\n\t\t\t\tquery.FieldRepoGroup,\n\t\t\t\tquery.FieldRepoHasFile:\n\t\t\t\treturn false\n\t\t\tdefault:\n\t\t\t\treturn true\n\t\t\t}\n\t\t})\n\t}", "\thasGlobalSearchResultType := args.ResultTypes.Has(result.TypeFile | result.TypePath | result.TypeSymbol)\n\tisIndexedSearch := args.PatternInfo.Index != query.No\n\tisEmpty := args.PatternInfo.Pattern == \"\" && args.PatternInfo.ExcludePattern == \"\" && len(args.PatternInfo.IncludePatterns) == 0\n\tif isGlobalSearch() && isIndexedSearch && hasGlobalSearchResultType && !isEmpty {\n\t\targs.Mode = search.ZoektGlobalSearch\n\t}\n\tif isEmpty {\n\t\targs.Mode = search.SkipUnindexed\n\t}\n\treturn args\n}", "// toSearchInputs converts a query parse tree to the _internal_ representation\n// needed to run a search. To understand why this conversion matters, think\n// about the fact that the query parse tree doesn't know anything about our\n// backends or architecture. It doesn't decide certain defaults, like whether we\n// should return multiple result types (pattern matches content, or a file name,\n// or a repo name). If we want to optimize a Sourcegraph query parse tree for a\n// particular backend (e.g., skip repository resolution and just run a Zoekt\n// query on all indexed repositories) then we need to convert our tree to\n// Zoekt's internal inputs and representation. These concerns are all handled by\n// toSearchInputs.\n//\n// toSearchInputs returns a tuple (args, jobs). `args` represents a large,\n// generic object with many values that drive search logic all over the backend.\n// `jobs` represent search objects with a Run() method that directly runs the\n// search job in question, and the job object comprises only the state to run\n// that search. Currently, both return values may be used to evaluate a search.\n// In time, it is expected that toSearchInputs migrates to return _only_ jobs,\n// where each job contains its separate state for that kind of search and\n// backend. To complete the migration to jobs in phases, `args` is kept\n// backwards compatibility and represents a generic search.\nfunc (r *searchResolver) toSearchInputs(q query.Q) (*search.TextParameters, []run.Job, error) {\n\tb, err := query.ToBasicQuery(q)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tp := search.ToTextPatternInfo(b, r.protocol(), query.Identity)", "\tforceResultTypes := result.TypeEmpty\n\tif r.PatternType == query.SearchTypeStructural {\n\t\tif p.Pattern == \"\" {\n\t\t\t// Fallback to literal search for searching repos and files if\n\t\t\t// the structural search pattern is empty.\n\t\t\tr.PatternType = query.SearchTypeLiteral\n\t\t\tp.IsStructuralPat = false\n\t\t\tforceResultTypes = result.Types(0)\n\t\t} else {\n\t\t\tforceResultTypes = result.TypeStructural\n\t\t}\n\t}", "\targs := search.TextParameters{\n\t\tPatternInfo: p,\n\t\tQuery: q,\n\t\tTimeout: search.TimeoutDuration(b),", "\t\t// UseFullDeadline if timeout: set or we are streaming.\n\t\tUseFullDeadline: q.Timeout() != nil || q.Count() != nil || r.stream != nil,", "\t\tZoekt: r.zoekt,\n\t\tSearcherURLs: r.searcherURLs,\n\t}\n\targs = withResultTypes(args, forceResultTypes)\n\targs = withMode(args, r.PatternType, r.VersionContext)", "\tvar jobs []run.Job\n\t{\n\t\t// This code block creates search jobs under specific\n\t\t// conditions, and depending on generic process of `args` above.\n\t\t// It which specializes search logic in doResults. In time, all\n\t\t// of the above logic should be used to create search jobs\n\t\t// across all of Sourcegraph.\n\t\tif r.PatternType == query.SearchTypeStructural && p.Pattern != \"\" {\n\t\t\tjobs = append(jobs, &unindexed.StructuralSearch{\n\t\t\t\tRepoFetcher: unindexed.NewRepoFetcher(r.stream, &args),\n\t\t\t\tMode: args.Mode,\n\t\t\t\tSearcherArgs: search.SearcherParameters{\n\t\t\t\t\tSearcherURLs: args.SearcherURLs,\n\t\t\t\t\tPatternInfo: args.PatternInfo,\n\t\t\t\t\tUseFullDeadline: args.UseFullDeadline,\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t}\n\treturn &args, jobs, nil\n}", "// evaluateLeaf performs a single search operation and corresponds to the\n// evaluation of leaf expression in a query.\nfunc (r *searchResolver) evaluateLeaf(ctx context.Context, args *search.TextParameters, jobs []run.Job) (_ *SearchResults, err error) {\n\ttr, ctx := trace.New(ctx, \"evaluateLeaf\", \"\")\n\tdefer func() {\n\t\ttr.SetError(err)\n\t\ttr.Finish()\n\t}()", "\treturn r.resultsWithTimeoutSuggestion(ctx, args, jobs)\n}", "// union returns the union of two sets of search results and merges common search data.\nfunc union(left, right *SearchResults) *SearchResults {\n\tif right == nil {\n\t\treturn left\n\t}\n\tif left == nil {\n\t\treturn right\n\t}", "\tif left.Matches != nil && right.Matches != nil {\n\t\tleft.Matches = result.Union(left.Matches, right.Matches)\n\t\tleft.Stats.Update(&right.Stats)\n\t\treturn left\n\t} else if right.Matches != nil {\n\t\treturn right\n\t}\n\treturn left\n}", "// intersect returns the intersection of two sets of search result content\n// matches, based on whether a single file path contains content matches in both sets.\nfunc intersect(left, right *SearchResults) *SearchResults {\n\tif left == nil || right == nil {\n\t\treturn nil\n\t}\n\tleft.Matches = result.Intersect(left.Matches, right.Matches)\n\tleft.Stats.Update(&right.Stats)\n\treturn left\n}", "// evaluateAnd performs set intersection on result sets. It collects results for\n// all expressions that are ANDed together by searching for each subexpression\n// and then intersects those results that are in the same repo/file path. To\n// collect N results for count:N, we need to opportunistically ask for more than\n// N results for each subexpression (since intersect can never yield more than N,\n// and likely yields fewer than N results). If the intersection does not yield N\n// results, and is not exhaustive for every expression, we rerun the search by\n// doubling count again.\nfunc (r *searchResolver) evaluateAnd(ctx context.Context, q query.Basic) (*SearchResults, error) {\n\tstart := time.Now()", "\t// Invariant: this function is only reachable from callers that\n\t// guarantee a root node with one or more operands.\n\toperands := q.Pattern.(query.Operator).Operands", "\tvar (\n\t\terr error\n\t\tresult *SearchResults\n\t\ttermResult *SearchResults\n\t)", "\t// The number of results we want. Note that for intersect, this number\n\t// corresponds to documents, not line matches. By default, we ask for at\n\t// least 5 documents to fill the result page.\n\twant := 5\n\t// The fraction of file matches two terms share on average\n\taverageIntersection := 0.05\n\t// When we retry, cap the max search results we request for each expression\n\t// if search continues to not be exhaustive. Alert if exceeded.\n\tmaxTryCount := 40000", "\t// Set an overall timeout in addition to the timeouts that are set for leaf-requests.\n\tctx, cancel := context.WithTimeout(ctx, search.TimeoutDuration(q))\n\tdefer cancel()", "\tif count := q.GetCount(); count != \"\" {\n\t\twant, _ = strconv.Atoi(count) // Invariant: count is validated.\n\t} else {\n\t\tq = q.AddCount(want)\n\t}", "\t// tryCount starts small but grows exponentially with the number of operands. It is capped at maxTryCount.\n\ttryCount := int(math.Floor(float64(want) / math.Pow(averageIntersection, float64(len(operands)-1))))\n\tif tryCount > maxTryCount {\n\t\ttryCount = maxTryCount\n\t}", "\tvar exhausted bool\n\tfor {\n\t\tq = q.MapCount(tryCount)\n\t\tresult, err = r.evaluatePatternExpression(ctx, q.MapPattern(operands[0]))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif result == nil {\n\t\t\treturn &SearchResults{}, nil\n\t\t}\n\t\tif len(result.Matches) == 0 {\n\t\t\t// result might contain an alert.\n\t\t\treturn result, nil\n\t\t}\n\t\texhausted = !result.Stats.IsLimitHit\n\t\tfor _, term := range operands[1:] {\n\t\t\t// check if we exceed the overall time limit before running the next query.\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tusedTime := time.Since(start)\n\t\t\t\tsuggestTime := longer(2, usedTime)\n\t\t\t\treturn alertForTimeout(usedTime, suggestTime, r).wrapResults(), nil\n\t\t\tdefault:\n\t\t\t}", "\t\t\ttermResult, err = r.evaluatePatternExpression(ctx, q.MapPattern(term))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif termResult == nil {\n\t\t\t\treturn &SearchResults{}, nil\n\t\t\t}\n\t\t\tif len(termResult.Matches) == 0 {\n\t\t\t\t// termResult might contain an alert.\n\t\t\t\treturn termResult, nil\n\t\t\t}\n\t\t\texhausted = exhausted && !termResult.Stats.IsLimitHit\n\t\t\tresult = intersect(result, termResult)\n\t\t}\n\t\tif exhausted {\n\t\t\tbreak\n\t\t}\n\t\tif len(result.Matches) >= want {\n\t\t\tbreak\n\t\t}\n\t\t// If the result size set is not big enough, and we haven't\n\t\t// exhausted search on all expressions, double the tryCount and search more.\n\t\ttryCount *= 2\n\t\tif tryCount > maxTryCount {\n\t\t\t// We've capped out what we're willing to do, throw alert.\n\t\t\treturn alertForCappedAndExpression().wrapResults(), nil\n\t\t}\n\t}\n\tresult.Stats.IsLimitHit = !exhausted\n\treturn result, nil\n}", "// evaluateOr performs set union on result sets. It collects results for all\n// expressions that are ORed together by searching for each subexpression. If\n// the maximum number of results are reached after evaluating a subexpression,\n// we shortcircuit and return results immediately.\nfunc (r *searchResolver) evaluateOr(ctx context.Context, q query.Basic) (*SearchResults, error) {\n\t// Invariant: this function is only reachable from callers that\n\t// guarantee a root node with one or more operands.\n\toperands := q.Pattern.(query.Operator).Operands", "\twantCount := defaultMaxSearchResults\n\tif count := q.GetCount(); count != \"\" {\n\t\twantCount, _ = strconv.Atoi(count) // Invariant: count is already validated\n\t}", "\tresult := &SearchResults{}\n\tfor _, term := range operands {\n\t\tnew, err := r.evaluatePatternExpression(ctx, q.MapPattern(term))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif new != nil {\n\t\t\tresult = union(result, new)\n\t\t\t// Do not rely on result.Stats.resultCount because it may\n\t\t\t// count non-content matches and there's no easy way to know.\n\t\t\tif len(result.Matches) > wantCount {\n\t\t\t\tresult.Matches = result.Matches[:wantCount]\n\t\t\t\treturn result, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn result, nil\n}", "// invalidateCache invalidates the repo cache if we are preparing to evaluate\n// subexpressions that require resolving potentially disjoint repository data.\nfunc (r *searchResolver) invalidateCache() {\n\tif r.invalidateRepoCache {\n\t\tr.resolved.RepoRevs = nil\n\t\tr.resolved.MissingRepoRevs = nil\n\t\tr.repoErr = nil\n\t}\n}", "// evaluatePatternExpression evaluates a search pattern containing and/or expressions.\nfunc (r *searchResolver) evaluatePatternExpression(ctx context.Context, q query.Basic) (*SearchResults, error) {\n\tswitch term := q.Pattern.(type) {\n\tcase query.Operator:\n\t\tif len(term.Operands) == 0 {\n\t\t\treturn &SearchResults{}, nil\n\t\t}", "\t\tswitch term.Kind {\n\t\tcase query.And:\n\t\t\treturn r.evaluateAnd(ctx, q)\n\t\tcase query.Or:\n\t\t\treturn r.evaluateOr(ctx, q)\n\t\tcase query.Concat:\n\t\t\tr.invalidateCache()\n\t\t\targs, jobs, err := r.toSearchInputs(q.ToParseTree())\n\t\t\tif err != nil {\n\t\t\t\treturn &SearchResults{}, err\n\t\t\t}\n\t\t\treturn r.evaluateLeaf(ctx, args, jobs)\n\t\t}\n\tcase query.Pattern:\n\t\tr.invalidateCache()\n\t\targs, jobs, err := r.toSearchInputs(q.ToParseTree())\n\t\tif err != nil {\n\t\t\treturn &SearchResults{}, err\n\t\t}\n\t\treturn r.evaluateLeaf(ctx, args, jobs)\n\tcase query.Parameter:\n\t\t// evaluatePatternExpression does not process Parameter nodes.\n\t\treturn &SearchResults{}, nil\n\t}\n\t// Unreachable.\n\treturn nil, errors.Errorf(\"unrecognized type %T in evaluatePatternExpression\", q.Pattern)\n}", "// evaluate evaluates all expressions of a search query.\nfunc (r *searchResolver) evaluate(ctx context.Context, q query.Basic) (*SearchResults, error) {\n\tif q.Pattern == nil {\n\t\tr.invalidateCache()\n\t\targs, jobs, err := r.toSearchInputs(query.ToNodes(q.Parameters))\n\t\tif err != nil {\n\t\t\treturn &SearchResults{}, err\n\t\t}\n\t\treturn r.evaluateLeaf(ctx, args, jobs)\n\t}\n\treturn r.evaluatePatternExpression(ctx, q)\n}", "// shouldInvalidateRepoCache returns whether resolved repos should be invalidated when\n// evaluating subexpressions. If a query contains more than one repo, revision,\n// or repogroup field, we should invalidate resolved repos, since multiple\n// repos, revisions, or repogroups imply that different repos may need to be\n// resolved.\nfunc shouldInvalidateRepoCache(plan query.Plan) bool {\n\tvar seenRepo, seenRevision, seenRepoGroup, seenContext int\n\tquery.VisitParameter(plan.ToParseTree(), func(field, _ string, _ bool, _ query.Annotation) {\n\t\tswitch field {\n\t\tcase query.FieldRepo:\n\t\t\tseenRepo += 1\n\t\tcase query.FieldRev:\n\t\t\tseenRevision += 1\n\t\tcase query.FieldRepoGroup:\n\t\t\tseenRepoGroup += 1\n\t\tcase query.FieldContext:\n\t\t\tseenContext += 1\n\t\t}\n\t})\n\treturn seenRepo+seenRepoGroup > 1 || seenRevision > 1 || seenContext > 1\n}", "func logPrometheusBatch(status, alertType, requestSource, requestName string, elapsed time.Duration) {\n\tsearchResponseCounter.WithLabelValues(\n\t\tstatus,\n\t\talertType,\n\t\trequestSource,\n\t\trequestName,\n\t).Inc()", "\tsearchLatencyHistogram.WithLabelValues(\n\t\tstatus,\n\t\talertType,\n\t\trequestSource,\n\t\trequestName,\n\t).Observe(elapsed.Seconds())\n}", "func (r *searchResolver) logBatch(ctx context.Context, srr *SearchResultsResolver, start time.Time, err error) {\n\telapsed := time.Since(start)\n\tif srr != nil {\n\t\tsrr.elapsed = elapsed\n\t\tLogSearchLatency(ctx, r.db, r.SearchInputs, srr.ElapsedMilliseconds())\n\t}", "\tvar status, alertType string\n\tstatus = DetermineStatusForLogs(srr, err)\n\tif srr != nil && srr.SearchResults.Alert != nil {\n\t\talertType = srr.SearchResults.Alert.PrometheusType()\n\t}\n\trequestSource := string(trace.RequestSource(ctx))\n\trequestName := trace.GraphQLRequestName(ctx)\n\tlogPrometheusBatch(status, alertType, requestSource, requestName, elapsed)", "\tisSlow := time.Since(start) > searchlogs.LogSlowSearchesThreshold()\n\tif honey.Enabled() || isSlow {\n\t\tvar n int\n\t\tif srr != nil {\n\t\t\tn = len(srr.Matches)\n\t\t}\n\t\tev := honey.SearchEvent(ctx, honey.SearchEventArgs{\n\t\t\tOriginalQuery: r.rawQuery(),\n\t\t\tTyp: requestName,\n\t\t\tSource: requestSource,\n\t\t\tStatus: status,\n\t\t\tAlertType: alertType,\n\t\t\tDurationMs: elapsed.Milliseconds(),\n\t\t\tResultSize: n,\n\t\t\tError: err,\n\t\t})", "\t\tif honey.Enabled() {\n\t\t\t_ = ev.Send()\n\t\t}", "\t\tif isSlow {\n\t\t\tlog15.Warn(\"slow search request\", searchlogs.MapToLog15Ctx(ev.Fields())...)\n\t\t}\n\t}\n}", "func (r *searchResolver) resultsBatch(ctx context.Context) (*SearchResultsResolver, error) {\n\tstart := time.Now()\n\tsr, err := r.resultsRecursive(ctx, r.Plan)\n\tsrr := r.resultsToResolver(sr)\n\tr.logBatch(ctx, srr, start, err)\n\treturn srr, err\n}", "func (r *searchResolver) resultsStreaming(ctx context.Context) (*SearchResultsResolver, error) {\n\tif !query.IsStreamingCompatible(r.Plan) {\n\t\t// The query is not streaming compatible, but we still want to\n\t\t// use the streaming endpoint. Run a batch search then send the\n\t\t// results back on the stream.\n\t\tendpoint := r.stream\n\t\tr.stream = nil // Disables streaming: backends may not use the endpoint.\n\t\tsrr, err := r.resultsBatch(ctx)\n\t\tif srr != nil {\n\t\t\tendpoint.Send(streaming.SearchEvent{\n\t\t\t\tResults: srr.Matches,\n\t\t\t\tStats: srr.Stats,\n\t\t\t})\n\t\t}\n\t\treturn srr, err\n\t}\n\tif sp, _ := r.Plan.ToParseTree().StringValue(query.FieldSelect); sp != \"\" {\n\t\t// Ensure downstream events sent on the stream are processed by `select:`.\n\t\tselectPath, _ := filter.SelectPathFromString(sp) // Invariant: error already checked\n\t\tr.stream = streaming.WithSelect(r.stream, selectPath)\n\t}\n\tsr, err := r.resultsRecursive(ctx, r.Plan)\n\tsrr := r.resultsToResolver(sr)\n\treturn srr, err\n}", "func (r *searchResolver) resultsToResolver(results *SearchResults) *SearchResultsResolver {\n\tif results == nil {\n\t\tresults = &SearchResults{}\n\t}\n\treturn &SearchResultsResolver{\n\t\tSearchResults: results,\n\t\tlimit: r.MaxResults(),\n\t\tdb: r.db,\n\t\tUserSettings: r.UserSettings,\n\t}\n}", "func (r *searchResolver) Results(ctx context.Context) (*SearchResultsResolver, error) {\n\tif r.stream == nil {\n\t\treturn r.resultsBatch(ctx)\n\t}\n\treturn r.resultsStreaming(ctx)\n}", "// DetermineStatusForLogs determines the final status of a search for logging\n// purposes.\nfunc DetermineStatusForLogs(srr *SearchResultsResolver, err error) string {\n\tswitch {\n\tcase err == context.DeadlineExceeded:\n\t\treturn \"timeout\"\n\tcase err != nil:\n\t\treturn \"error\"\n\tcase srr.Stats.Status.All(search.RepoStatusTimedout) && srr.Stats.Status.Len() == len(srr.Stats.Repos):\n\t\treturn \"timeout\"\n\tcase srr.Stats.Status.Any(search.RepoStatusTimedout):\n\t\treturn \"partial_timeout\"\n\tcase srr.SearchResults.Alert != nil:\n\t\treturn \"alert\"\n\tdefault:\n\t\treturn \"success\"\n\t}\n}", "func (r *searchResolver) resultsRecursive(ctx context.Context, plan query.Plan) (sr *SearchResults, err error) {\n\ttr, ctx := trace.New(ctx, \"Results\", \"\")\n\tdefer func() {\n\t\ttr.SetError(err)\n\t\ttr.Finish()\n\t}()", "\tif shouldInvalidateRepoCache(plan) {\n\t\tr.invalidateRepoCache = true\n\t}", "\twantCount := defaultMaxSearchResults\n\tif count := r.Query.Count(); count != nil {\n\t\twantCount = *count\n\t}", "\tfor _, q := range plan {\n\t\tpredicatePlan, err := substitutePredicates(q, func(pred query.Predicate) (*SearchResults, error) {\n\t\t\t// Disable streaming for subqueries so we can use\n\t\t\t// the results rather than sending them back to the caller\n\t\t\torig := r.stream\n\t\t\tr.stream = nil\n\t\t\tdefer func() { r.stream = orig }()", "\t\t\tr.invalidateRepoCache = true\n\t\t\tplan, err := pred.Plan(q)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn r.resultsRecursive(ctx, plan)\n\t\t})\n\t\tif errors.Is(err, ErrPredicateNoResults) {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\t// Fail if predicate processing fails.\n\t\t\treturn nil, err\n\t\t}\n\t\tif predicatePlan != nil {\n\t\t\t// If a predicate filter generated a new plan, evaluate that plan.\n\t\t\treturn r.resultsRecursive(ctx, predicatePlan)\n\t\t}", "\t\tnewResult, err := r.evaluate(ctx, q)\n\t\tif err != nil {\n\t\t\t// Fail if any subexpression fails.\n\t\t\treturn nil, err\n\t\t}", "\t\tif newResult != nil {\n\t\t\tnewResult.Matches = result.Select(newResult.Matches, q)\n\t\t\tsr = union(sr, newResult)\n\t\t\tif len(sr.Matches) > wantCount {\n\t\t\t\tsr.Matches = sr.Matches[:wantCount]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}", "\tif sr != nil {\n\t\tr.sortResults(sr.Matches)\n\t}\n\treturn sr, err\n}", "// searchResultsToRepoNodes converts a set of search results into repository nodes\n// such that they can be used to replace a repository predicate\nfunc searchResultsToRepoNodes(matches []result.Match) ([]query.Node, error) {\n\tnodes := make([]query.Node, 0, len(matches))\n\tfor _, match := range matches {\n\t\trepoMatch, ok := match.(*result.RepoMatch)\n\t\tif !ok {\n\t\t\treturn nil, errors.Errorf(\"expected type %T, but got %T\", &result.RepoMatch{}, match)\n\t\t}", "\t\tnodes = append(nodes, query.Parameter{\n\t\t\tField: query.FieldRepo,\n\t\t\tValue: \"^\" + regexp.QuoteMeta(string(repoMatch.Name)) + \"$\",\n\t\t})\n\t}", "\treturn nodes, nil\n}", "// searchResultsToFileNodes converts a set of search results into repo/file nodes so that they\n// can replace a file predicate\nfunc searchResultsToFileNodes(matches []result.Match) ([]query.Node, error) {\n\tnodes := make([]query.Node, 0, len(matches))\n\tfor _, match := range matches {\n\t\tfileMatch, ok := match.(*result.FileMatch)\n\t\tif !ok {\n\t\t\treturn nil, errors.Errorf(\"expected type %T, but got %T\", &result.FileMatch{}, match)\n\t\t}", "\t\t// We create AND nodes to match both the repo and the file at the same time so\n\t\t// we don't get files of the same name from different repositories.\n\t\tnodes = append(nodes, query.Operator{\n\t\t\tKind: query.And,\n\t\t\tOperands: []query.Node{\n\t\t\t\tquery.Parameter{\n\t\t\t\t\tField: query.FieldRepo,\n\t\t\t\t\tValue: \"^\" + regexp.QuoteMeta(string(fileMatch.Repo.Name)) + \"$\",\n\t\t\t\t},\n\t\t\t\tquery.Parameter{\n\t\t\t\t\tField: query.FieldFile,\n\t\t\t\t\tValue: \"^\" + regexp.QuoteMeta(fileMatch.Path) + \"$\",\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t}", "\treturn nodes, nil\n}", "// resultsWithTimeoutSuggestion calls doResults, and in case of deadline\n// exceeded returns a search alert with a did-you-mean link for the same\n// query with a longer timeout.\nfunc (r *searchResolver) resultsWithTimeoutSuggestion(ctx context.Context, args *search.TextParameters, jobs []run.Job) (*SearchResults, error) {\n\tstart := time.Now()\n\trr, err := r.doResults(ctx, args, jobs)", "\t// We have an alert for context timeouts and we have a progress\n\t// notification for timeouts. We don't want to show both, so we only show\n\t// it if no repos are marked as timedout. This somewhat couples us to how\n\t// progress notifications work, but this is the third attempt at trying to\n\t// fix this behaviour so we are accepting that.\n\tif errors.Is(err, context.DeadlineExceeded) {\n\t\tif rr == nil || !rr.Stats.Status.Any(search.RepoStatusTimedout) {\n\t\t\tusedTime := time.Since(start)\n\t\t\tsuggestTime := longer(2, usedTime)\n\t\t\treturn alertForTimeout(usedTime, suggestTime, r).wrapResults(), nil\n\t\t} else {\n\t\t\terr = nil\n\t\t}\n\t}", "\treturn rr, err\n}", "// substitutePredicates replaces all the predicates in a query with their expanded form. The predicates\n// are expanded using the doExpand function.\nfunc substitutePredicates(q query.Basic, evaluate func(query.Predicate) (*SearchResults, error)) (query.Plan, error) {\n\tvar topErr error\n\tsuccess := false\n\tnewQ := query.MapParameter(q.ToParseTree(), func(field, value string, neg bool, ann query.Annotation) query.Node {\n\t\torig := query.Parameter{\n\t\t\tField: field,\n\t\t\tValue: value,\n\t\t\tNegated: neg,\n\t\t\tAnnotation: ann,\n\t\t}", "\t\tif !ann.Labels.IsSet(query.IsPredicate) {\n\t\t\treturn orig\n\t\t}", "\t\tif topErr != nil {\n\t\t\treturn orig\n\t\t}", "\t\tname, params := query.ParseAsPredicate(value)\n\t\tpredicate := query.DefaultPredicateRegistry.Get(field, name)\n\t\tpredicate.ParseParams(params)\n\t\tsrr, err := evaluate(predicate)\n\t\tif err != nil {\n\t\t\ttopErr = err\n\t\t\treturn nil\n\t\t}", "\t\tvar nodes []query.Node\n\t\tswitch predicate.Field() {\n\t\tcase query.FieldRepo:\n\t\t\tnodes, err = searchResultsToRepoNodes(srr.Matches)\n\t\t\tif err != nil {\n\t\t\t\ttopErr = err\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase query.FieldFile:\n\t\t\tnodes, err = searchResultsToFileNodes(srr.Matches)\n\t\t\tif err != nil {\n\t\t\t\ttopErr = err\n\t\t\t\treturn nil\n\t\t\t}\n\t\tdefault:\n\t\t\ttopErr = errors.Errorf(\"unsupported predicate result type %q\", predicate.Field())\n\t\t\treturn nil\n\t\t}", "\t\t// If no results are returned, we need to return a sentinel error rather\n\t\t// than an empty expansion because an empty expansion means \"everything\"\n\t\t// rather than \"nothing\".\n\t\tif len(nodes) == 0 {\n\t\t\ttopErr = ErrPredicateNoResults\n\t\t\treturn nil\n\t\t}", "\t\t// A predicate was successfully evaluated and has results.\n\t\tsuccess = true", "\t\t// No need to return an operator for only one result\n\t\tif len(nodes) == 1 {\n\t\t\treturn nodes[0]\n\t\t}", "\t\treturn query.Operator{\n\t\t\tKind: query.Or,\n\t\t\tOperands: nodes,\n\t\t}\n\t})", "\tif topErr != nil || !success {\n\t\treturn nil, topErr\n\t}\n\tplan, err := query.ToPlan(query.Dnf(newQ))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn plan, nil\n}", "var ErrPredicateNoResults = errors.New(\"no results returned for predicate\")", "// longer returns a suggested longer time to wait if the given duration wasn't long enough.\nfunc longer(n int, dt time.Duration) time.Duration {\n\tdt2 := func() time.Duration {\n\t\tNdt := time.Duration(n) * dt\n\t\tdceil := func(x float64) time.Duration {\n\t\t\treturn time.Duration(math.Ceil(x))\n\t\t}\n\t\tswitch {\n\t\tcase math.Floor(Ndt.Hours()) > 0:\n\t\t\treturn dceil(Ndt.Hours()) * time.Hour\n\t\tcase math.Floor(Ndt.Minutes()) > 0:\n\t\t\treturn dceil(Ndt.Minutes()) * time.Minute\n\t\tcase math.Floor(Ndt.Seconds()) > 0:\n\t\t\treturn dceil(Ndt.Seconds()) * time.Second\n\t\tdefault:\n\t\t\treturn 0\n\t\t}\n\t}()\n\tlowest := 2 * time.Second\n\tif dt2 < lowest {\n\t\treturn lowest\n\t}\n\treturn dt2\n}", "type searchResultsStats struct {\n\tJApproximateResultCount string\n\tJSparkline []int32", "\tsr *searchResolver", "\tonce sync.Once\n\tsrs *SearchResultsResolver\n\tsrsErr error\n}", "func (srs *searchResultsStats) ApproximateResultCount() string { return srs.JApproximateResultCount }\nfunc (srs *searchResultsStats) Sparkline() []int32 { return srs.JSparkline }", "var (\n\tsearchResultsStatsCache = rcache.NewWithTTL(\"search_results_stats\", 3600) // 1h\n\tsearchResultsStatsCounter = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"src_graphql_search_results_stats_cache_hit\",\n\t\tHelp: \"Counts cache hits and misses for search results stats (e.g. sparklines).\",\n\t}, []string{\"type\"})\n)", "func (r *searchResolver) Stats(ctx context.Context) (stats *searchResultsStats, err error) {\n\t// Override user context to ensure that stats for this query are cached\n\t// regardless of the user context's cancellation. For example, if\n\t// stats/sparklines are slow to load on the homepage and all users navigate\n\t// away from that page before they load, no user would ever see them and we\n\t// would never cache them. This fixes that by ensuring the first request\n\t// 'kicks off loading' and places the result into cache regardless of\n\t// whether or not the original querier of this information still wants it.\n\toriginalCtx := ctx\n\tctx = context.Background()\n\tctx = opentracing.ContextWithSpan(ctx, opentracing.SpanFromContext(originalCtx))", "\tcacheKey := r.rawQuery()\n\t// Check if value is in the cache.\n\tjsonRes, ok := searchResultsStatsCache.Get(cacheKey)\n\tif ok {\n\t\tsearchResultsStatsCounter.WithLabelValues(\"hit\").Inc()\n\t\tif err := json.Unmarshal(jsonRes, &stats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstats.sr = r\n\t\treturn stats, nil\n\t}", "\t// Calculate value from scratch.\n\tsearchResultsStatsCounter.WithLabelValues(\"miss\").Inc()\n\tattempts := 0\n\tvar v *SearchResultsResolver\n\tfor {\n\t\t// Query search results.\n\t\tvar err error\n\t\targs, jobs, err := r.toSearchInputs(r.Query)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresults, err := r.doResults(ctx, args, jobs)\n\t\tif err != nil {\n\t\t\treturn nil, err // do not cache errors.\n\t\t}\n\t\tv = r.resultsToResolver(results)\n\t\tif v.MatchCount() > 0 {\n\t\t\tbreak\n\t\t}", "\t\tcloning := len(v.Cloning())\n\t\ttimedout := len(v.Timedout())\n\t\tif cloning == 0 && timedout == 0 {\n\t\t\tbreak // zero results, but no cloning or timed out repos. No point in retrying.\n\t\t}", "\t\tif attempts > 5 {\n\t\t\tlog15.Error(\"failed to generate sparkline due to cloning or timed out repos\", \"cloning\", len(v.Cloning()), \"timedout\", len(v.Timedout()))\n\t\t\treturn nil, errors.Errorf(\"failed to generate sparkline due to %d cloning %d timedout repos\", len(v.Cloning()), len(v.Timedout()))\n\t\t}", "\t\t// We didn't find any search results. Some repos are cloning or timed\n\t\t// out, so try again in a few seconds.\n\t\tattempts++\n\t\tlog15.Warn(\"sparkline generation found 0 search results due to cloning or timed out repos (retrying in 5s)\", \"cloning\", len(v.Cloning()), \"timedout\", len(v.Timedout()))\n\t\ttime.Sleep(5 * time.Second)\n\t}", "\tsparkline, err := v.Sparkline(ctx)\n\tif err != nil {\n\t\treturn nil, err // sparkline generation failed, so don't cache.\n\t}\n\tstats = &searchResultsStats{\n\t\tJApproximateResultCount: v.ApproximateResultCount(),\n\t\tJSparkline: sparkline,\n\t\tsr: r,\n\t}", "\t// Store in the cache if we got non-zero results. If we got zero results,\n\t// it should be quick and caching is not desired because e.g. it could be\n\t// a query for a repo that has not been added by the user yet.\n\tif v.ResultCount() > 0 {\n\t\tjsonRes, err = json.Marshal(stats)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsearchResultsStatsCache.Set(cacheKey, jsonRes)\n\t}\n\treturn stats, nil\n}", "// withResultTypes populates the ResultTypes field of args, which drives the kind\n// of search to run (e.g., text search, symbol search).\nfunc withResultTypes(args search.TextParameters, forceTypes result.Types) search.TextParameters {\n\tvar rts result.Types\n\tif forceTypes != 0 {\n\t\trts = forceTypes\n\t} else {\n\t\tstringTypes, _ := args.Query.StringValues(query.FieldType)\n\t\tif len(stringTypes) == 0 {\n\t\t\trts = result.TypeFile | result.TypePath | result.TypeRepo\n\t\t} else {\n\t\t\tfor _, stringType := range stringTypes {\n\t\t\t\trts = rts.With(result.TypeFromString[stringType])\n\t\t\t}\n\t\t}\n\t}", "\tif rts.Has(result.TypeFile) {\n\t\targs.PatternInfo.PatternMatchesContent = true\n\t}", "\tif rts.Has(result.TypePath) {\n\t\targs.PatternInfo.PatternMatchesPath = true\n\t}\n\targs.ResultTypes = rts\n\treturn args\n}", "// doResults is one of the highest level search functions that handles finding results.\n//\n// If forceOnlyResultType is specified, only results of the given type are returned,\n// regardless of what `type:` is specified in the query string.\n//\n// Partial results AND an error may be returned.\nfunc (r *searchResolver) doResults(ctx context.Context, args *search.TextParameters, jobs []run.Job) (res *SearchResults, err error) {\n\ttr, ctx := trace.New(ctx, \"doResults\", r.rawQuery())\n\tdefer func() {\n\t\ttr.SetError(err)\n\t\tif res != nil {\n\t\t\ttr.LazyPrintf(\"matches=%d %s\", len(res.Matches), &res.Stats)\n\t\t}\n\t\ttr.Finish()\n\t}()", "\tstart := time.Now()", "\tctx, cancel := context.WithTimeout(ctx, args.Timeout)\n\tdefer cancel()", "\tlimit := r.MaxResults()\n\ttr.LazyPrintf(\"resultTypes: %s\", args.ResultTypes)\n\tvar (\n\t\trequiredWg sync.WaitGroup\n\t\toptionalWg sync.WaitGroup\n\t)", "\twaitGroup := func(required bool) *sync.WaitGroup {\n\t\tif args.UseFullDeadline {\n\t\t\t// When a custom timeout is specified, all searches are required and get the full timeout.\n\t\t\treturn &requiredWg\n\t\t}\n\t\tif required {\n\t\t\treturn &requiredWg\n\t\t}\n\t\treturn &optionalWg\n\t}", "\t// For streaming search we want to limit based on all results, not just\n\t// per backend. This works better than batch based since we have higher\n\t// defaults.\n\tstream := r.stream\n\tif stream != nil {\n\t\tvar cancelOnLimit context.CancelFunc\n\t\tctx, stream, cancelOnLimit = streaming.WithLimit(ctx, stream, limit)\n\t\tdefer cancelOnLimit()\n\t}", "\tagg := run.NewAggregator(r.db, stream)", "\t// This ensures we properly cleanup in the case of an early return. In\n\t// particular we want to cancel global searches before returning early.\n\thasStartedAllBackends := false\n\tdefer func() {\n\t\tif hasStartedAllBackends {\n\t\t\treturn\n\t\t}\n\t\tcancel()\n\t\trequiredWg.Wait()\n\t\toptionalWg.Wait()\n\t\t_, _, _, _ = agg.Get()\n\t}()", "\targs.RepoOptions = r.toRepoOptions(args.Query, resolveRepositoriesOpts{})", "\t// performance optimization: call zoekt early, resolve repos concurrently, filter\n\t// search results with resolved repos.\n\tif args.Mode == search.ZoektGlobalSearch {\n\t\targsIndexed := *args", "\t\tuserID := int32(0)\n\t\tif envvar.SourcegraphDotComMode() {\n\t\t\tif a := actor.FromContext(ctx); a != nil {\n\t\t\t\tuserID = a.UID\n\t\t\t}\n\t\t}", "\t\t// Get all private repos for the the current actor. On sourcegraph.com, those are\n\t\t// only the repos directly added by the user. Otherwise it's all repos the user has\n\t\t// access to on all connected code hosts / external services.\n\t\tuserPrivateRepos, err := database.Repos(r.db).ListRepoNames(ctx, database.ReposListOptions{", "\t\t\tUserID: userID, // Zero valued when not in sourcegraph.com mode\n\t\t\tOnlyPrivate: true,\n\t\t\tLimitOffset: &database.LimitOffset{Limit: search.SearchLimits(conf.Get()).MaxRepos + 1},\n\t\t\tOnlyForks: args.RepoOptions.OnlyForks,\n\t\t\tNoForks: args.RepoOptions.NoForks,\n\t\t\tOnlyArchived: args.RepoOptions.OnlyArchived,\n\t\t\tNoArchived: args.RepoOptions.NoArchived,\n\t\t\tExcludePattern: repos.UnionRegExps(args.RepoOptions.MinusRepoFilters),", "\t\t})", "\t\tif err != nil {\n\t\t\tlog15.Error(\"doResults: failed to list user private repos\", \"error\", err, \"user-id\", userID)\n\t\t\ttr.LazyPrintf(\"error resolving user private repos: %v\", err)\n\t\t} else {\n\t\t\targsIndexed.UserPrivateRepos = userPrivateRepos\n\t\t}", "\t\twg := waitGroup(true)\n\t\tif args.ResultTypes.Has(result.TypeFile | result.TypePath) {\n\t\t\twg.Add(1)\n\t\t\tgoroutine.Go(func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\t_ = agg.DoFilePathSearch(ctx, &argsIndexed)\n\t\t\t})\n\t\t}", "\t\tif args.ResultTypes.Has(result.TypeSymbol) {\n\t\t\twg.Add(1)\n\t\t\tgoroutine.Go(func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\t_ = agg.DoSymbolSearch(ctx, &argsIndexed, limit)\n\t\t\t})\n\t\t}", "\t\t// On sourcegraph.com and for unscoped queries, determineRepos returns the subset\n\t\t// of indexed default searchrepos. No need to call searcher, because\n\t\t// len(searcherRepos) will always be 0.\n\t\tif envvar.SourcegraphDotComMode() {\n\t\t\targs.Mode = search.SkipUnindexed\n\t\t} else {\n\t\t\targs.Mode = search.SearcherOnly\n\t\t}\n\t}", "\tresolved, err := r.resolveRepositories(ctx, args.RepoOptions)\n\tif err != nil {\n\t\tif alert, err := errorToAlert(err); alert != nil {\n\t\t\treturn alert.wrapResults(), err\n\t\t}\n\t\t// Don't surface context errors to the user.\n\t\tif errors.Is(err, context.Canceled) {\n\t\t\ttr.LazyPrintf(\"context canceled during repo resolution: %v\", err)\n\t\t\toptionalWg.Wait()\n\t\t\trequiredWg.Wait()\n\t\t\treturn r.toSearchResults(ctx, agg)\n\t\t}\n\t\treturn nil, err\n\t}\n\targs.Repos = resolved.RepoRevs", "\ttr.LazyPrintf(\"searching %d repos, %d missing\", len(args.Repos), len(resolved.MissingRepoRevs))\n\tif len(args.Repos) == 0 {\n\t\treturn r.alertForNoResolvedRepos(ctx, args.Query).wrapResults(), nil\n\t}", "\tif len(resolved.MissingRepoRevs) > 0 {\n\t\tagg.Error(&missingRepoRevsError{Missing: resolved.MissingRepoRevs})\n\t\ttr.LazyPrintf(\"adding error for missing repo revs - done\")\n\t}", "\tagg.Send(streaming.SearchEvent{\n\t\tStats: streaming.Stats{\n\t\t\tRepos: resolved.RepoSet,\n\t\t\tExcludedForks: resolved.ExcludedRepos.Forks,\n\t\t\tExcludedArchived: resolved.ExcludedRepos.Archived,\n\t\t},\n\t})\n\ttr.LazyPrintf(\"sending first stats (repos %d, excluded repos %+v) - done\", len(resolved.RepoSet), resolved.ExcludedRepos)", "\tif args.ResultTypes.Has(result.TypeRepo) {\n\t\twg := waitGroup(true)\n\t\twg.Add(1)\n\t\tgoroutine.Go(func() {\n\t\t\tdefer wg.Done()\n\t\t\t_ = agg.DoRepoSearch(ctx, args, int32(limit))\n\t\t})", "\t}", "\tif args.ResultTypes.Has(result.TypeSymbol) && args.PatternInfo.Pattern != \"\" {\n\t\tif args.Mode != search.SkipUnindexed {\n\t\t\twg := waitGroup(args.ResultTypes.Without(result.TypeSymbol) == 0)\n\t\t\twg.Add(1)\n\t\t\tgoroutine.Go(func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\t_ = agg.DoSymbolSearch(ctx, args, limit)\n\t\t\t})\n\t\t}\n\t}", "\tif args.ResultTypes.Has(result.TypeFile | result.TypePath) {\n\t\tif args.Mode != search.SkipUnindexed {\n\t\t\twg := waitGroup(true)\n\t\t\twg.Add(1)\n\t\t\tgoroutine.Go(func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\t_ = agg.DoFilePathSearch(ctx, args)\n\t\t\t})\n\t\t}\n\t}", "\tif featureflag.FromContext(ctx).GetBoolOr(\"cc_commit_search\", false) {\n\t\taddCommitSearch := func(diff bool) {\n\t\t\tj, err := commit.NewSearchJob(args.Query, args.Repos, diff, int(args.PatternInfo.FileMatchLimit))\n\t\t\tif err != nil {\n\t\t\t\tagg.Error(err)\n\t\t\t\treturn\n\t\t\t}", "\t\t\tif err := j.ExpandUsernames(ctx, r.db); err != nil {\n\t\t\t\tagg.Error(err)\n\t\t\t\treturn\n\t\t\t}", "\t\t\tjobs = append(jobs, j)\n\t\t}", "\t\tif args.ResultTypes.Has(result.TypeCommit) {\n\t\t\taddCommitSearch(false)\n\t\t}", "\t\tif args.ResultTypes.Has(result.TypeDiff) {\n\t\t\taddCommitSearch(true)\n\t\t}\n\t} else {\n\t\tif args.ResultTypes.Has(result.TypeDiff) {\n\t\t\twg := waitGroup(args.ResultTypes.Without(result.TypeDiff) == 0)\n\t\t\twg.Add(1)\n\t\t\tgoroutine.Go(func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\t_ = agg.DoDiffSearch(ctx, args)\n\t\t\t})\n\t\t}", "\t\tif args.ResultTypes.Has(result.TypeCommit) {\n\t\t\twg := waitGroup(args.ResultTypes.Without(result.TypeCommit) == 0)\n\t\t\twg.Add(1)\n\t\t\tgoroutine.Go(func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\t_ = agg.DoCommitSearch(ctx, args)\n\t\t\t})", "\t\t}\n\t}", "\twgForJob := func(job run.Job) *sync.WaitGroup {\n\t\tswitch job.Name() {\n\t\tcase \"Diff\":\n\t\t\treturn waitGroup(args.ResultTypes.Without(result.TypeDiff) == 0)\n\t\tcase \"Commit\":\n\t\t\treturn waitGroup(args.ResultTypes.Without(result.TypeCommit) == 0)\n\t\tcase \"Structural\":\n\t\t\treturn waitGroup(true)\n\t\tdefault:\n\t\t\tpanic(\"unknown job name \" + job.Name())\n\t\t}\n\t}", "\t// Start all specific search jobs, if any.\n\tfor _, job := range jobs {\n\t\twg := wgForJob(job)\n\t\twg.Add(1)\n\t\tgoroutine.Go(func() {\n\t\t\tdefer wg.Done()\n\t\t\t_ = agg.DoSearch(ctx, job, args.Mode)\n\t\t})\n\t}", "\thasStartedAllBackends = true", "\t// Wait for required searches.\n\trequiredWg.Wait()", "\t// Give optional searches some minimum budget in case required searches return quickly.\n\t// Cancel all remaining searches after this minimum budget.\n\tbudget := 100 * time.Millisecond\n\telapsed := time.Since(start)\n\ttimer := time.AfterFunc(budget-elapsed, cancel)", "\t// Wait for remaining optional searches to finish or get cancelled.\n\toptionalWg.Wait()", "\ttimer.Stop()", "\treturn r.toSearchResults(ctx, agg)\n}", "// toSearchResults converts an Aggregator to SearchResults.\n//\n// toSearchResults relies on all WaitGroups being done since it relies on\n// collecting from the streams.\nfunc (r *searchResolver) toSearchResults(ctx context.Context, agg *run.Aggregator) (*SearchResults, error) {\n\tmatches, common, matchCount, aggErrs := agg.Get()", "\tif aggErrs == nil {\n\t\treturn nil, errors.New(\"aggErrs should never be nil\")\n\t}", "\tao := alertObserver{\n\t\tInputs: r.SearchInputs,\n\t\thasResults: matchCount > 0,\n\t}\n\tfor _, err := range aggErrs.Errors {\n\t\tao.Error(ctx, err)\n\t}\n\talert, err := ao.Done(&common)", "\tr.sortResults(matches)", "\treturn &SearchResults{\n\t\tMatches: matches,\n\t\tStats: common,\n\t\tAlert: alert,\n\t}, err\n}", "// isContextError returns true if ctx.Err() is not nil or if err\n// is an error caused by context cancelation or timeout.\nfunc isContextError(ctx context.Context, err error) bool {\n\treturn ctx.Err() != nil || errors.IsAny(err, context.Canceled, context.DeadlineExceeded)\n}", "// SearchResultResolver is a resolver for the GraphQL union type `SearchResult`.\n//\n// Supported types:\n//\n// - *RepositoryResolver // repo name match\n// - *fileMatchResolver // text match\n// - *commitSearchResultResolver // diff or commit match\n//\n// Note: Any new result types added here also need to be handled properly in search_results.go:301 (sparklines)\ntype SearchResultResolver interface {\n\tToRepository() (*RepositoryResolver, bool)\n\tToFileMatch() (*FileMatchResolver, bool)\n\tToCommitSearchResult() (*CommitSearchResultResolver, bool)", "\tResultCount() int32\n}", "// compareFileLengths sorts file paths such that they appear earlier if they\n// match file: patterns in the query exactly.\nfunc compareFileLengths(left, right string, exactFilePatterns map[string]struct{}) bool {\n\t_, aMatch := exactFilePatterns[path.Base(left)]\n\t_, bMatch := exactFilePatterns[path.Base(right)]\n\tif aMatch || bMatch {\n\t\tif aMatch && bMatch {\n\t\t\t// Prefer shorter file names (ie root files come first)\n\t\t\tif len(left) != len(right) {\n\t\t\t\treturn len(left) < len(right)\n\t\t\t}\n\t\t\treturn left < right\n\t\t}\n\t\t// Prefer exact match\n\t\treturn aMatch\n\t}\n\treturn left < right\n}", "func compareDates(left, right *time.Time) bool {\n\tif left == nil || right == nil {\n\t\treturn left != nil // Place the value that is defined first.\n\t}\n\treturn left.After(*right)\n}", "// compareSearchResults sorts repository matches, file matches, and commits.\n// Repositories and filenames are sorted alphabetically. As a refinement, if any\n// filename matches a value in a non-empty set exactFilePatterns, then such\n// filenames are listed earlier.\n//\n// Commits are sorted by date. Commits are not associated with searchrepos, and\n// will always list after repository or file match results, if any.\nfunc compareSearchResults(left, right result.Match, exactFilePatterns map[string]struct{}) bool {\n\tsortKeys := func(match result.Match) (string, string, *time.Time) {\n\t\tswitch r := match.(type) {\n\t\tcase *result.RepoMatch:\n\t\t\treturn string(r.Name), \"\", nil\n\t\tcase *result.FileMatch:\n\t\t\treturn string(r.Repo.Name), r.Path, nil\n\t\tcase *result.CommitMatch:\n\t\t\t// Commits are relatively sorted by date, and after repo\n\t\t\t// or path names. We use ~ as the key for repo and\n\t\t\t// paths,lexicographically last in ASCII.\n\t\t\treturn \"~\", \"~\", &r.Commit.Author.Date\n\t\t}\n\t\t// Unreachable.\n\t\tpanic(\"unreachable: compareSearchResults expects RepositoryResolver, FileMatchResolver, or CommitSearchResultResolver\")\n\t}", "\tarepo, afile, adate := sortKeys(left)\n\tbrepo, bfile, bdate := sortKeys(right)", "\tif arepo == brepo {\n\t\tif len(exactFilePatterns) == 0 {\n\t\t\tif afile != bfile {\n\t\t\t\treturn afile < bfile\n\t\t\t}\n\t\t\treturn compareDates(adate, bdate)\n\t\t}\n\t\treturn compareFileLengths(afile, bfile, exactFilePatterns)\n\t}\n\treturn arepo < brepo\n}", "func (r *searchResolver) sortResults(results []result.Match) {\n\tvar exactPatterns map[string]struct{}\n\tif getBoolPtr(r.UserSettings.SearchGlobbing, false) {\n\t\texactPatterns = r.getExactFilePatterns()\n\t}\n\tsort.Slice(results, func(i, j int) bool { return compareSearchResults(results[i], results[j], exactPatterns) })\n}", "// getExactFilePatterns returns the set of file patterns without glob syntax.\nfunc (r *searchResolver) getExactFilePatterns() map[string]struct{} {\n\tm := map[string]struct{}{}\n\tquery.VisitField(\n\t\tr.Query,\n\t\tquery.FieldFile,\n\t\tfunc(value string, negated bool, annotation query.Annotation) {\n\t\t\toriginalValue := r.OriginalQuery[annotation.Range.Start.Column+len(query.FieldFile)+1 : annotation.Range.End.Column]\n\t\t\tif !negated && query.ContainsNoGlobSyntax(originalValue) {\n\t\t\t\tm[originalValue] = struct{}{}\n\t\t\t}\n\t\t})\n\treturn m\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [26, 1516, 36, 537], "buggy_code_start_loc": [26, 39, 33, 537], "filenames": ["CHANGELOG.md", "cmd/frontend/graphqlbackend/search_results.go", "dev/gqltest/README.md", "dev/gqltest/search_test.go"], "fixing_code_end_loc": [35, 1518, 36, 544], "fixing_code_start_loc": [27, 40, 33, 538], "message": "Sourcegraph is a code search and navigation engine. Sourcegraph prior to version 3.33.2 is vulnerable to a side-channel attack where strings in private source code could be guessed by an authenticated but unauthorized actor. This issue affects the Saved Searches and Code Monitoring features. A successful attack would require an authenticated bad actor to create many Saved Searches or Code Monitors to receive confirmation that a specific string exists. This could allow an attacker to guess formatted tokens in source code, such as API keys. This issue was patched in version 3.33.2 and any future versions of Sourcegraph. We strongly encourage upgrading to secure versions. If you are unable to, you may disable Saved Searches and Code Monitors.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sourcegraph:sourcegraph:*:*:*:*:*:*:*:*", "matchCriteriaId": "8AC67147-DAE3-4326-9027-0DEB53C55D32", "versionEndExcluding": "3.33.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Sourcegraph is a code search and navigation engine. Sourcegraph prior to version 3.33.2 is vulnerable to a side-channel attack where strings in private source code could be guessed by an authenticated but unauthorized actor. This issue affects the Saved Searches and Code Monitoring features. A successful attack would require an authenticated bad actor to create many Saved Searches or Code Monitors to receive confirmation that a specific string exists. This could allow an attacker to guess formatted tokens in source code, such as API keys. This issue was patched in version 3.33.2 and any future versions of Sourcegraph. We strongly encourage upgrading to secure versions. If you are unable to, you may disable Saved Searches and Code Monitors."}, {"lang": "es", "value": "Sourcegraph es un motor de b\u00fasqueda y navegaci\u00f3n de c\u00f3digo. Sourcegraph versiones anteriores a 3.33.2 es vulnerable a un ataque de canal lateral en el que las cadenas del c\u00f3digo fuente privado podr\u00edan ser adivinadas por un actor autenticado pero no autorizado. Este problema afecta a las funciones de B\u00fasquedas Guardadas y Monitorizaci\u00f3n de C\u00f3digo. Un ataque con \u00e9xito requerir\u00eda que un actor malo autenticado creara muchas B\u00fasquedas Guardadas o Monitores de C\u00f3digo para recibir la confirmaci\u00f3n de que una cadena espec\u00edfica esta presente. Esto podr\u00eda permitir a un atacante adivinar los tokens formateados en el c\u00f3digo fuente, como las claves de la API. Este problema ha sido parcheado en la versi\u00f3n 3.33.2 y en las futuras versiones de Sourcegraph. Recomendamos encarecidamente que se actualice a las versiones seguras. Si no puede hacerlo, puede deshabilitar las B\u00fasquedas Guardadas y los Monitores de C\u00f3digo"}], "evaluatorComment": null, "id": "CVE-2021-43823", "lastModified": "2021-12-16T15:00:25.970", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Primary"}]}, "published": "2021-12-13T20:15:07.813", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/sourcegraph/sourcegraph/commit/a88d90a8302c492282186d39718cd8fb093c14fa"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/sourcegraph/sourcegraph/security/advisories/GHSA-cpq7-hmvv-29w9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-203"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/sourcegraph/sourcegraph/commit/a88d90a8302c492282186d39718cd8fb093c14fa"}, "type": "CWE-203"}
326
Determine whether the {function_name} code is vulnerable or not.
[ "# GraphQL integration tests", "This directory contains API-based integration tests in the form of standard Go tests. It is called gqltest since most of our API is GraphQL. However, the test suite has been extended to test other endpoints such as streaming search.", "## How to set up credentials", "Tests use environment variables to accept credentials of different external services involved, it is suggested to use [direnv](https://direnv.net/) to persist those credentials for your convenience. Here is a comprehensive example `.envrc` file (you're free to use any other means, e.g. `.profile` or `.bashrc`):", "```sh\n# Your GitHub personal access token, this token needs to have scope to access private\n# repositories of \"sgtest\" organization. If you haven't joined \"sgtest\" organization,\n# please post a message on #dev-chat to ask for an invite.\nexport GITHUB_TOKEN=<REDACTED>", "# Please go to https://team-sourcegraph.1password.com/vaults/dnrhbauihkhjs5ag6vszsme45a/allitems/zpxz7vl3ek7j3yxbnjvh6utrei\n# and copy relevant credentials to here.\nexport AWS_ACCESS_KEY_ID=<REDACTED>\nexport AWS_SECRET_ACCESS_KEY=<REDACTED>\nexport AWS_CODE_COMMIT_USERNAME=<REDACTED>\nexport AWS_CODE_COMMIT_PASSWORD=<REDACTED>", "export BITBUCKET_SERVER_URL=<REDACTED>\nexport BITBUCKET_SERVER_TOKEN=<REDACTED>\nexport BITBUCKET_SERVER_USERNAME=<REDACTED>\n```", "You need to run `direnv allow` after editing the `.envrc` file (it is suggested to place the `.envrc` file under `dev/gqltest`).", "Alternatively you can use the 1password CLI tool:", "```sh\n# dev-private token for ghe.sgdev.org", "op get item bw4nttlfqve3rc6xqzbqq7l7pm | jq -r '.. | select(.t? == \"token name: dev-private\") | @sh \"export GITHUB_TOKEN=\\(.v)\"'", "# AWS and Bitbucket tokens", "op get item 5q5lnpirajegt7uifngeabrak4 | jq -r '.details.sections[] | .fields[] | @sh \"export \\(.t)=\\(.v)\"", "```", "## How to run tests", "GraphQL-based integration tests are running against a live Sourcegraph instance, the eaiset way to make one is by booting up a single Docker container:", "```sh\n# For easier testing, run Sourcegraph instance without volume,\n# so it always starts from a clean state.\ndocker run --publish 7080:7080 --rm sourcegraph/server:insiders\n```", "Once the the instance is live (look for the log line `✱ Sourcegraph is ready at: http://127.0.0.1:7080`), you can open another terminal tab to run these tests under this directory (`dev/gqltest`):", "```sh\n→ go test -long\n2020/07/17 14:17:32 Site admin has been created: gqltest-admin\nPASS\nok \tgithub.com/sourcegraph/sourcegraph/dev/gqltest\t31.521s\n```", "### Testing against local dev instance", "It is not required to boot up a single Docker container to run these tests, which means it's also possible to run these tests against any Sourcegraph instance, for example, your local dev instance:", "```sh\ngo test -long -base-url \"http://localhost:3080\" -email \"joe@sourcegraph.com\" -username \"joe\" -password \"<REDACTED>\"\n```", "Generally, you're able to repeatedly run these tests regardless of any failures because tests are written in the way that cleans up and restores to the previous state. It is aware of if the instance has been initialized, so you can focus on debugging tests.", "Because we're using the standard Go test framework, you are able to just run a single or subset of these tests:", "```sh\n→ go test -long -run TestSearch\n2020/07/17 14:20:59 Site admin authenticated: gqltest-admin\nPASS\nok \tgithub.com/sourcegraph/sourcegraph/dev/gqltest\t3.073s\n```", "## How to add new tests", "Adding new tests to this test suite is as easy as adding a Go test, here are some general rules to follow:", "- Use `gqltest-` prefix for entity name, and be as specific as possible for easier debugging, e.g. `gqltest-org-user-1`.\n- Restore the previous state regardless of failures, including:\n - Delete new users created during the test.\n - Delete external services created during the test.\n - Although, sometimes you would not want to delete an entity so you could login and inspect the failure state.\n- Prefix your branch name with `backend-integration/` will run integration tests in CI on your pull request." ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [26, 1516, 36, 537], "buggy_code_start_loc": [26, 39, 33, 537], "filenames": ["CHANGELOG.md", "cmd/frontend/graphqlbackend/search_results.go", "dev/gqltest/README.md", "dev/gqltest/search_test.go"], "fixing_code_end_loc": [35, 1518, 36, 544], "fixing_code_start_loc": [27, 40, 33, 538], "message": "Sourcegraph is a code search and navigation engine. Sourcegraph prior to version 3.33.2 is vulnerable to a side-channel attack where strings in private source code could be guessed by an authenticated but unauthorized actor. This issue affects the Saved Searches and Code Monitoring features. A successful attack would require an authenticated bad actor to create many Saved Searches or Code Monitors to receive confirmation that a specific string exists. This could allow an attacker to guess formatted tokens in source code, such as API keys. This issue was patched in version 3.33.2 and any future versions of Sourcegraph. We strongly encourage upgrading to secure versions. If you are unable to, you may disable Saved Searches and Code Monitors.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sourcegraph:sourcegraph:*:*:*:*:*:*:*:*", "matchCriteriaId": "8AC67147-DAE3-4326-9027-0DEB53C55D32", "versionEndExcluding": "3.33.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Sourcegraph is a code search and navigation engine. Sourcegraph prior to version 3.33.2 is vulnerable to a side-channel attack where strings in private source code could be guessed by an authenticated but unauthorized actor. This issue affects the Saved Searches and Code Monitoring features. A successful attack would require an authenticated bad actor to create many Saved Searches or Code Monitors to receive confirmation that a specific string exists. This could allow an attacker to guess formatted tokens in source code, such as API keys. This issue was patched in version 3.33.2 and any future versions of Sourcegraph. We strongly encourage upgrading to secure versions. If you are unable to, you may disable Saved Searches and Code Monitors."}, {"lang": "es", "value": "Sourcegraph es un motor de b\u00fasqueda y navegaci\u00f3n de c\u00f3digo. Sourcegraph versiones anteriores a 3.33.2 es vulnerable a un ataque de canal lateral en el que las cadenas del c\u00f3digo fuente privado podr\u00edan ser adivinadas por un actor autenticado pero no autorizado. Este problema afecta a las funciones de B\u00fasquedas Guardadas y Monitorizaci\u00f3n de C\u00f3digo. Un ataque con \u00e9xito requerir\u00eda que un actor malo autenticado creara muchas B\u00fasquedas Guardadas o Monitores de C\u00f3digo para recibir la confirmaci\u00f3n de que una cadena espec\u00edfica esta presente. Esto podr\u00eda permitir a un atacante adivinar los tokens formateados en el c\u00f3digo fuente, como las claves de la API. Este problema ha sido parcheado en la versi\u00f3n 3.33.2 y en las futuras versiones de Sourcegraph. Recomendamos encarecidamente que se actualice a las versiones seguras. Si no puede hacerlo, puede deshabilitar las B\u00fasquedas Guardadas y los Monitores de C\u00f3digo"}], "evaluatorComment": null, "id": "CVE-2021-43823", "lastModified": "2021-12-16T15:00:25.970", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Primary"}]}, "published": "2021-12-13T20:15:07.813", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/sourcegraph/sourcegraph/commit/a88d90a8302c492282186d39718cd8fb093c14fa"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/sourcegraph/sourcegraph/security/advisories/GHSA-cpq7-hmvv-29w9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-203"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/sourcegraph/sourcegraph/commit/a88d90a8302c492282186d39718cd8fb093c14fa"}, "type": "CWE-203"}
326
Determine whether the {function_name} code is vulnerable or not.
[ "# GraphQL integration tests", "This directory contains API-based integration tests in the form of standard Go tests. It is called gqltest since most of our API is GraphQL. However, the test suite has been extended to test other endpoints such as streaming search.", "## How to set up credentials", "Tests use environment variables to accept credentials of different external services involved, it is suggested to use [direnv](https://direnv.net/) to persist those credentials for your convenience. Here is a comprehensive example `.envrc` file (you're free to use any other means, e.g. `.profile` or `.bashrc`):", "```sh\n# Your GitHub personal access token, this token needs to have scope to access private\n# repositories of \"sgtest\" organization. If you haven't joined \"sgtest\" organization,\n# please post a message on #dev-chat to ask for an invite.\nexport GITHUB_TOKEN=<REDACTED>", "# Please go to https://team-sourcegraph.1password.com/vaults/dnrhbauihkhjs5ag6vszsme45a/allitems/zpxz7vl3ek7j3yxbnjvh6utrei\n# and copy relevant credentials to here.\nexport AWS_ACCESS_KEY_ID=<REDACTED>\nexport AWS_SECRET_ACCESS_KEY=<REDACTED>\nexport AWS_CODE_COMMIT_USERNAME=<REDACTED>\nexport AWS_CODE_COMMIT_PASSWORD=<REDACTED>", "export BITBUCKET_SERVER_URL=<REDACTED>\nexport BITBUCKET_SERVER_TOKEN=<REDACTED>\nexport BITBUCKET_SERVER_USERNAME=<REDACTED>\n```", "You need to run `direnv allow` after editing the `.envrc` file (it is suggested to place the `.envrc` file under `dev/gqltest`).", "Alternatively you can use the 1password CLI tool:", "```sh\n# dev-private token for ghe.sgdev.org", "op get item bw4nttlfqve3rc6xqzbqq7l7pm | jq -r '.. | select(.t? == \"k8s.sgdev.org\") | @sh \"export GITHUB_TOKEN=\\(.v)\"'", "# AWS and Bitbucket tokens", "op get item 5q5lnpirajegt7uifngeabrak4 | jq -r '.details.sections[] | .fields[] | @sh \"export \\(.t)=\\(.v)\"'", "```", "## How to run tests", "GraphQL-based integration tests are running against a live Sourcegraph instance, the eaiset way to make one is by booting up a single Docker container:", "```sh\n# For easier testing, run Sourcegraph instance without volume,\n# so it always starts from a clean state.\ndocker run --publish 7080:7080 --rm sourcegraph/server:insiders\n```", "Once the the instance is live (look for the log line `✱ Sourcegraph is ready at: http://127.0.0.1:7080`), you can open another terminal tab to run these tests under this directory (`dev/gqltest`):", "```sh\n→ go test -long\n2020/07/17 14:17:32 Site admin has been created: gqltest-admin\nPASS\nok \tgithub.com/sourcegraph/sourcegraph/dev/gqltest\t31.521s\n```", "### Testing against local dev instance", "It is not required to boot up a single Docker container to run these tests, which means it's also possible to run these tests against any Sourcegraph instance, for example, your local dev instance:", "```sh\ngo test -long -base-url \"http://localhost:3080\" -email \"joe@sourcegraph.com\" -username \"joe\" -password \"<REDACTED>\"\n```", "Generally, you're able to repeatedly run these tests regardless of any failures because tests are written in the way that cleans up and restores to the previous state. It is aware of if the instance has been initialized, so you can focus on debugging tests.", "Because we're using the standard Go test framework, you are able to just run a single or subset of these tests:", "```sh\n→ go test -long -run TestSearch\n2020/07/17 14:20:59 Site admin authenticated: gqltest-admin\nPASS\nok \tgithub.com/sourcegraph/sourcegraph/dev/gqltest\t3.073s\n```", "## How to add new tests", "Adding new tests to this test suite is as easy as adding a Go test, here are some general rules to follow:", "- Use `gqltest-` prefix for entity name, and be as specific as possible for easier debugging, e.g. `gqltest-org-user-1`.\n- Restore the previous state regardless of failures, including:\n - Delete new users created during the test.\n - Delete external services created during the test.\n - Although, sometimes you would not want to delete an entity so you could login and inspect the failure state.\n- Prefix your branch name with `backend-integration/` will run integration tests in CI on your pull request." ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [26, 1516, 36, 537], "buggy_code_start_loc": [26, 39, 33, 537], "filenames": ["CHANGELOG.md", "cmd/frontend/graphqlbackend/search_results.go", "dev/gqltest/README.md", "dev/gqltest/search_test.go"], "fixing_code_end_loc": [35, 1518, 36, 544], "fixing_code_start_loc": [27, 40, 33, 538], "message": "Sourcegraph is a code search and navigation engine. Sourcegraph prior to version 3.33.2 is vulnerable to a side-channel attack where strings in private source code could be guessed by an authenticated but unauthorized actor. This issue affects the Saved Searches and Code Monitoring features. A successful attack would require an authenticated bad actor to create many Saved Searches or Code Monitors to receive confirmation that a specific string exists. This could allow an attacker to guess formatted tokens in source code, such as API keys. This issue was patched in version 3.33.2 and any future versions of Sourcegraph. We strongly encourage upgrading to secure versions. If you are unable to, you may disable Saved Searches and Code Monitors.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sourcegraph:sourcegraph:*:*:*:*:*:*:*:*", "matchCriteriaId": "8AC67147-DAE3-4326-9027-0DEB53C55D32", "versionEndExcluding": "3.33.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Sourcegraph is a code search and navigation engine. Sourcegraph prior to version 3.33.2 is vulnerable to a side-channel attack where strings in private source code could be guessed by an authenticated but unauthorized actor. This issue affects the Saved Searches and Code Monitoring features. A successful attack would require an authenticated bad actor to create many Saved Searches or Code Monitors to receive confirmation that a specific string exists. This could allow an attacker to guess formatted tokens in source code, such as API keys. This issue was patched in version 3.33.2 and any future versions of Sourcegraph. We strongly encourage upgrading to secure versions. If you are unable to, you may disable Saved Searches and Code Monitors."}, {"lang": "es", "value": "Sourcegraph es un motor de b\u00fasqueda y navegaci\u00f3n de c\u00f3digo. Sourcegraph versiones anteriores a 3.33.2 es vulnerable a un ataque de canal lateral en el que las cadenas del c\u00f3digo fuente privado podr\u00edan ser adivinadas por un actor autenticado pero no autorizado. Este problema afecta a las funciones de B\u00fasquedas Guardadas y Monitorizaci\u00f3n de C\u00f3digo. Un ataque con \u00e9xito requerir\u00eda que un actor malo autenticado creara muchas B\u00fasquedas Guardadas o Monitores de C\u00f3digo para recibir la confirmaci\u00f3n de que una cadena espec\u00edfica esta presente. Esto podr\u00eda permitir a un atacante adivinar los tokens formateados en el c\u00f3digo fuente, como las claves de la API. Este problema ha sido parcheado en la versi\u00f3n 3.33.2 y en las futuras versiones de Sourcegraph. Recomendamos encarecidamente que se actualice a las versiones seguras. Si no puede hacerlo, puede deshabilitar las B\u00fasquedas Guardadas y los Monitores de C\u00f3digo"}], "evaluatorComment": null, "id": "CVE-2021-43823", "lastModified": "2021-12-16T15:00:25.970", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Primary"}]}, "published": "2021-12-13T20:15:07.813", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/sourcegraph/sourcegraph/commit/a88d90a8302c492282186d39718cd8fb093c14fa"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/sourcegraph/sourcegraph/security/advisories/GHSA-cpq7-hmvv-29w9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-203"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/sourcegraph/sourcegraph/commit/a88d90a8302c492282186d39718cd8fb093c14fa"}, "type": "CWE-203"}
326
Determine whether the {function_name} code is vulnerable or not.
[ "package main", "import (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"", "\t\"github.com/google/go-cmp/cmp\"\n\t\"github.com/stretchr/testify/require\"", "\t\"github.com/sourcegraph/sourcegraph/internal/extsvc\"\n\t\"github.com/sourcegraph/sourcegraph/internal/gqltestutil\"\n)", "func TestSearch(t *testing.T) {\n\tif len(*githubToken) == 0 {\n\t\tt.Skip(\"Environment variable GITHUB_TOKEN is not set\")\n\t}", "\t// Set up external service\n\tesID, err := client.AddExternalService(gqltestutil.AddExternalServiceInput{\n\t\tKind: extsvc.KindGitHub,\n\t\tDisplayName: \"gqltest-github-search\",\n\t\tConfig: mustMarshalJSONString(struct {\n\t\t\tURL string `json:\"url\"`\n\t\t\tToken string `json:\"token\"`\n\t\t\tRepos []string `json:\"repos\"`\n\t\t\tRepositoryPathPattern string `json:\"repositoryPathPattern\"`\n\t\t}{\n\t\t\tURL: \"https://ghe.sgdev.org/\",\n\t\t\tToken: *githubToken,\n\t\t\tRepos: []string{\n\t\t\t\t\"sgtest/java-langserver\",\n\t\t\t\t\"sgtest/jsonrpc2\",\n\t\t\t\t\"sgtest/go-diff\",\n\t\t\t\t\"sgtest/appdash\",\n\t\t\t\t\"sgtest/sourcegraph-typescript\",\n\t\t\t\t\"sgtest/private\", // Private\n\t\t\t\t\"sgtest/mux\", // Fork\n\t\t\t\t\"sgtest/archived\", // Archived\n\t\t\t},\n\t\t\tRepositoryPathPattern: \"github.com/{nameWithOwner}\",\n\t\t}),\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer func() {\n\t\terr := client.DeleteExternalService(esID)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()", "\terr = client.WaitForReposToBeCloned(\n\t\t\"github.com/sgtest/java-langserver\",\n\t\t\"github.com/sgtest/jsonrpc2\",\n\t\t\"github.com/sgtest/go-diff\",\n\t\t\"github.com/sgtest/appdash\",\n\t\t\"github.com/sgtest/sourcegraph-typescript\",\n\t\t\"github.com/sgtest/private\", // Private\n\t\t\"github.com/sgtest/mux\", // Fork\n\t\t\"github.com/sgtest/archived\", // Archived\n\t)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}", "\terr = client.WaitForReposToBeIndex(\n\t\t\"github.com/sgtest/java-langserver\",\n\t)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}", "\tt.Run(\"search contexts\", func(t *testing.T) {\n\t\ttestSearchContextsCRUD(t, client)\n\t\ttestListingSearchContexts(t, client)\n\t})", "\tt.Run(\"graphql\", func(t *testing.T) {\n\t\ttestSearchClient(t, client)\n\t})\n\tt.Run(\"stream\", func(t *testing.T) {\n\t\ttestSearchClient(t, &gqltestutil.SearchStreamClient{\n\t\t\tClient: client,\n\t\t})\n\t})", "\ttestSearchOther(t)\n}", "// searchClient is an interface so we can swap out a streaming vs graphql\n// based search API. It only supports the methods that streaming supports.\ntype searchClient interface {\n\tSearchRepositories(query string) (gqltestutil.SearchRepositoryResults, error)\n\tSearchFiles(query string) (*gqltestutil.SearchFileResults, error)\n\tSearchAll(query string) ([]*gqltestutil.AnyResult, error)", "\tOverwriteSettings(subjectID, contents string) error\n\tAuthenticatedUserID() string\n}", "func testSearchClient(t *testing.T, client searchClient) {\n\t// Temporary test until we have equivalence.\n\t_, isStreaming := client.(*gqltestutil.SearchStreamClient)", "\tconst (\n\t\tskipStream = 1 << iota\n\t\tskipGraphQL\n\t)\n\tdoSkip := func(t *testing.T, skip int) {\n\t\tt.Helper()\n\t\tif skip&skipStream != 0 && isStreaming {\n\t\t\tt.Skip(\"does not support streaming\")\n\t\t}\n\t\tif skip&skipGraphQL != 0 && !isStreaming {\n\t\t\tt.Skip(\"does not support graphql\")\n\t\t}\n\t}", "\tt.Run(\"visibility\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tquery string\n\t\t\twantMissing []string\n\t\t}{\n\t\t\t{\n\t\t\t\tquery: \"type:repo visibility:private sgtest\",\n\t\t\t\twantMissing: []string{},\n\t\t\t},\n\t\t\t{\n\t\t\t\tquery: \"type:repo visibility:public sgtest\",\n\t\t\t\twantMissing: []string{\"github.com/sgtest/private\"},\n\t\t\t},\n\t\t\t{\n\t\t\t\tquery: \"type:repo visibility:any sgtest\",\n\t\t\t\twantMissing: []string{},\n\t\t\t},\n\t\t}\n\t\tfor _, test := range tests {\n\t\t\tt.Run(test.query, func(t *testing.T) {\n\t\t\t\tresults, err := client.SearchRepositories(test.query)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t\tmissing := results.Exists(\"github.com/sgtest/private\")\n\t\t\t\tif diff := cmp.Diff(test.wantMissing, missing); diff != \"\" {\n\t\t\t\t\tt.Fatalf(\"Missing mismatch (-want +got):\\n%s\", diff)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})", "\tt.Run(\"execute search with search parameters\", func(t *testing.T) {\n\t\tresults, err := client.SearchFiles(\"repo:^github.com/sgtest/go-diff$ type:file file:.go -file:.md\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}", "\t\t// Make sure only got .go files and no .md files\n\t\tfor _, r := range results.Results {\n\t\t\tif !strings.HasSuffix(r.File.Name, \".go\") {\n\t\t\t\tt.Fatalf(\"Found file name does not end with .go: %s\", r.File.Name)\n\t\t\t}\n\t\t}\n\t})", "\tt.Run(\"lang: filter\", func(t *testing.T) {\n\t\t// On our test repositories, `function` has results for go, ts, python, html\n\t\tresults, err := client.SearchFiles(\"function lang:go\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\t// Make sure we only got .go files\n\t\tfor _, r := range results.Results {\n\t\t\tif !strings.Contains(r.File.Name, \".go\") {\n\t\t\t\tt.Fatalf(\"Found file name does not end with .go: %s\", r.File.Name)\n\t\t\t}\n\t\t}\n\t})", "\tt.Run(\"excluding repositories\", func(t *testing.T) {\n\t\tresults, err := client.SearchFiles(\"fmt.Sprintf -repo:jsonrpc2\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\t// Make sure we got some results\n\t\tif len(results.Results) == 0 {\n\t\t\tt.Fatal(\"Want non-zero results but got 0\")\n\t\t}\n\t\t// Make sure we got no results from the excluded repository\n\t\tfor _, r := range results.Results {\n\t\t\tif strings.Contains(r.Repository.Name, \"jsonrpc2\") {\n\t\t\t\tt.Fatal(\"Got results for excluded repository\")\n\t\t\t}\n\t\t}\n\t})", "\tt.Run(\"multiple revisions per repository\", func(t *testing.T) {\n\t\tresults, err := client.SearchFiles(\"repo:sgtest/go-diff$@master:print-options:*refs/heads/ func NewHunksReader\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}", "\t\twantExprs := map[string]struct{}{\n\t\t\t\"master\": {},\n\t\t\t\"print-options\": {},", "\t\t\t// These next 2 branches are included because of the *refs/heads/ in the query.\n\t\t\t\"test-already-exist-pr\": {},\n\t\t\t\"bug-fix-wip\": {},\n\t\t}", "\t\tfor _, r := range results.Results {\n\t\t\tdelete(wantExprs, r.RevSpec.Expr)\n\t\t}", "\t\tif len(wantExprs) > 0 {\n\t\t\tmissing := make([]string, 0, len(wantExprs))\n\t\t\tfor expr := range wantExprs {\n\t\t\t\tmissing = append(missing, expr)\n\t\t\t}\n\t\t\tt.Fatalf(\"Missing exprs: %v\", missing)\n\t\t}\n\t})", "\tt.Run(\"repository groups\", func(t *testing.T) {\n\t\tconst repoName = \"github.com/sgtest/go-diff\"\n\t\terr := client.OverwriteSettings(client.AuthenticatedUserID(), fmt.Sprintf(`{\"search.repositoryGroups\":{\"gql_test_group\": [\"%s\"]}}`, repoName))\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tdefer func() {\n\t\t\terr := client.OverwriteSettings(client.AuthenticatedUserID(), `{}`)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t}()", "\t\tresults, err := client.SearchFiles(\"repogroup:gql_test_group diff.\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}", "\t\t// Make sure there are results and all results are from the same repository\n\t\tif len(results.Results) == 0 {\n\t\t\tt.Fatal(\"Unexpected zero result\")\n\t\t}\n\t\tfor _, r := range results.Results {\n\t\t\tif r.Repository.Name != repoName {\n\t\t\t\tt.Fatalf(\"Repository: want %q but got %q\", repoName, r.Repository.Name)\n\t\t\t}\n\t\t}\n\t})", "\tt.Run(\"repository search\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname string\n\t\t\tquery string\n\t\t\tzeroResult bool\n\t\t\twantMissing []string\n\t\t}{\n\t\t\t{\n\t\t\t\tname: `archived excluded, zero results`,\n\t\t\t\tquery: `type:repo archived`,\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `archived included, nonzero result`,\n\t\t\t\tquery: `type:repo archived archived:yes`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `archived included if exact without option, nonzero result`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/archived$`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `fork excluded, zero results`,\n\t\t\t\tquery: `type:repo sgtest/mux`,\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `fork included, nonzero result`,\n\t\t\t\tquery: `type:repo sgtest/mux fork:yes`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `fork included if exact without option, nonzero result`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/mux$`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"repohasfile returns results for global search\",\n\t\t\t\tquery: \"repohasfile:README\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"multiple repohasfile returns no results if one doesn't match\",\n\t\t\t\tquery: \"repohasfile:README repohasfile:thisfiledoesnotexist_1571751\",\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"repo search by name, nonzero result\",\n\t\t\t\tquery: \"repo:go-diff$\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"true is an alias for yes when fork is set\",\n\t\t\t\tquery: `repo:github\\.com/sgtest/mux fork:true`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `exclude counts for fork and archive`,\n\t\t\t\tquery: `repo:mux|archived|go-diff`,\n\t\t\t\twantMissing: []string{\n\t\t\t\t\t\"github.com/sgtest/archived\",\n\t\t\t\t\t\"github.com/sgtest/mux\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Structural search returns repo results if patterntype set but pattern is empty`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/sourcegraph-typescript$ patterntype:structural`,\n\t\t\t},\n\t\t}\n\t\tfor _, test := range tests {\n\t\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t\tresults, err := client.SearchRepositories(test.query)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}", "\t\t\t\tif test.zeroResult {\n\t\t\t\t\tif len(results) > 0 {\n\t\t\t\t\t\tt.Fatalf(\"Want zero result but got %d\", len(results))\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif len(results) == 0 {\n\t\t\t\t\t\tt.Fatal(\"Want non-zero results but got 0\")\n\t\t\t\t\t}\n\t\t\t\t}", "\t\t\t\tif test.wantMissing != nil {\n\t\t\t\t\tmissing := results.Exists(test.wantMissing...)\n\t\t\t\t\tsort.Strings(missing)\n\t\t\t\t\tif diff := cmp.Diff(test.wantMissing, missing); diff != \"\" {\n\t\t\t\t\t\tt.Fatalf(\"Missing mismatch (-want +got):\\n%s\", diff)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})", "\tt.Run(\"global text search\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname string\n\t\t\tquery string\n\t\t\tzeroResult bool\n\t\t\tminMatchCount int64\n\t\t\twantAlert *gqltestutil.SearchAlert\n\t\t\tskip int\n\t\t}{\n\t\t\t// Global search\n\t\t\t{\n\t\t\t\tname: \"error\",\n\t\t\t\tquery: \"error\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"error count:1000\",\n\t\t\t\tquery: \"error count:1000\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"something with more than 1000 results and use count:1000\",\n\t\t\t\tquery: \". count:1000\",\n\t\t\t\tminMatchCount: 1000,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"default limit streaming\",\n\t\t\t\tquery: \".\",\n\t\t\t\tminMatchCount: 500,\n\t\t\t\tskip: skipGraphQL,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"default limit graphql\",\n\t\t\t\tquery: \".\",\n\t\t\t\tminMatchCount: 30,\n\t\t\t\tskip: skipStream,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"regular expression without indexed search\",\n\t\t\t\tquery: \"index:no patterntype:regexp ^func.*$\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"fork:only\",\n\t\t\t\tquery: \"fork:only router\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"double-quoted pattern, nonzero result\",\n\t\t\t\tquery: `\"func main() {\\n\" patterntype:regexp type:file`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"exclude repo, nonzero result\",\n\t\t\t\tquery: `\"func main() {\\n\" -repo:go-diff patterntype:regexp type:file`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"fork:no\",\n\t\t\t\tquery: \"fork:no FORK\" + \"_SENTINEL\",\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"fork:yes\",\n\t\t\t\tquery: \"fork:yes FORK\" + \"_SENTINEL\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"random characters, zero results\",\n\t\t\t\tquery: \"asdfalksd+jflaksjdfklas patterntype:literal -repo:sourcegraph\",\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t// Global search visibility\n\t\t\t{\n\t\t\t\tname: \"visibility:all for global search includes private repo\",\n\t\t\t\t// match content in a private repo sgtest/private and a public repo sgtest/go-diff.\n\t\t\t\tquery: `(#\\ private|#\\ go-diff) visibility:all patterntype:regexp`,\n\t\t\t\tminMatchCount: 2,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"visibility:public for global search excludes private repo\",\n\t\t\t\t// expect no matches because pattern '# private' is only in a private repo.\n\t\t\t\tquery: \"# private visibility:public\",\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"visibility:private for global includes only private repo\",\n\t\t\t\t// expect no matches because #go-diff doesn't exist in private repo.\n\t\t\t\tquery: \"# go-diff visibility:private\",\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"visibility:private for global includes only private\",\n\t\t\t\t// expect a match because # private is only in a private repo.\n\t\t\t\tquery: \"# private visibility:private\",\n\t\t\t\tzeroResult: false,\n\t\t\t},\n\t\t\t// Repo search\n\t\t\t{\n\t\t\t\tname: \"repo search by name, case yes, nonzero result\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ String case:yes type:file`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"non-master branch, nonzero result\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/java-langserver$@v1 void sendPartialResult(Object requestId, JsonPatch jsonPatch); patterntype:literal type:file`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"indexed multiline search, nonzero result\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/java-langserver$ \\nimport index:only patterntype:regexp type:file`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"unindexed multiline search, nonzero result\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/java-langserver$ \\nimport index:no patterntype:regexp type:file`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"random characters, zero result\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/java-langserver$ doesnot734734743734743exist`,\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t// Filename search\n\t\t\t{\n\t\t\t\tname: \"search for a known file\",\n\t\t\t\tquery: \"file:doc.go\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"search for a non-existent file\",\n\t\t\t\tquery: \"file:asdfasdf.go\",\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t// Symbol search\n\t\t\t{\n\t\t\t\tname: \"search for a known symbol\",\n\t\t\t\tquery: \"type:symbol count:100 patterntype:regexp ^newroute\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"search for a non-existent symbol\",\n\t\t\t\tquery: \"type:symbol asdfasdf\",\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t// Commit search\n\t\t\t{\n\t\t\t\tname: \"commit search, nonzero result\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ type:commit`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"commit search, non-existent ref\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$@ref/noexist type:commit`,\n\t\t\t\tzeroResult: true,\n\t\t\t\twantAlert: &gqltestutil.SearchAlert{\n\t\t\t\t\tTitle: \"Some repositories could not be searched\",\n\t\t\t\t\tDescription: `The repository github.com/sgtest/go-diff matched by your repo: filter could not be searched because it does not contain the revision \"ref/noexist\".`,\n\t\t\t\t\tProposedQueries: nil,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"commit search, non-zero result message\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/sourcegraph-typescript$ type:commit message:test`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"commit search, non-zero result pattern\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/sourcegraph-typescript$ type:commit test`,\n\t\t\t},\n\t\t\t// Diff search\n\t\t\t{\n\t\t\t\tname: \"diff search, nonzero result\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ type:diff main`,\n\t\t\t},\n\t\t\t// Repohascommitafter\n\t\t\t{\n\t\t\t\tname: `Repohascommitafter, nonzero result`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ repohascommitafter:\"2019-01-01\" test patterntype:literal`,\n\t\t\t},\n\t\t\t// Regex text search\n\t\t\t{\n\t\t\t\tname: `regex, unindexed, nonzero result`,\n\t\t\t\tquery: `^func.*$ patterntype:regexp index:only type:file`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `regex, fork only, nonzero result`,\n\t\t\t\tquery: `fork:only patterntype:regexp FORK_SENTINEL`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `regex, filter by language`,\n\t\t\t\tquery: `\\bfunc\\b lang:go type:file patterntype:regexp`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `regex, filename, zero results`,\n\t\t\t\tquery: `file:asdfasdf.go patterntype:regexp`,\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `regexp, filename, nonzero result`,\n\t\t\t\tquery: `file:doc.go patterntype:regexp`,\n\t\t\t},", "", "\t\t}\n\t\tfor _, test := range tests {\n\t\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t\tdoSkip(t, test.skip)", "\t\t\t\tresults, err := client.SearchFiles(test.query)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}", "\t\t\t\tif diff := cmp.Diff(test.wantAlert, results.Alert); diff != \"\" {\n\t\t\t\t\tt.Fatalf(\"Alert mismatch (-want +got):\\n%s\", diff)\n\t\t\t\t}", "\t\t\t\tif test.zeroResult {\n\t\t\t\t\tif len(results.Results) > 0 {\n\t\t\t\t\t\tt.Fatalf(\"Want zero result but got %d\", len(results.Results))\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif len(results.Results) == 0 {\n\t\t\t\t\t\tt.Fatal(\"Want non-zero results but got 0\")\n\t\t\t\t\t}\n\t\t\t\t}", "\t\t\t\tif results.MatchCount < test.minMatchCount {\n\t\t\t\t\tt.Fatalf(\"Want at least %d match count but got %d\", test.minMatchCount, results.MatchCount)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})", "\tt.Run(\"structural search\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname string\n\t\t\tquery string\n\t\t\tzeroResult bool\n\t\t\twantAlert *gqltestutil.SearchAlert\n\t\t}{\n\t\t\t{\n\t\t\t\tname: \"Structural, index only, nonzero result\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ make(:[1]) index:only patterntype:structural count:3`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"Structural, index only, backcompat, nonzero result\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ make(:[1]) lang:go rule:'where \"backcompat\" == \"backcompat\"' patterntype:structural`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"Structural, unindexed, nonzero result\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$@adde71 make(:[1]) index:no patterntype:structural count:3`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Structural search quotes are interpreted literally`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/sourcegraph-typescript$ file:^README\\.md \"basic :[_] access :[_]\" patterntype:structural`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Alert to activate structural search mode for :[...] syntax`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ patterntype:literal i can't :[believe] it's not butter`,\n\t\t\t\tzeroResult: true,\n\t\t\t\twantAlert: &gqltestutil.SearchAlert{\n\t\t\t\t\tTitle: \"No results\",\n\t\t\t\t\tDescription: \"It looks like you may have meant to run a structural search, but it is not toggled.\",\n\t\t\t\t\tProposedQueries: []gqltestutil.ProposedQuery{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tDescription: \"Activate structural search\",\n\t\t\t\t\t\t\tQuery: `repo:^github\\.com/sgtest/go-diff$ patterntype:literal i can't :[believe] it's not butter patternType:structural`,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Alert to activate structural search mode for ... syntax`,\n\t\t\t\tquery: `no results for { ... } raises alert repo:^github\\.com/sgtest/go-diff$`,\n\t\t\t\tzeroResult: true,\n\t\t\t\twantAlert: &gqltestutil.SearchAlert{\n\t\t\t\t\tTitle: \"No results\",\n\t\t\t\t\tDescription: \"It looks like you may have meant to run a structural search, but it is not toggled.\",\n\t\t\t\t\tProposedQueries: []gqltestutil.ProposedQuery{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tDescription: \"Activate structural search\",\n\t\t\t\t\t\t\tQuery: `no results for { ... } raises alert repo:^github\\.com/sgtest/go-diff$ patternType:structural`,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\tfor _, test := range tests {\n\t\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t\tresults, err := client.SearchFiles(test.query)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}", "\t\t\t\tif diff := cmp.Diff(test.wantAlert, results.Alert); diff != \"\" {\n\t\t\t\t\tt.Fatalf(\"Alert mismatch (-want +got):\\n%s\", diff)\n\t\t\t\t}", "\t\t\t\tif test.zeroResult {\n\t\t\t\t\tif len(results.Results) > 0 {\n\t\t\t\t\t\tt.Fatalf(\"Want zero result but got %d\", len(results.Results))\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif len(results.Results) == 0 {\n\t\t\t\t\t\tt.Fatal(\"Want non-zero results but got 0\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})", "\tt.Run(\"And/Or queries\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname string\n\t\t\tquery string\n\t\t\tzeroResult bool\n\t\t\twantAlert *gqltestutil.SearchAlert\n\t\t}{\n\t\t\t{\n\t\t\t\tname: `And operator, basic`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ func and main type:file`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Or operator, single and double quoted`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ \"func PrintMultiFileDiff\" or 'func readLine(' type:file patterntype:regexp`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literals, grouped parens with parens-as-patterns heuristic`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ (() or ()) type:file patterntype:regexp`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literals, no grouped parens`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ () or () type:file patterntype:regexp`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literals, escaped parens`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ \\(\\) or \\(\\) type:file patterntype:regexp`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literals, escaped and unescaped parens, no group`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ () or \\(\\) type:file patterntype:regexp`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literals, escaped and unescaped parens, grouped`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ (() or \\(\\)) type:file patterntype:regexp`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literals, double paren`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ ()() or ()()`,\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literals, double paren, dangling paren right side`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ ()() or main()(`,\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literals, double paren, dangling paren left side`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ ()( or ()()`,\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Mixed regexp and literal`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ patternType:regexp func(.*) or does_not_exist_3744 type:file`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Mixed regexp and literal heuristic`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ func( or func(.*) type:file`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Mixed regexp and quoted literal`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ \"*\" and cert.*Load type:file`,\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Escape sequences`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ patternType:regexp \\' and \\\" and \\\\ and /`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Escaped whitespace sequences with 'and'`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ patternType:regexp \\ and /`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Concat converted to spaces for literal search`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ file:^diff/print\\.go t := or ts Time patterntype:literal`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literal parentheses match pattern`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff file:^diff/print\\.go Bytes() and Time() patterntype:literal`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literals, simple not keyword inside group`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ (not .svg) patterntype:literal`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literals, not keyword and implicit and inside group`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ (a/foo not .svg) patterntype:literal`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literals, not and and keyword inside group`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ (a/foo and not .svg) patterntype:literal`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Dangling right parens, supported via content: filter`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ content:\"diffPath)\" and main patterntype:literal`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Dangling right parens, unsupported in literal search`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ diffPath) and main patterntype:literal`,\n\t\t\t\tzeroResult: true,\n\t\t\t\twantAlert: &gqltestutil.SearchAlert{\n\t\t\t\t\tTitle: \"Unable To Process Query\",\n\t\t\t\t\tDescription: \"Unsupported expression. The combination of parentheses in the query have an unclear meaning. Try using the content: filter to quote patterns that contain parentheses\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Dangling right parens, unsupported in literal search, double parens`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ MarshalTo and OrigName)) patterntype:literal`,\n\t\t\t\tzeroResult: true,\n\t\t\t\twantAlert: &gqltestutil.SearchAlert{\n\t\t\t\t\tTitle: \"Unable To Process Query\",\n\t\t\t\t\tDescription: \"Unsupported expression. The combination of parentheses in the query have an unclear meaning. Try using the content: filter to quote patterns that contain parentheses\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Dangling right parens, unsupported in literal search, simple group before right paren`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ MarshalTo and (m.OrigName)) patterntype:literal`,\n\t\t\t\tzeroResult: true,\n\t\t\t\twantAlert: &gqltestutil.SearchAlert{\n\t\t\t\t\tTitle: \"Unable To Process Query\",\n\t\t\t\t\tDescription: \"Unsupported expression. The combination of parentheses in the query have an unclear meaning. Try using the content: filter to quote patterns that contain parentheses\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Dangling right parens, heuristic for literal search, cannot succeed, too confusing`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ (respObj.Size and (data))) patterntype:literal`,\n\t\t\t\tzeroResult: true,\n\t\t\t\twantAlert: &gqltestutil.SearchAlert{\n\t\t\t\t\tTitle: \"Unable To Process Query\",\n\t\t\t\t\tDescription: \"Unsupported expression. The combination of parentheses in the query have an unclear meaning. Try using the content: filter to quote patterns that contain parentheses\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `No result for confusing grouping`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff file:^README\\.md (bar and (foo or x\\) ()) patterntype:literal`,\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Successful grouping removes alert`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff file:^README\\.md (bar and (foo or (x\\) ())) patterntype:literal`,\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `No dangling right paren with complex group for literal search`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ (m *FileDiff and (data)) patterntype:literal`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Concat converted to .* for regexp search`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ file:^diff/print\\.go t := or ts Time patterntype:regexp type:file`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Structural search uses literal search parser`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ file:^diff/print\\.go :[[v]] := ts and printFileHeader(:[_]) patterntype:structural`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Union file matches per file and accurate counts`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff file:^diff/print\\.go func or package`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Intersect file matches per file and accurate counts`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff file:^diff/print\\.go func and package`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Simple combined union and intersect file matches per file and accurate counts`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff file:^diff/print\\.go ((func timePtr and package diff) or return buf.Bytes())`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Complex union of intersect file matches per file and accurate counts`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff file:^diff/print\\.go ((func timePtr and package diff) or (ts == nil and ts.Time()))`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Complex intersect of union file matches per file and accurate counts`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff file:^diff/print\\.go ((func timePtr or package diff) and (ts == nil or ts.Time()))`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Intersect file matches per file against an empty result set`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff file:^diff/print\\.go func and doesnotexist838338`,\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Dedupe union operation`,\n\t\t\t\tquery: `file:diff.go|print.go|parse.go repo:^github\\.com/sgtest/go-diff _, :[[x]] := range :[src.] { :[_] } or if :[s1] == :[s2] patterntype:structural`,\n\t\t\t},\n\t\t}\n\t\tfor _, test := range tests {\n\t\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t\tresults, err := client.SearchFiles(test.query)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}", "\t\t\t\tif diff := cmp.Diff(test.wantAlert, results.Alert); diff != \"\" {\n\t\t\t\t\tt.Fatalf(\"Alert mismatch (-want +got):\\n%s\", diff)\n\t\t\t\t}", "\t\t\t\tif test.zeroResult {\n\t\t\t\t\tif len(results.Results) > 0 {\n\t\t\t\t\t\tt.Fatalf(\"Want zero result but got %d\", len(results.Results))\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif len(results.Results) == 0 {\n\t\t\t\t\t\tt.Fatal(\"Want non-zero results but got 0\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})", "\tt.Run(\"And/Or search expression queries\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname string\n\t\t\tquery string\n\t\t\tzeroResult bool\n\t\t\texactMatchCount int64\n\t\t\twantAlert *gqltestutil.SearchAlert\n\t\t\tskip int\n\t\t}{\n\t\t\t{\n\t\t\t\tname: `Or distributive property on content and file`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/sourcegraph-typescript$ (Fetches OR file:language-server.ts)`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Or distributive property on nested file on content`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/sourcegraph-typescript$ ((file:^renovate\\.json extends) or file:progress.ts createProgressProvider)`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Or distributive property on commit`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/sourcegraph-typescript$ (type:diff or type:commit) author:felix yarn`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Or match on both diff and commit returns both`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/sourcegraph-typescript$ (type:diff or type:commit) subscription after:\"june 11 2019\" before:\"june 13 2019\"`,\n\t\t\t\texactMatchCount: 2,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Or distributive property on rev`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/mux$ (rev:v1.7.3 or revision:v1.7.2)`,\n\t\t\t\texactMatchCount: 2,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Or distributive property on rev with file`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/mux$ (rev:v1.7.3 or revision:v1.7.2) file:README.md`,\n\t\t\t\texactMatchCount: 2,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Or distributive property on repo`,\n\t\t\t\tquery: `(repo:^github\\.com/sgtest/go-diff$@garo/lsif-indexing-campaign:test-already-exist-pr or repo:^github\\.com/sgtest/sourcegraph-typescript$) file:README.md #`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Or distributive property on repo where only one repo contains match (tests repo cache is invalidated)`,\n\t\t\t\tquery: `(repo:^github\\.com/sgtest/sourcegraph-typescript$ or repo:^github\\.com/sgtest/go-diff$) package diff provides`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Or distributive property on commits deduplicates and merges`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ type:commit (message:add or message:file)`,\n\t\t\t\texactMatchCount: 21,\n\t\t\t\tskip: skipStream,\n\t\t\t},\n\t\t}\n\t\tfor _, test := range tests {\n\t\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t\tdoSkip(t, test.skip)", "\t\t\t\tresults, err := client.SearchFiles(test.query)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}", "\t\t\t\tif diff := cmp.Diff(test.wantAlert, results.Alert); diff != \"\" {\n\t\t\t\t\tt.Fatalf(\"Alert mismatch (-want +got):\\n%s\", diff)\n\t\t\t\t}", "\t\t\t\tif test.zeroResult {\n\t\t\t\t\tif len(results.Results) > 0 {\n\t\t\t\t\t\tt.Fatalf(\"Want zero result but got %d\", len(results.Results))\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif len(results.Results) == 0 {\n\t\t\t\t\t\tt.Fatal(\"Want non-zero results but got 0\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif test.exactMatchCount != 0 && results.MatchCount != test.exactMatchCount {\n\t\t\t\t\tt.Fatalf(\"Want exactly %d results but got %d\", test.exactMatchCount, results.MatchCount)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})", "\ttype counts struct {\n\t\tRepo int\n\t\tCommit int\n\t\tContent int\n\t\tSymbol int\n\t\tFile int\n\t}", "\tcountResults := func(results []*gqltestutil.AnyResult) counts {\n\t\tvar count counts\n\t\tfor _, res := range results {\n\t\t\tswitch v := res.Inner.(type) {\n\t\t\tcase gqltestutil.CommitResult:\n\t\t\t\tcount.Commit += 1\n\t\t\tcase gqltestutil.RepositoryResult:\n\t\t\t\tcount.Repo += 1\n\t\t\tcase gqltestutil.FileResult:\n\t\t\t\tcount.Symbol += len(v.Symbols)\n\t\t\t\tfor _, lm := range v.LineMatches {\n\t\t\t\t\tcount.Content += len(lm.OffsetAndLengths)\n\t\t\t\t}\n\t\t\t\tif len(v.Symbols) == 0 && len(v.LineMatches) == 0 {\n\t\t\t\t\tcount.File += 1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn count\n\t}", "\tt.Run(\"Predicate Queries\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname string\n\t\t\tquery string\n\t\t\tcounts counts\n\t\t}{\n\t\t\t{\n\t\t\t\tname: `repo contains file`,\n\t\t\t\tquery: `repo:contains(file:go\\.mod)`,\n\t\t\t\tcounts: counts{Repo: 2},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `no repo contains file`,\n\t\t\t\tquery: `repo:contains(file:noexist.go)`,\n\t\t\t\tcounts: counts{},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `no repo contains file with pattern`,\n\t\t\t\tquery: `repo:contains(file:noexist.go) test`,\n\t\t\t\tcounts: counts{},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `repo contains content`,\n\t\t\t\tquery: `repo:contains(content:nextFileFirstLine)`,\n\t\t\t\tcounts: counts{Repo: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `repo contains content scoped predicate`,\n\t\t\t\tquery: `repo:contains.content(nextFileFirstLine)`,\n\t\t\t\tcounts: counts{Repo: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `or-expression on repo:contains`,\n\t\t\t\tquery: `repo:contains(content:does-not-exist-D2E1E74C7279) or repo:contains(content:nextFileFirstLine)`,\n\t\t\t\tcounts: counts{Repo: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `and-expression on repo:contains`,\n\t\t\t\tquery: `repo:contains(content:does-not-exist-D2E1E74C7279) and repo:contains(content:nextFileFirstLine)`,\n\t\t\t\tcounts: counts{Repo: 0},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `repo contains file then search common`,\n\t\t\t\tquery: `repo:contains(file:go.mod) count:100 fmt`,\n\t\t\t\tcounts: counts{Content: 61},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `repo contains file scoped predicate`,\n\t\t\t\tquery: `repo:contains.file(go.mod) count:100 fmt`,\n\t\t\t\tcounts: counts{Content: 61},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `repo contains with matching repo filter`,\n\t\t\t\tquery: `repo:go-diff repo:contains(file:diff.proto)`,\n\t\t\t\tcounts: counts{Repo: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `repo contains with non-matching repo filter`,\n\t\t\t\tquery: `repo:nonexist repo:contains(file:diff.proto)`,\n\t\t\t\tcounts: counts{Repo: 0},\n\t\t\t},\n\t\t\t{\n\t\t\t\t`repo contains respects parameters that affect repo search (fork)`,\n\t\t\t\t`repo:sgtest/mux fork:yes repo:contains.file(README)`,\n\t\t\t\tcounts{Repo: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `commit results without repo filter`,\n\t\t\t\tquery: `type:commit LSIF`,\n\t\t\t\tcounts: counts{Commit: 9},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `commit results with repo filter`,\n\t\t\t\tquery: `repo:contains(file:diff.pb.go) type:commit LSIF`,\n\t\t\t\tcounts: counts{Commit: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `predicate logic does not conflict with unrecognized patterns`,\n\t\t\t\tquery: `repo:sg(test)`,\n\t\t\t\tcounts: counts{Repo: 6},\n\t\t\t},\n\t\t\t{\n\t\t\t\t`repo has commit after`,\n\t\t\t\t`repo:go-diff repo:contains.commit.after(10 years ago)`,\n\t\t\t\tcounts{Repo: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\t`repo has commit after no results`,\n\t\t\t\t`repo:go-diff repo:contains.commit.after(1 second ago)`,\n\t\t\t\tcounts{Repo: 0},\n\t\t\t},\n\t\t\t{\n\t\t\t\t`unscoped repo has commit after no results`,\n\t\t\t\t`repo:contains.commit.after(1 second ago)`,\n\t\t\t\tcounts{Repo: 0},\n\t\t\t},\n\t\t}", "\t\tfor _, test := range tests {\n\t\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t\tresults, err := client.SearchAll(test.query)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}", "\t\t\t\tcount := countResults(results)\n\t\t\t\tif diff := cmp.Diff(test.counts, count); diff != \"\" {\n\t\t\t\t\tt.Fatalf(\"mismatch (-want +got):\\n%s\", diff)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})", "\tt.Run(\"Select Queries\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname string\n\t\t\tquery string\n\t\t\tcounts counts\n\t\t}{\n\t\t\t{\n\t\t\t\tname: `select repo`,\n\t\t\t\tquery: `repo:go-diff patterntype:literal HunkNoChunksize select:repo`,\n\t\t\t\tcounts: counts{Repo: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `select repo, only repo`,\n\t\t\t\tquery: `repo:go-diff select:repo`,\n\t\t\t\tcounts: counts{Repo: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `select repo, only file`,\n\t\t\t\tquery: `file:go-diff.go select:repo`,\n\t\t\t\tcounts: counts{Repo: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `select file`,\n\t\t\t\tquery: `repo:go-diff patterntype:literal HunkNoChunksize select:file`,\n\t\t\t\tcounts: counts{File: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `or statement merges file`,\n\t\t\t\tquery: `repo:go-diff HunkNoChunksize or ParseHunksAndPrintHunks select:file`,\n\t\t\t\tcounts: counts{File: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `select file.directory`,\n\t\t\t\tquery: `repo:go-diff HunkNoChunksize or diffFile *os.File select:file.directory`,\n\t\t\t\tcounts: counts{File: 2},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `select content`,\n\t\t\t\tquery: `repo:go-diff patterntype:literal HunkNoChunksize select:content`,\n\t\t\t\tcounts: counts{Content: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `no select`,\n\t\t\t\tquery: `repo:go-diff patterntype:literal HunkNoChunksize`,\n\t\t\t\tcounts: counts{Content: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `select commit, no results`,\n\t\t\t\tquery: `repo:go-diff patterntype:literal HunkNoChunksize select:commit`,\n\t\t\t\tcounts: counts{},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `select symbol, no results`,\n\t\t\t\tquery: `repo:go-diff patterntype:literal HunkNoChunksize select:symbol`,\n\t\t\t\tcounts: counts{},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `select symbol`,\n\t\t\t\tquery: `repo:go-diff patterntype:literal type:symbol HunkNoChunksize select:symbol`,\n\t\t\t\tcounts: counts{Symbol: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `search diffs with file start anchor`,\n\t\t\t\tquery: `repo:go-diff patterntype:literal type:diff file:^README.md$ installing`,\n\t\t\t\tcounts: counts{Commit: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\t// https://github.com/sourcegraph/sourcegraph/issues/21031\n\t\t\t\tname: `search diffs with file filter and time filters`,\n\t\t\t\tquery: `repo:go-diff patterntype:literal type:diff lang:go before:\"May 10 2020\" after:\"May 5 2020\" unquotedOrigName`,\n\t\t\t\tcounts: counts{Commit: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `select diffs with added lines containing pattern`,\n\t\t\t\tquery: `repo:go-diff patterntype:literal type:diff select:commit.diff.added sample_binary_inline`,\n\t\t\t\tcounts: counts{Commit: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `select diffs with removed lines containing pattern`,\n\t\t\t\tquery: `repo:go-diff patterntype:literal type:diff select:commit.diff.removed sample_binary_inline`,\n\t\t\t\tcounts: counts{Commit: 0},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `file contains content predicate`, // equivalent to the `select file` test\n\t\t\t\tquery: `repo:go-diff patterntype:literal file:contains.content(HunkNoChunkSize)`,\n\t\t\t\tcounts: counts{File: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `file contains content predicate type diff`,\n\t\t\t\tquery: `type:diff repo:go-diff file:contains(after_success)`, // matches .travis.yml and its 10 commits\n\t\t\t\tcounts: counts{Commit: 10},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `select repo on 'and' operation`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ (func and main) select:repo`,\n\t\t\t\tcounts: counts{Repo: 1},\n\t\t\t},\n\t\t}", "\t\tfor _, test := range tests {\n\t\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t\tif test.name == \"select symbol\" {\n\t\t\t\t\tt.Skip(\"streaming not supported yet\")\n\t\t\t\t}", "\t\t\t\tresults, err := client.SearchAll(test.query)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}", "\t\t\t\tcount := countResults(results)\n\t\t\t\tif diff := cmp.Diff(test.counts, count); diff != \"\" {\n\t\t\t\t\tt.Fatalf(\"mismatch (-want +got):\\n%s\", diff)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})", "\tt.Run(\"Exact Counts\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname string\n\t\t\tquery string\n\t\t\tcounts counts\n\t\t}{\n\t\t\t{\n\t\t\t\tname: `no duplicate commits (#19460)`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/sourcegraph-typescript$ type:commit author:felix count:1000 before:\"march 25 2021\"`,\n\t\t\t\tcounts: counts{Commit: 317},\n\t\t\t},\n\t\t}", "\t\tfor _, test := range tests {\n\t\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t\tresults, err := client.SearchAll(test.query)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}", "\t\t\t\tcount := countResults(results)\n\t\t\t\tif diff := cmp.Diff(test.counts, count); diff != \"\" {\n\t\t\t\t\tt.Fatalf(\"mismatch (-want +got):\\n%s\", diff)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})\n}", "// testSearchOther other contains search tests for parts of the GraphQL API\n// which are not replicated in the streaming API (statistics and suggestions).\nfunc testSearchOther(t *testing.T) {\n\tt.Run(\"Suggestions\", func(t *testing.T) {\n\t\trepo1, err := client.Repository(\"github.com/sgtest/java-langserver\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\trepo2, err := client.Repository(\"github.com/sgtest/jsonrpc2\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}", "\t\tscID1, err := client.CreateSearchContext(\n\t\t\tgqltestutil.CreateSearchContextInput{Name: \"SuggestionSearchContext\", Public: true},\n\t\t\t[]gqltestutil.SearchContextRepositoryRevisionsInput{\n\t\t\t\t{RepositoryID: repo1.ID, Revisions: []string{\"HEAD\"}},\n\t\t\t\t{RepositoryID: repo2.ID, Revisions: []string{\"HEAD\"}},\n\t\t\t})\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tscID2, err := client.CreateSearchContext(gqltestutil.CreateSearchContextInput{Name: \"EmptySearchContext\", Public: true}, []gqltestutil.SearchContextRepositoryRevisionsInput{})\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tdefer func() {\n\t\t\terr = client.DeleteSearchContext(scID1)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\terr = client.DeleteSearchContext(scID2)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t}()", "\t\ttests := []struct {\n\t\t\tquery string\n\t\t\tsuggestionCount int\n\t\t}{\n\t\t\t{query: `repo:sourcegraph-typescript$ type:file file:deploy`, suggestionCount: 12},\n\t\t\t{query: `context:SuggestionSearchContext repo:`, suggestionCount: 3},\n\t\t\t{query: `context:Empty`, suggestionCount: 1},\n\t\t}", "\t\tfor _, test := range tests {\n\t\t\tt.Run(test.query, func(t *testing.T) {\n\t\t\t\tresults, err := client.SearchSuggestions(test.query)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}", "\t\t\t\tif len(results) != test.suggestionCount {\n\t\t\t\t\tt.Fatalf(\"expected %d results, but got %d\", test.suggestionCount, len(results))\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})", "\tt.Run(\"search statistics\", func(t *testing.T) {\n\t\terr := client.OverwriteSettings(client.AuthenticatedUserID(), `{\"experimentalFeatures\":{\"searchStats\": true}}`)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tdefer func() {\n\t\t\terr := client.OverwriteSettings(client.AuthenticatedUserID(), `{}`)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t}()", "\t\tvar lastResult *gqltestutil.SearchStatsResult\n\t\t// Retry because the configuration update endpoint is eventually consistent\n\t\terr = gqltestutil.Retry(5*time.Second, func() error {\n\t\t\t// This is a substring that appears in the sgtest/go-diff repository.\n\t\t\t// It is OK if it starts to appear in other repositories, the test just\n\t\t\t// checks that it is found in at least 1 Go file.\n\t\t\tresult, err := client.SearchStats(\"Incomplete-Lines\")\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tlastResult = result", "\t\t\tfor _, lang := range result.Languages {\n\t\t\t\tif strings.EqualFold(lang.Name, \"Go\") {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}", "\t\t\treturn gqltestutil.ErrContinueRetry\n\t\t})\n\t\tif err != nil {\n\t\t\tt.Fatal(err, \"lastResult:\", lastResult)\n\t\t}\n\t})\n}", "func testSearchContextsCRUD(t *testing.T, client *gqltestutil.Client) {\n\trepo1, err := client.Repository(\"github.com/sgtest/java-langserver\")\n\trequire.NoError(t, err)\n\trepo2, err := client.Repository(\"github.com/sgtest/jsonrpc2\")\n\trequire.NoError(t, err)", "\t// Create a search context\n\tscName := \"TestSearchContext\" + strconv.Itoa(int(rand.Int31()))\n\tscID, err := client.CreateSearchContext(\n\t\tgqltestutil.CreateSearchContextInput{Name: scName, Description: \"test description\", Public: true},\n\t\t[]gqltestutil.SearchContextRepositoryRevisionsInput{\n\t\t\t{RepositoryID: repo1.ID, Revisions: []string{\"HEAD\"}},\n\t\t\t{RepositoryID: repo2.ID, Revisions: []string{\"HEAD\"}},\n\t\t},\n\t)\n\trequire.NoError(t, err)\n\tdefer client.DeleteSearchContext(scID)", "\t// Retrieve the search context and check that it has the correct fields\n\tresultContext, err := client.GetSearchContext(scID)\n\trequire.NoError(t, err)\n\trequire.Equal(t, scName, resultContext.Spec)\n\trequire.Equal(t, \"test description\", resultContext.Description)", "\t// Update the search context\n\tupdatedSCName := \"TestUpdated\" + strconv.Itoa(int(rand.Int31()))\n\tscID, err = client.UpdateSearchContext(\n\t\tscID,\n\t\tgqltestutil.UpdateSearchContextInput{\n\t\t\tName: updatedSCName,\n\t\t\tPublic: false,\n\t\t\tDescription: \"Updated description\",\n\t\t},\n\t\t[]gqltestutil.SearchContextRepositoryRevisionsInput{\n\t\t\t{RepositoryID: repo1.ID, Revisions: []string{\"HEAD\"}},\n\t\t},\n\t)\n\trequire.NoError(t, err)", "\t// Retrieve the search context and check that it has the updated fields\n\tresultContext, err = client.GetSearchContext(scID)\n\trequire.NoError(t, err)\n\trequire.Equal(t, updatedSCName, resultContext.Spec)\n\trequire.Equal(t, \"Updated description\", resultContext.Description)", "\t// Delete the context\n\terr = client.DeleteSearchContext(scID)\n\trequire.NoError(t, err)", "\t// Check that retrieving the deleted search context fails\n\t_, err = client.GetSearchContext(scID)\n\trequire.Error(t, err)\n}", "func testListingSearchContexts(t *testing.T, client *gqltestutil.Client) {\n\tnumSearchContexts := 10\n\tsearchContextIDs := make([]string, 0, numSearchContexts)\n\tfor i := 0; i < numSearchContexts; i++ {\n\t\tscID, err := client.CreateSearchContext(\n\t\t\tgqltestutil.CreateSearchContextInput{Name: fmt.Sprintf(\"SearchContext%d\", i), Public: true},\n\t\t\t[]gqltestutil.SearchContextRepositoryRevisionsInput{},\n\t\t)\n\t\trequire.NoError(t, err)\n\t\tsearchContextIDs = append(searchContextIDs, scID)\n\t}\n\tdefer func() {\n\t\tfor i := 0; i < numSearchContexts; i++ {\n\t\t\terr := client.DeleteSearchContext(searchContextIDs[i])\n\t\t\trequire.NoError(t, err)\n\t\t}\n\t}()", "\torderBySpec := gqltestutil.SearchContextsOrderBySpec\n\tresultFirstPage, err := client.ListSearchContexts(gqltestutil.ListSearchContextsOptions{\n\t\tFirst: 5,\n\t\tOrderBy: &orderBySpec,\n\t\tDescending: true,\n\t})\n\trequire.NoError(t, err)\n\tif len(resultFirstPage.Nodes) != 5 {\n\t\tt.Fatalf(\"expected 5 search contexts, got %d\", len(resultFirstPage.Nodes))\n\t}\n\tif resultFirstPage.Nodes[0].Spec != \"SearchContext9\" {\n\t\tt.Fatalf(\"expected first page first search context spec to be SearchContext9, got %s\", resultFirstPage.Nodes[0].Spec)\n\t}", "\tresultSecondPage, err := client.ListSearchContexts(gqltestutil.ListSearchContextsOptions{\n\t\tFirst: 5,\n\t\tAfter: resultFirstPage.PageInfo.EndCursor,\n\t\tOrderBy: &orderBySpec,\n\t\tDescending: true,\n\t})\n\trequire.NoError(t, err)\n\tif len(resultSecondPage.Nodes) != 5 {\n\t\tt.Fatalf(\"expected 5 search contexts, got %d\", len(resultSecondPage.Nodes))\n\t}\n\tif resultSecondPage.Nodes[0].Spec != \"SearchContext4\" {\n\t\tt.Fatalf(\"expected second page search context spec to be SearchContext4, got %s\", resultSecondPage.Nodes[0].Spec)\n\t}\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [26, 1516, 36, 537], "buggy_code_start_loc": [26, 39, 33, 537], "filenames": ["CHANGELOG.md", "cmd/frontend/graphqlbackend/search_results.go", "dev/gqltest/README.md", "dev/gqltest/search_test.go"], "fixing_code_end_loc": [35, 1518, 36, 544], "fixing_code_start_loc": [27, 40, 33, 538], "message": "Sourcegraph is a code search and navigation engine. Sourcegraph prior to version 3.33.2 is vulnerable to a side-channel attack where strings in private source code could be guessed by an authenticated but unauthorized actor. This issue affects the Saved Searches and Code Monitoring features. A successful attack would require an authenticated bad actor to create many Saved Searches or Code Monitors to receive confirmation that a specific string exists. This could allow an attacker to guess formatted tokens in source code, such as API keys. This issue was patched in version 3.33.2 and any future versions of Sourcegraph. We strongly encourage upgrading to secure versions. If you are unable to, you may disable Saved Searches and Code Monitors.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sourcegraph:sourcegraph:*:*:*:*:*:*:*:*", "matchCriteriaId": "8AC67147-DAE3-4326-9027-0DEB53C55D32", "versionEndExcluding": "3.33.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Sourcegraph is a code search and navigation engine. Sourcegraph prior to version 3.33.2 is vulnerable to a side-channel attack where strings in private source code could be guessed by an authenticated but unauthorized actor. This issue affects the Saved Searches and Code Monitoring features. A successful attack would require an authenticated bad actor to create many Saved Searches or Code Monitors to receive confirmation that a specific string exists. This could allow an attacker to guess formatted tokens in source code, such as API keys. This issue was patched in version 3.33.2 and any future versions of Sourcegraph. We strongly encourage upgrading to secure versions. If you are unable to, you may disable Saved Searches and Code Monitors."}, {"lang": "es", "value": "Sourcegraph es un motor de b\u00fasqueda y navegaci\u00f3n de c\u00f3digo. Sourcegraph versiones anteriores a 3.33.2 es vulnerable a un ataque de canal lateral en el que las cadenas del c\u00f3digo fuente privado podr\u00edan ser adivinadas por un actor autenticado pero no autorizado. Este problema afecta a las funciones de B\u00fasquedas Guardadas y Monitorizaci\u00f3n de C\u00f3digo. Un ataque con \u00e9xito requerir\u00eda que un actor malo autenticado creara muchas B\u00fasquedas Guardadas o Monitores de C\u00f3digo para recibir la confirmaci\u00f3n de que una cadena espec\u00edfica esta presente. Esto podr\u00eda permitir a un atacante adivinar los tokens formateados en el c\u00f3digo fuente, como las claves de la API. Este problema ha sido parcheado en la versi\u00f3n 3.33.2 y en las futuras versiones de Sourcegraph. Recomendamos encarecidamente que se actualice a las versiones seguras. Si no puede hacerlo, puede deshabilitar las B\u00fasquedas Guardadas y los Monitores de C\u00f3digo"}], "evaluatorComment": null, "id": "CVE-2021-43823", "lastModified": "2021-12-16T15:00:25.970", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Primary"}]}, "published": "2021-12-13T20:15:07.813", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/sourcegraph/sourcegraph/commit/a88d90a8302c492282186d39718cd8fb093c14fa"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/sourcegraph/sourcegraph/security/advisories/GHSA-cpq7-hmvv-29w9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-203"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/sourcegraph/sourcegraph/commit/a88d90a8302c492282186d39718cd8fb093c14fa"}, "type": "CWE-203"}
326
Determine whether the {function_name} code is vulnerable or not.
[ "package main", "import (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"", "\t\"github.com/google/go-cmp/cmp\"\n\t\"github.com/stretchr/testify/require\"", "\t\"github.com/sourcegraph/sourcegraph/internal/extsvc\"\n\t\"github.com/sourcegraph/sourcegraph/internal/gqltestutil\"\n)", "func TestSearch(t *testing.T) {\n\tif len(*githubToken) == 0 {\n\t\tt.Skip(\"Environment variable GITHUB_TOKEN is not set\")\n\t}", "\t// Set up external service\n\tesID, err := client.AddExternalService(gqltestutil.AddExternalServiceInput{\n\t\tKind: extsvc.KindGitHub,\n\t\tDisplayName: \"gqltest-github-search\",\n\t\tConfig: mustMarshalJSONString(struct {\n\t\t\tURL string `json:\"url\"`\n\t\t\tToken string `json:\"token\"`\n\t\t\tRepos []string `json:\"repos\"`\n\t\t\tRepositoryPathPattern string `json:\"repositoryPathPattern\"`\n\t\t}{\n\t\t\tURL: \"https://ghe.sgdev.org/\",\n\t\t\tToken: *githubToken,\n\t\t\tRepos: []string{\n\t\t\t\t\"sgtest/java-langserver\",\n\t\t\t\t\"sgtest/jsonrpc2\",\n\t\t\t\t\"sgtest/go-diff\",\n\t\t\t\t\"sgtest/appdash\",\n\t\t\t\t\"sgtest/sourcegraph-typescript\",\n\t\t\t\t\"sgtest/private\", // Private\n\t\t\t\t\"sgtest/mux\", // Fork\n\t\t\t\t\"sgtest/archived\", // Archived\n\t\t\t},\n\t\t\tRepositoryPathPattern: \"github.com/{nameWithOwner}\",\n\t\t}),\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer func() {\n\t\terr := client.DeleteExternalService(esID)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()", "\terr = client.WaitForReposToBeCloned(\n\t\t\"github.com/sgtest/java-langserver\",\n\t\t\"github.com/sgtest/jsonrpc2\",\n\t\t\"github.com/sgtest/go-diff\",\n\t\t\"github.com/sgtest/appdash\",\n\t\t\"github.com/sgtest/sourcegraph-typescript\",\n\t\t\"github.com/sgtest/private\", // Private\n\t\t\"github.com/sgtest/mux\", // Fork\n\t\t\"github.com/sgtest/archived\", // Archived\n\t)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}", "\terr = client.WaitForReposToBeIndex(\n\t\t\"github.com/sgtest/java-langserver\",\n\t)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}", "\tt.Run(\"search contexts\", func(t *testing.T) {\n\t\ttestSearchContextsCRUD(t, client)\n\t\ttestListingSearchContexts(t, client)\n\t})", "\tt.Run(\"graphql\", func(t *testing.T) {\n\t\ttestSearchClient(t, client)\n\t})\n\tt.Run(\"stream\", func(t *testing.T) {\n\t\ttestSearchClient(t, &gqltestutil.SearchStreamClient{\n\t\t\tClient: client,\n\t\t})\n\t})", "\ttestSearchOther(t)\n}", "// searchClient is an interface so we can swap out a streaming vs graphql\n// based search API. It only supports the methods that streaming supports.\ntype searchClient interface {\n\tSearchRepositories(query string) (gqltestutil.SearchRepositoryResults, error)\n\tSearchFiles(query string) (*gqltestutil.SearchFileResults, error)\n\tSearchAll(query string) ([]*gqltestutil.AnyResult, error)", "\tOverwriteSettings(subjectID, contents string) error\n\tAuthenticatedUserID() string\n}", "func testSearchClient(t *testing.T, client searchClient) {\n\t// Temporary test until we have equivalence.\n\t_, isStreaming := client.(*gqltestutil.SearchStreamClient)", "\tconst (\n\t\tskipStream = 1 << iota\n\t\tskipGraphQL\n\t)\n\tdoSkip := func(t *testing.T, skip int) {\n\t\tt.Helper()\n\t\tif skip&skipStream != 0 && isStreaming {\n\t\t\tt.Skip(\"does not support streaming\")\n\t\t}\n\t\tif skip&skipGraphQL != 0 && !isStreaming {\n\t\t\tt.Skip(\"does not support graphql\")\n\t\t}\n\t}", "\tt.Run(\"visibility\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tquery string\n\t\t\twantMissing []string\n\t\t}{\n\t\t\t{\n\t\t\t\tquery: \"type:repo visibility:private sgtest\",\n\t\t\t\twantMissing: []string{},\n\t\t\t},\n\t\t\t{\n\t\t\t\tquery: \"type:repo visibility:public sgtest\",\n\t\t\t\twantMissing: []string{\"github.com/sgtest/private\"},\n\t\t\t},\n\t\t\t{\n\t\t\t\tquery: \"type:repo visibility:any sgtest\",\n\t\t\t\twantMissing: []string{},\n\t\t\t},\n\t\t}\n\t\tfor _, test := range tests {\n\t\t\tt.Run(test.query, func(t *testing.T) {\n\t\t\t\tresults, err := client.SearchRepositories(test.query)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t\tmissing := results.Exists(\"github.com/sgtest/private\")\n\t\t\t\tif diff := cmp.Diff(test.wantMissing, missing); diff != \"\" {\n\t\t\t\t\tt.Fatalf(\"Missing mismatch (-want +got):\\n%s\", diff)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})", "\tt.Run(\"execute search with search parameters\", func(t *testing.T) {\n\t\tresults, err := client.SearchFiles(\"repo:^github.com/sgtest/go-diff$ type:file file:.go -file:.md\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}", "\t\t// Make sure only got .go files and no .md files\n\t\tfor _, r := range results.Results {\n\t\t\tif !strings.HasSuffix(r.File.Name, \".go\") {\n\t\t\t\tt.Fatalf(\"Found file name does not end with .go: %s\", r.File.Name)\n\t\t\t}\n\t\t}\n\t})", "\tt.Run(\"lang: filter\", func(t *testing.T) {\n\t\t// On our test repositories, `function` has results for go, ts, python, html\n\t\tresults, err := client.SearchFiles(\"function lang:go\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\t// Make sure we only got .go files\n\t\tfor _, r := range results.Results {\n\t\t\tif !strings.Contains(r.File.Name, \".go\") {\n\t\t\t\tt.Fatalf(\"Found file name does not end with .go: %s\", r.File.Name)\n\t\t\t}\n\t\t}\n\t})", "\tt.Run(\"excluding repositories\", func(t *testing.T) {\n\t\tresults, err := client.SearchFiles(\"fmt.Sprintf -repo:jsonrpc2\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\t// Make sure we got some results\n\t\tif len(results.Results) == 0 {\n\t\t\tt.Fatal(\"Want non-zero results but got 0\")\n\t\t}\n\t\t// Make sure we got no results from the excluded repository\n\t\tfor _, r := range results.Results {\n\t\t\tif strings.Contains(r.Repository.Name, \"jsonrpc2\") {\n\t\t\t\tt.Fatal(\"Got results for excluded repository\")\n\t\t\t}\n\t\t}\n\t})", "\tt.Run(\"multiple revisions per repository\", func(t *testing.T) {\n\t\tresults, err := client.SearchFiles(\"repo:sgtest/go-diff$@master:print-options:*refs/heads/ func NewHunksReader\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}", "\t\twantExprs := map[string]struct{}{\n\t\t\t\"master\": {},\n\t\t\t\"print-options\": {},", "\t\t\t// These next 2 branches are included because of the *refs/heads/ in the query.\n\t\t\t\"test-already-exist-pr\": {},\n\t\t\t\"bug-fix-wip\": {},\n\t\t}", "\t\tfor _, r := range results.Results {\n\t\t\tdelete(wantExprs, r.RevSpec.Expr)\n\t\t}", "\t\tif len(wantExprs) > 0 {\n\t\t\tmissing := make([]string, 0, len(wantExprs))\n\t\t\tfor expr := range wantExprs {\n\t\t\t\tmissing = append(missing, expr)\n\t\t\t}\n\t\t\tt.Fatalf(\"Missing exprs: %v\", missing)\n\t\t}\n\t})", "\tt.Run(\"repository groups\", func(t *testing.T) {\n\t\tconst repoName = \"github.com/sgtest/go-diff\"\n\t\terr := client.OverwriteSettings(client.AuthenticatedUserID(), fmt.Sprintf(`{\"search.repositoryGroups\":{\"gql_test_group\": [\"%s\"]}}`, repoName))\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tdefer func() {\n\t\t\terr := client.OverwriteSettings(client.AuthenticatedUserID(), `{}`)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t}()", "\t\tresults, err := client.SearchFiles(\"repogroup:gql_test_group diff.\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}", "\t\t// Make sure there are results and all results are from the same repository\n\t\tif len(results.Results) == 0 {\n\t\t\tt.Fatal(\"Unexpected zero result\")\n\t\t}\n\t\tfor _, r := range results.Results {\n\t\t\tif r.Repository.Name != repoName {\n\t\t\t\tt.Fatalf(\"Repository: want %q but got %q\", repoName, r.Repository.Name)\n\t\t\t}\n\t\t}\n\t})", "\tt.Run(\"repository search\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname string\n\t\t\tquery string\n\t\t\tzeroResult bool\n\t\t\twantMissing []string\n\t\t}{\n\t\t\t{\n\t\t\t\tname: `archived excluded, zero results`,\n\t\t\t\tquery: `type:repo archived`,\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `archived included, nonzero result`,\n\t\t\t\tquery: `type:repo archived archived:yes`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `archived included if exact without option, nonzero result`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/archived$`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `fork excluded, zero results`,\n\t\t\t\tquery: `type:repo sgtest/mux`,\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `fork included, nonzero result`,\n\t\t\t\tquery: `type:repo sgtest/mux fork:yes`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `fork included if exact without option, nonzero result`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/mux$`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"repohasfile returns results for global search\",\n\t\t\t\tquery: \"repohasfile:README\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"multiple repohasfile returns no results if one doesn't match\",\n\t\t\t\tquery: \"repohasfile:README repohasfile:thisfiledoesnotexist_1571751\",\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"repo search by name, nonzero result\",\n\t\t\t\tquery: \"repo:go-diff$\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"true is an alias for yes when fork is set\",\n\t\t\t\tquery: `repo:github\\.com/sgtest/mux fork:true`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `exclude counts for fork and archive`,\n\t\t\t\tquery: `repo:mux|archived|go-diff`,\n\t\t\t\twantMissing: []string{\n\t\t\t\t\t\"github.com/sgtest/archived\",\n\t\t\t\t\t\"github.com/sgtest/mux\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Structural search returns repo results if patterntype set but pattern is empty`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/sourcegraph-typescript$ patterntype:structural`,\n\t\t\t},\n\t\t}\n\t\tfor _, test := range tests {\n\t\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t\tresults, err := client.SearchRepositories(test.query)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}", "\t\t\t\tif test.zeroResult {\n\t\t\t\t\tif len(results) > 0 {\n\t\t\t\t\t\tt.Fatalf(\"Want zero result but got %d\", len(results))\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif len(results) == 0 {\n\t\t\t\t\t\tt.Fatal(\"Want non-zero results but got 0\")\n\t\t\t\t\t}\n\t\t\t\t}", "\t\t\t\tif test.wantMissing != nil {\n\t\t\t\t\tmissing := results.Exists(test.wantMissing...)\n\t\t\t\t\tsort.Strings(missing)\n\t\t\t\t\tif diff := cmp.Diff(test.wantMissing, missing); diff != \"\" {\n\t\t\t\t\t\tt.Fatalf(\"Missing mismatch (-want +got):\\n%s\", diff)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})", "\tt.Run(\"global text search\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname string\n\t\t\tquery string\n\t\t\tzeroResult bool\n\t\t\tminMatchCount int64\n\t\t\twantAlert *gqltestutil.SearchAlert\n\t\t\tskip int\n\t\t}{\n\t\t\t// Global search\n\t\t\t{\n\t\t\t\tname: \"error\",\n\t\t\t\tquery: \"error\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"error count:1000\",\n\t\t\t\tquery: \"error count:1000\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"something with more than 1000 results and use count:1000\",\n\t\t\t\tquery: \". count:1000\",\n\t\t\t\tminMatchCount: 1000,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"default limit streaming\",\n\t\t\t\tquery: \".\",\n\t\t\t\tminMatchCount: 500,\n\t\t\t\tskip: skipGraphQL,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"default limit graphql\",\n\t\t\t\tquery: \".\",\n\t\t\t\tminMatchCount: 30,\n\t\t\t\tskip: skipStream,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"regular expression without indexed search\",\n\t\t\t\tquery: \"index:no patterntype:regexp ^func.*$\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"fork:only\",\n\t\t\t\tquery: \"fork:only router\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"double-quoted pattern, nonzero result\",\n\t\t\t\tquery: `\"func main() {\\n\" patterntype:regexp type:file`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"exclude repo, nonzero result\",\n\t\t\t\tquery: `\"func main() {\\n\" -repo:go-diff patterntype:regexp type:file`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"fork:no\",\n\t\t\t\tquery: \"fork:no FORK\" + \"_SENTINEL\",\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"fork:yes\",\n\t\t\t\tquery: \"fork:yes FORK\" + \"_SENTINEL\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"random characters, zero results\",\n\t\t\t\tquery: \"asdfalksd+jflaksjdfklas patterntype:literal -repo:sourcegraph\",\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t// Global search visibility\n\t\t\t{\n\t\t\t\tname: \"visibility:all for global search includes private repo\",\n\t\t\t\t// match content in a private repo sgtest/private and a public repo sgtest/go-diff.\n\t\t\t\tquery: `(#\\ private|#\\ go-diff) visibility:all patterntype:regexp`,\n\t\t\t\tminMatchCount: 2,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"visibility:public for global search excludes private repo\",\n\t\t\t\t// expect no matches because pattern '# private' is only in a private repo.\n\t\t\t\tquery: \"# private visibility:public\",\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"visibility:private for global includes only private repo\",\n\t\t\t\t// expect no matches because #go-diff doesn't exist in private repo.\n\t\t\t\tquery: \"# go-diff visibility:private\",\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"visibility:private for global includes only private\",\n\t\t\t\t// expect a match because # private is only in a private repo.\n\t\t\t\tquery: \"# private visibility:private\",\n\t\t\t\tzeroResult: false,\n\t\t\t},\n\t\t\t// Repo search\n\t\t\t{\n\t\t\t\tname: \"repo search by name, case yes, nonzero result\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ String case:yes type:file`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"non-master branch, nonzero result\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/java-langserver$@v1 void sendPartialResult(Object requestId, JsonPatch jsonPatch); patterntype:literal type:file`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"indexed multiline search, nonzero result\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/java-langserver$ \\nimport index:only patterntype:regexp type:file`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"unindexed multiline search, nonzero result\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/java-langserver$ \\nimport index:no patterntype:regexp type:file`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"random characters, zero result\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/java-langserver$ doesnot734734743734743exist`,\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t// Filename search\n\t\t\t{\n\t\t\t\tname: \"search for a known file\",\n\t\t\t\tquery: \"file:doc.go\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"search for a non-existent file\",\n\t\t\t\tquery: \"file:asdfasdf.go\",\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t// Symbol search\n\t\t\t{\n\t\t\t\tname: \"search for a known symbol\",\n\t\t\t\tquery: \"type:symbol count:100 patterntype:regexp ^newroute\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"search for a non-existent symbol\",\n\t\t\t\tquery: \"type:symbol asdfasdf\",\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t// Commit search\n\t\t\t{\n\t\t\t\tname: \"commit search, nonzero result\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ type:commit`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"commit search, non-existent ref\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$@ref/noexist type:commit`,\n\t\t\t\tzeroResult: true,\n\t\t\t\twantAlert: &gqltestutil.SearchAlert{\n\t\t\t\t\tTitle: \"Some repositories could not be searched\",\n\t\t\t\t\tDescription: `The repository github.com/sgtest/go-diff matched by your repo: filter could not be searched because it does not contain the revision \"ref/noexist\".`,\n\t\t\t\t\tProposedQueries: nil,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"commit search, non-zero result message\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/sourcegraph-typescript$ type:commit message:test`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"commit search, non-zero result pattern\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/sourcegraph-typescript$ type:commit test`,\n\t\t\t},\n\t\t\t// Diff search\n\t\t\t{\n\t\t\t\tname: \"diff search, nonzero result\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ type:diff main`,\n\t\t\t},\n\t\t\t// Repohascommitafter\n\t\t\t{\n\t\t\t\tname: `Repohascommitafter, nonzero result`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ repohascommitafter:\"2019-01-01\" test patterntype:literal`,\n\t\t\t},\n\t\t\t// Regex text search\n\t\t\t{\n\t\t\t\tname: `regex, unindexed, nonzero result`,\n\t\t\t\tquery: `^func.*$ patterntype:regexp index:only type:file`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `regex, fork only, nonzero result`,\n\t\t\t\tquery: `fork:only patterntype:regexp FORK_SENTINEL`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `regex, filter by language`,\n\t\t\t\tquery: `\\bfunc\\b lang:go type:file patterntype:regexp`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `regex, filename, zero results`,\n\t\t\t\tquery: `file:asdfasdf.go patterntype:regexp`,\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `regexp, filename, nonzero result`,\n\t\t\t\tquery: `file:doc.go patterntype:regexp`,\n\t\t\t},", "\t\t\t// Ensure repo resolution is correct in global. https://github.com/sourcegraph/sourcegraph/issues/27044\n\t\t\t{\n\t\t\t\tname: `-repo excludes private repos`,\n\t\t\t\tquery: `-repo:private // this is a change`,\n\t\t\t\tzeroResult: true,\n\t\t\t},", "\t\t}\n\t\tfor _, test := range tests {\n\t\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t\tdoSkip(t, test.skip)", "\t\t\t\tresults, err := client.SearchFiles(test.query)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}", "\t\t\t\tif diff := cmp.Diff(test.wantAlert, results.Alert); diff != \"\" {\n\t\t\t\t\tt.Fatalf(\"Alert mismatch (-want +got):\\n%s\", diff)\n\t\t\t\t}", "\t\t\t\tif test.zeroResult {\n\t\t\t\t\tif len(results.Results) > 0 {\n\t\t\t\t\t\tt.Fatalf(\"Want zero result but got %d\", len(results.Results))\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif len(results.Results) == 0 {\n\t\t\t\t\t\tt.Fatal(\"Want non-zero results but got 0\")\n\t\t\t\t\t}\n\t\t\t\t}", "\t\t\t\tif results.MatchCount < test.minMatchCount {\n\t\t\t\t\tt.Fatalf(\"Want at least %d match count but got %d\", test.minMatchCount, results.MatchCount)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})", "\tt.Run(\"structural search\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname string\n\t\t\tquery string\n\t\t\tzeroResult bool\n\t\t\twantAlert *gqltestutil.SearchAlert\n\t\t}{\n\t\t\t{\n\t\t\t\tname: \"Structural, index only, nonzero result\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ make(:[1]) index:only patterntype:structural count:3`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"Structural, index only, backcompat, nonzero result\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ make(:[1]) lang:go rule:'where \"backcompat\" == \"backcompat\"' patterntype:structural`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"Structural, unindexed, nonzero result\",\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$@adde71 make(:[1]) index:no patterntype:structural count:3`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Structural search quotes are interpreted literally`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/sourcegraph-typescript$ file:^README\\.md \"basic :[_] access :[_]\" patterntype:structural`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Alert to activate structural search mode for :[...] syntax`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ patterntype:literal i can't :[believe] it's not butter`,\n\t\t\t\tzeroResult: true,\n\t\t\t\twantAlert: &gqltestutil.SearchAlert{\n\t\t\t\t\tTitle: \"No results\",\n\t\t\t\t\tDescription: \"It looks like you may have meant to run a structural search, but it is not toggled.\",\n\t\t\t\t\tProposedQueries: []gqltestutil.ProposedQuery{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tDescription: \"Activate structural search\",\n\t\t\t\t\t\t\tQuery: `repo:^github\\.com/sgtest/go-diff$ patterntype:literal i can't :[believe] it's not butter patternType:structural`,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Alert to activate structural search mode for ... syntax`,\n\t\t\t\tquery: `no results for { ... } raises alert repo:^github\\.com/sgtest/go-diff$`,\n\t\t\t\tzeroResult: true,\n\t\t\t\twantAlert: &gqltestutil.SearchAlert{\n\t\t\t\t\tTitle: \"No results\",\n\t\t\t\t\tDescription: \"It looks like you may have meant to run a structural search, but it is not toggled.\",\n\t\t\t\t\tProposedQueries: []gqltestutil.ProposedQuery{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tDescription: \"Activate structural search\",\n\t\t\t\t\t\t\tQuery: `no results for { ... } raises alert repo:^github\\.com/sgtest/go-diff$ patternType:structural`,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\tfor _, test := range tests {\n\t\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t\tresults, err := client.SearchFiles(test.query)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}", "\t\t\t\tif diff := cmp.Diff(test.wantAlert, results.Alert); diff != \"\" {\n\t\t\t\t\tt.Fatalf(\"Alert mismatch (-want +got):\\n%s\", diff)\n\t\t\t\t}", "\t\t\t\tif test.zeroResult {\n\t\t\t\t\tif len(results.Results) > 0 {\n\t\t\t\t\t\tt.Fatalf(\"Want zero result but got %d\", len(results.Results))\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif len(results.Results) == 0 {\n\t\t\t\t\t\tt.Fatal(\"Want non-zero results but got 0\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})", "\tt.Run(\"And/Or queries\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname string\n\t\t\tquery string\n\t\t\tzeroResult bool\n\t\t\twantAlert *gqltestutil.SearchAlert\n\t\t}{\n\t\t\t{\n\t\t\t\tname: `And operator, basic`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ func and main type:file`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Or operator, single and double quoted`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ \"func PrintMultiFileDiff\" or 'func readLine(' type:file patterntype:regexp`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literals, grouped parens with parens-as-patterns heuristic`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ (() or ()) type:file patterntype:regexp`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literals, no grouped parens`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ () or () type:file patterntype:regexp`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literals, escaped parens`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ \\(\\) or \\(\\) type:file patterntype:regexp`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literals, escaped and unescaped parens, no group`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ () or \\(\\) type:file patterntype:regexp`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literals, escaped and unescaped parens, grouped`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ (() or \\(\\)) type:file patterntype:regexp`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literals, double paren`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ ()() or ()()`,\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literals, double paren, dangling paren right side`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ ()() or main()(`,\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literals, double paren, dangling paren left side`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ ()( or ()()`,\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Mixed regexp and literal`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ patternType:regexp func(.*) or does_not_exist_3744 type:file`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Mixed regexp and literal heuristic`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ func( or func(.*) type:file`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Mixed regexp and quoted literal`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ \"*\" and cert.*Load type:file`,\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Escape sequences`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ patternType:regexp \\' and \\\" and \\\\ and /`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Escaped whitespace sequences with 'and'`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ patternType:regexp \\ and /`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Concat converted to spaces for literal search`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ file:^diff/print\\.go t := or ts Time patterntype:literal`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literal parentheses match pattern`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff file:^diff/print\\.go Bytes() and Time() patterntype:literal`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literals, simple not keyword inside group`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ (not .svg) patterntype:literal`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literals, not keyword and implicit and inside group`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ (a/foo not .svg) patterntype:literal`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Literals, not and and keyword inside group`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ (a/foo and not .svg) patterntype:literal`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Dangling right parens, supported via content: filter`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ content:\"diffPath)\" and main patterntype:literal`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Dangling right parens, unsupported in literal search`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ diffPath) and main patterntype:literal`,\n\t\t\t\tzeroResult: true,\n\t\t\t\twantAlert: &gqltestutil.SearchAlert{\n\t\t\t\t\tTitle: \"Unable To Process Query\",\n\t\t\t\t\tDescription: \"Unsupported expression. The combination of parentheses in the query have an unclear meaning. Try using the content: filter to quote patterns that contain parentheses\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Dangling right parens, unsupported in literal search, double parens`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ MarshalTo and OrigName)) patterntype:literal`,\n\t\t\t\tzeroResult: true,\n\t\t\t\twantAlert: &gqltestutil.SearchAlert{\n\t\t\t\t\tTitle: \"Unable To Process Query\",\n\t\t\t\t\tDescription: \"Unsupported expression. The combination of parentheses in the query have an unclear meaning. Try using the content: filter to quote patterns that contain parentheses\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Dangling right parens, unsupported in literal search, simple group before right paren`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ MarshalTo and (m.OrigName)) patterntype:literal`,\n\t\t\t\tzeroResult: true,\n\t\t\t\twantAlert: &gqltestutil.SearchAlert{\n\t\t\t\t\tTitle: \"Unable To Process Query\",\n\t\t\t\t\tDescription: \"Unsupported expression. The combination of parentheses in the query have an unclear meaning. Try using the content: filter to quote patterns that contain parentheses\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Dangling right parens, heuristic for literal search, cannot succeed, too confusing`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ (respObj.Size and (data))) patterntype:literal`,\n\t\t\t\tzeroResult: true,\n\t\t\t\twantAlert: &gqltestutil.SearchAlert{\n\t\t\t\t\tTitle: \"Unable To Process Query\",\n\t\t\t\t\tDescription: \"Unsupported expression. The combination of parentheses in the query have an unclear meaning. Try using the content: filter to quote patterns that contain parentheses\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `No result for confusing grouping`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff file:^README\\.md (bar and (foo or x\\) ()) patterntype:literal`,\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Successful grouping removes alert`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff file:^README\\.md (bar and (foo or (x\\) ())) patterntype:literal`,\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `No dangling right paren with complex group for literal search`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ (m *FileDiff and (data)) patterntype:literal`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Concat converted to .* for regexp search`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ file:^diff/print\\.go t := or ts Time patterntype:regexp type:file`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Structural search uses literal search parser`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ file:^diff/print\\.go :[[v]] := ts and printFileHeader(:[_]) patterntype:structural`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Union file matches per file and accurate counts`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff file:^diff/print\\.go func or package`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Intersect file matches per file and accurate counts`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff file:^diff/print\\.go func and package`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Simple combined union and intersect file matches per file and accurate counts`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff file:^diff/print\\.go ((func timePtr and package diff) or return buf.Bytes())`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Complex union of intersect file matches per file and accurate counts`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff file:^diff/print\\.go ((func timePtr and package diff) or (ts == nil and ts.Time()))`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Complex intersect of union file matches per file and accurate counts`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff file:^diff/print\\.go ((func timePtr or package diff) and (ts == nil or ts.Time()))`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Intersect file matches per file against an empty result set`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff file:^diff/print\\.go func and doesnotexist838338`,\n\t\t\t\tzeroResult: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Dedupe union operation`,\n\t\t\t\tquery: `file:diff.go|print.go|parse.go repo:^github\\.com/sgtest/go-diff _, :[[x]] := range :[src.] { :[_] } or if :[s1] == :[s2] patterntype:structural`,\n\t\t\t},\n\t\t}\n\t\tfor _, test := range tests {\n\t\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t\tresults, err := client.SearchFiles(test.query)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}", "\t\t\t\tif diff := cmp.Diff(test.wantAlert, results.Alert); diff != \"\" {\n\t\t\t\t\tt.Fatalf(\"Alert mismatch (-want +got):\\n%s\", diff)\n\t\t\t\t}", "\t\t\t\tif test.zeroResult {\n\t\t\t\t\tif len(results.Results) > 0 {\n\t\t\t\t\t\tt.Fatalf(\"Want zero result but got %d\", len(results.Results))\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif len(results.Results) == 0 {\n\t\t\t\t\t\tt.Fatal(\"Want non-zero results but got 0\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})", "\tt.Run(\"And/Or search expression queries\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname string\n\t\t\tquery string\n\t\t\tzeroResult bool\n\t\t\texactMatchCount int64\n\t\t\twantAlert *gqltestutil.SearchAlert\n\t\t\tskip int\n\t\t}{\n\t\t\t{\n\t\t\t\tname: `Or distributive property on content and file`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/sourcegraph-typescript$ (Fetches OR file:language-server.ts)`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Or distributive property on nested file on content`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/sourcegraph-typescript$ ((file:^renovate\\.json extends) or file:progress.ts createProgressProvider)`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Or distributive property on commit`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/sourcegraph-typescript$ (type:diff or type:commit) author:felix yarn`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Or match on both diff and commit returns both`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/sourcegraph-typescript$ (type:diff or type:commit) subscription after:\"june 11 2019\" before:\"june 13 2019\"`,\n\t\t\t\texactMatchCount: 2,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Or distributive property on rev`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/mux$ (rev:v1.7.3 or revision:v1.7.2)`,\n\t\t\t\texactMatchCount: 2,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Or distributive property on rev with file`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/mux$ (rev:v1.7.3 or revision:v1.7.2) file:README.md`,\n\t\t\t\texactMatchCount: 2,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Or distributive property on repo`,\n\t\t\t\tquery: `(repo:^github\\.com/sgtest/go-diff$@garo/lsif-indexing-campaign:test-already-exist-pr or repo:^github\\.com/sgtest/sourcegraph-typescript$) file:README.md #`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Or distributive property on repo where only one repo contains match (tests repo cache is invalidated)`,\n\t\t\t\tquery: `(repo:^github\\.com/sgtest/sourcegraph-typescript$ or repo:^github\\.com/sgtest/go-diff$) package diff provides`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `Or distributive property on commits deduplicates and merges`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ type:commit (message:add or message:file)`,\n\t\t\t\texactMatchCount: 21,\n\t\t\t\tskip: skipStream,\n\t\t\t},\n\t\t}\n\t\tfor _, test := range tests {\n\t\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t\tdoSkip(t, test.skip)", "\t\t\t\tresults, err := client.SearchFiles(test.query)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}", "\t\t\t\tif diff := cmp.Diff(test.wantAlert, results.Alert); diff != \"\" {\n\t\t\t\t\tt.Fatalf(\"Alert mismatch (-want +got):\\n%s\", diff)\n\t\t\t\t}", "\t\t\t\tif test.zeroResult {\n\t\t\t\t\tif len(results.Results) > 0 {\n\t\t\t\t\t\tt.Fatalf(\"Want zero result but got %d\", len(results.Results))\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif len(results.Results) == 0 {\n\t\t\t\t\t\tt.Fatal(\"Want non-zero results but got 0\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif test.exactMatchCount != 0 && results.MatchCount != test.exactMatchCount {\n\t\t\t\t\tt.Fatalf(\"Want exactly %d results but got %d\", test.exactMatchCount, results.MatchCount)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})", "\ttype counts struct {\n\t\tRepo int\n\t\tCommit int\n\t\tContent int\n\t\tSymbol int\n\t\tFile int\n\t}", "\tcountResults := func(results []*gqltestutil.AnyResult) counts {\n\t\tvar count counts\n\t\tfor _, res := range results {\n\t\t\tswitch v := res.Inner.(type) {\n\t\t\tcase gqltestutil.CommitResult:\n\t\t\t\tcount.Commit += 1\n\t\t\tcase gqltestutil.RepositoryResult:\n\t\t\t\tcount.Repo += 1\n\t\t\tcase gqltestutil.FileResult:\n\t\t\t\tcount.Symbol += len(v.Symbols)\n\t\t\t\tfor _, lm := range v.LineMatches {\n\t\t\t\t\tcount.Content += len(lm.OffsetAndLengths)\n\t\t\t\t}\n\t\t\t\tif len(v.Symbols) == 0 && len(v.LineMatches) == 0 {\n\t\t\t\t\tcount.File += 1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn count\n\t}", "\tt.Run(\"Predicate Queries\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname string\n\t\t\tquery string\n\t\t\tcounts counts\n\t\t}{\n\t\t\t{\n\t\t\t\tname: `repo contains file`,\n\t\t\t\tquery: `repo:contains(file:go\\.mod)`,\n\t\t\t\tcounts: counts{Repo: 2},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `no repo contains file`,\n\t\t\t\tquery: `repo:contains(file:noexist.go)`,\n\t\t\t\tcounts: counts{},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `no repo contains file with pattern`,\n\t\t\t\tquery: `repo:contains(file:noexist.go) test`,\n\t\t\t\tcounts: counts{},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `repo contains content`,\n\t\t\t\tquery: `repo:contains(content:nextFileFirstLine)`,\n\t\t\t\tcounts: counts{Repo: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `repo contains content scoped predicate`,\n\t\t\t\tquery: `repo:contains.content(nextFileFirstLine)`,\n\t\t\t\tcounts: counts{Repo: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `or-expression on repo:contains`,\n\t\t\t\tquery: `repo:contains(content:does-not-exist-D2E1E74C7279) or repo:contains(content:nextFileFirstLine)`,\n\t\t\t\tcounts: counts{Repo: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `and-expression on repo:contains`,\n\t\t\t\tquery: `repo:contains(content:does-not-exist-D2E1E74C7279) and repo:contains(content:nextFileFirstLine)`,\n\t\t\t\tcounts: counts{Repo: 0},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `repo contains file then search common`,\n\t\t\t\tquery: `repo:contains(file:go.mod) count:100 fmt`,\n\t\t\t\tcounts: counts{Content: 61},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `repo contains file scoped predicate`,\n\t\t\t\tquery: `repo:contains.file(go.mod) count:100 fmt`,\n\t\t\t\tcounts: counts{Content: 61},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `repo contains with matching repo filter`,\n\t\t\t\tquery: `repo:go-diff repo:contains(file:diff.proto)`,\n\t\t\t\tcounts: counts{Repo: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `repo contains with non-matching repo filter`,\n\t\t\t\tquery: `repo:nonexist repo:contains(file:diff.proto)`,\n\t\t\t\tcounts: counts{Repo: 0},\n\t\t\t},\n\t\t\t{\n\t\t\t\t`repo contains respects parameters that affect repo search (fork)`,\n\t\t\t\t`repo:sgtest/mux fork:yes repo:contains.file(README)`,\n\t\t\t\tcounts{Repo: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `commit results without repo filter`,\n\t\t\t\tquery: `type:commit LSIF`,\n\t\t\t\tcounts: counts{Commit: 9},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `commit results with repo filter`,\n\t\t\t\tquery: `repo:contains(file:diff.pb.go) type:commit LSIF`,\n\t\t\t\tcounts: counts{Commit: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `predicate logic does not conflict with unrecognized patterns`,\n\t\t\t\tquery: `repo:sg(test)`,\n\t\t\t\tcounts: counts{Repo: 6},\n\t\t\t},\n\t\t\t{\n\t\t\t\t`repo has commit after`,\n\t\t\t\t`repo:go-diff repo:contains.commit.after(10 years ago)`,\n\t\t\t\tcounts{Repo: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\t`repo has commit after no results`,\n\t\t\t\t`repo:go-diff repo:contains.commit.after(1 second ago)`,\n\t\t\t\tcounts{Repo: 0},\n\t\t\t},\n\t\t\t{\n\t\t\t\t`unscoped repo has commit after no results`,\n\t\t\t\t`repo:contains.commit.after(1 second ago)`,\n\t\t\t\tcounts{Repo: 0},\n\t\t\t},\n\t\t}", "\t\tfor _, test := range tests {\n\t\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t\tresults, err := client.SearchAll(test.query)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}", "\t\t\t\tcount := countResults(results)\n\t\t\t\tif diff := cmp.Diff(test.counts, count); diff != \"\" {\n\t\t\t\t\tt.Fatalf(\"mismatch (-want +got):\\n%s\", diff)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})", "\tt.Run(\"Select Queries\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname string\n\t\t\tquery string\n\t\t\tcounts counts\n\t\t}{\n\t\t\t{\n\t\t\t\tname: `select repo`,\n\t\t\t\tquery: `repo:go-diff patterntype:literal HunkNoChunksize select:repo`,\n\t\t\t\tcounts: counts{Repo: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `select repo, only repo`,\n\t\t\t\tquery: `repo:go-diff select:repo`,\n\t\t\t\tcounts: counts{Repo: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `select repo, only file`,\n\t\t\t\tquery: `file:go-diff.go select:repo`,\n\t\t\t\tcounts: counts{Repo: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `select file`,\n\t\t\t\tquery: `repo:go-diff patterntype:literal HunkNoChunksize select:file`,\n\t\t\t\tcounts: counts{File: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `or statement merges file`,\n\t\t\t\tquery: `repo:go-diff HunkNoChunksize or ParseHunksAndPrintHunks select:file`,\n\t\t\t\tcounts: counts{File: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `select file.directory`,\n\t\t\t\tquery: `repo:go-diff HunkNoChunksize or diffFile *os.File select:file.directory`,\n\t\t\t\tcounts: counts{File: 2},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `select content`,\n\t\t\t\tquery: `repo:go-diff patterntype:literal HunkNoChunksize select:content`,\n\t\t\t\tcounts: counts{Content: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `no select`,\n\t\t\t\tquery: `repo:go-diff patterntype:literal HunkNoChunksize`,\n\t\t\t\tcounts: counts{Content: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `select commit, no results`,\n\t\t\t\tquery: `repo:go-diff patterntype:literal HunkNoChunksize select:commit`,\n\t\t\t\tcounts: counts{},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `select symbol, no results`,\n\t\t\t\tquery: `repo:go-diff patterntype:literal HunkNoChunksize select:symbol`,\n\t\t\t\tcounts: counts{},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `select symbol`,\n\t\t\t\tquery: `repo:go-diff patterntype:literal type:symbol HunkNoChunksize select:symbol`,\n\t\t\t\tcounts: counts{Symbol: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `search diffs with file start anchor`,\n\t\t\t\tquery: `repo:go-diff patterntype:literal type:diff file:^README.md$ installing`,\n\t\t\t\tcounts: counts{Commit: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\t// https://github.com/sourcegraph/sourcegraph/issues/21031\n\t\t\t\tname: `search diffs with file filter and time filters`,\n\t\t\t\tquery: `repo:go-diff patterntype:literal type:diff lang:go before:\"May 10 2020\" after:\"May 5 2020\" unquotedOrigName`,\n\t\t\t\tcounts: counts{Commit: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `select diffs with added lines containing pattern`,\n\t\t\t\tquery: `repo:go-diff patterntype:literal type:diff select:commit.diff.added sample_binary_inline`,\n\t\t\t\tcounts: counts{Commit: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `select diffs with removed lines containing pattern`,\n\t\t\t\tquery: `repo:go-diff patterntype:literal type:diff select:commit.diff.removed sample_binary_inline`,\n\t\t\t\tcounts: counts{Commit: 0},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `file contains content predicate`, // equivalent to the `select file` test\n\t\t\t\tquery: `repo:go-diff patterntype:literal file:contains.content(HunkNoChunkSize)`,\n\t\t\t\tcounts: counts{File: 1},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `file contains content predicate type diff`,\n\t\t\t\tquery: `type:diff repo:go-diff file:contains(after_success)`, // matches .travis.yml and its 10 commits\n\t\t\t\tcounts: counts{Commit: 10},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `select repo on 'and' operation`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/go-diff$ (func and main) select:repo`,\n\t\t\t\tcounts: counts{Repo: 1},\n\t\t\t},\n\t\t}", "\t\tfor _, test := range tests {\n\t\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t\tif test.name == \"select symbol\" {\n\t\t\t\t\tt.Skip(\"streaming not supported yet\")\n\t\t\t\t}", "\t\t\t\tresults, err := client.SearchAll(test.query)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}", "\t\t\t\tcount := countResults(results)\n\t\t\t\tif diff := cmp.Diff(test.counts, count); diff != \"\" {\n\t\t\t\t\tt.Fatalf(\"mismatch (-want +got):\\n%s\", diff)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})", "\tt.Run(\"Exact Counts\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname string\n\t\t\tquery string\n\t\t\tcounts counts\n\t\t}{\n\t\t\t{\n\t\t\t\tname: `no duplicate commits (#19460)`,\n\t\t\t\tquery: `repo:^github\\.com/sgtest/sourcegraph-typescript$ type:commit author:felix count:1000 before:\"march 25 2021\"`,\n\t\t\t\tcounts: counts{Commit: 317},\n\t\t\t},\n\t\t}", "\t\tfor _, test := range tests {\n\t\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t\tresults, err := client.SearchAll(test.query)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}", "\t\t\t\tcount := countResults(results)\n\t\t\t\tif diff := cmp.Diff(test.counts, count); diff != \"\" {\n\t\t\t\t\tt.Fatalf(\"mismatch (-want +got):\\n%s\", diff)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})\n}", "// testSearchOther other contains search tests for parts of the GraphQL API\n// which are not replicated in the streaming API (statistics and suggestions).\nfunc testSearchOther(t *testing.T) {\n\tt.Run(\"Suggestions\", func(t *testing.T) {\n\t\trepo1, err := client.Repository(\"github.com/sgtest/java-langserver\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\trepo2, err := client.Repository(\"github.com/sgtest/jsonrpc2\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}", "\t\tscID1, err := client.CreateSearchContext(\n\t\t\tgqltestutil.CreateSearchContextInput{Name: \"SuggestionSearchContext\", Public: true},\n\t\t\t[]gqltestutil.SearchContextRepositoryRevisionsInput{\n\t\t\t\t{RepositoryID: repo1.ID, Revisions: []string{\"HEAD\"}},\n\t\t\t\t{RepositoryID: repo2.ID, Revisions: []string{\"HEAD\"}},\n\t\t\t})\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tscID2, err := client.CreateSearchContext(gqltestutil.CreateSearchContextInput{Name: \"EmptySearchContext\", Public: true}, []gqltestutil.SearchContextRepositoryRevisionsInput{})\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tdefer func() {\n\t\t\terr = client.DeleteSearchContext(scID1)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\terr = client.DeleteSearchContext(scID2)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t}()", "\t\ttests := []struct {\n\t\t\tquery string\n\t\t\tsuggestionCount int\n\t\t}{\n\t\t\t{query: `repo:sourcegraph-typescript$ type:file file:deploy`, suggestionCount: 12},\n\t\t\t{query: `context:SuggestionSearchContext repo:`, suggestionCount: 3},\n\t\t\t{query: `context:Empty`, suggestionCount: 1},\n\t\t}", "\t\tfor _, test := range tests {\n\t\t\tt.Run(test.query, func(t *testing.T) {\n\t\t\t\tresults, err := client.SearchSuggestions(test.query)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}", "\t\t\t\tif len(results) != test.suggestionCount {\n\t\t\t\t\tt.Fatalf(\"expected %d results, but got %d\", test.suggestionCount, len(results))\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})", "\tt.Run(\"search statistics\", func(t *testing.T) {\n\t\terr := client.OverwriteSettings(client.AuthenticatedUserID(), `{\"experimentalFeatures\":{\"searchStats\": true}}`)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tdefer func() {\n\t\t\terr := client.OverwriteSettings(client.AuthenticatedUserID(), `{}`)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t}()", "\t\tvar lastResult *gqltestutil.SearchStatsResult\n\t\t// Retry because the configuration update endpoint is eventually consistent\n\t\terr = gqltestutil.Retry(5*time.Second, func() error {\n\t\t\t// This is a substring that appears in the sgtest/go-diff repository.\n\t\t\t// It is OK if it starts to appear in other repositories, the test just\n\t\t\t// checks that it is found in at least 1 Go file.\n\t\t\tresult, err := client.SearchStats(\"Incomplete-Lines\")\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tlastResult = result", "\t\t\tfor _, lang := range result.Languages {\n\t\t\t\tif strings.EqualFold(lang.Name, \"Go\") {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}", "\t\t\treturn gqltestutil.ErrContinueRetry\n\t\t})\n\t\tif err != nil {\n\t\t\tt.Fatal(err, \"lastResult:\", lastResult)\n\t\t}\n\t})\n}", "func testSearchContextsCRUD(t *testing.T, client *gqltestutil.Client) {\n\trepo1, err := client.Repository(\"github.com/sgtest/java-langserver\")\n\trequire.NoError(t, err)\n\trepo2, err := client.Repository(\"github.com/sgtest/jsonrpc2\")\n\trequire.NoError(t, err)", "\t// Create a search context\n\tscName := \"TestSearchContext\" + strconv.Itoa(int(rand.Int31()))\n\tscID, err := client.CreateSearchContext(\n\t\tgqltestutil.CreateSearchContextInput{Name: scName, Description: \"test description\", Public: true},\n\t\t[]gqltestutil.SearchContextRepositoryRevisionsInput{\n\t\t\t{RepositoryID: repo1.ID, Revisions: []string{\"HEAD\"}},\n\t\t\t{RepositoryID: repo2.ID, Revisions: []string{\"HEAD\"}},\n\t\t},\n\t)\n\trequire.NoError(t, err)\n\tdefer client.DeleteSearchContext(scID)", "\t// Retrieve the search context and check that it has the correct fields\n\tresultContext, err := client.GetSearchContext(scID)\n\trequire.NoError(t, err)\n\trequire.Equal(t, scName, resultContext.Spec)\n\trequire.Equal(t, \"test description\", resultContext.Description)", "\t// Update the search context\n\tupdatedSCName := \"TestUpdated\" + strconv.Itoa(int(rand.Int31()))\n\tscID, err = client.UpdateSearchContext(\n\t\tscID,\n\t\tgqltestutil.UpdateSearchContextInput{\n\t\t\tName: updatedSCName,\n\t\t\tPublic: false,\n\t\t\tDescription: \"Updated description\",\n\t\t},\n\t\t[]gqltestutil.SearchContextRepositoryRevisionsInput{\n\t\t\t{RepositoryID: repo1.ID, Revisions: []string{\"HEAD\"}},\n\t\t},\n\t)\n\trequire.NoError(t, err)", "\t// Retrieve the search context and check that it has the updated fields\n\tresultContext, err = client.GetSearchContext(scID)\n\trequire.NoError(t, err)\n\trequire.Equal(t, updatedSCName, resultContext.Spec)\n\trequire.Equal(t, \"Updated description\", resultContext.Description)", "\t// Delete the context\n\terr = client.DeleteSearchContext(scID)\n\trequire.NoError(t, err)", "\t// Check that retrieving the deleted search context fails\n\t_, err = client.GetSearchContext(scID)\n\trequire.Error(t, err)\n}", "func testListingSearchContexts(t *testing.T, client *gqltestutil.Client) {\n\tnumSearchContexts := 10\n\tsearchContextIDs := make([]string, 0, numSearchContexts)\n\tfor i := 0; i < numSearchContexts; i++ {\n\t\tscID, err := client.CreateSearchContext(\n\t\t\tgqltestutil.CreateSearchContextInput{Name: fmt.Sprintf(\"SearchContext%d\", i), Public: true},\n\t\t\t[]gqltestutil.SearchContextRepositoryRevisionsInput{},\n\t\t)\n\t\trequire.NoError(t, err)\n\t\tsearchContextIDs = append(searchContextIDs, scID)\n\t}\n\tdefer func() {\n\t\tfor i := 0; i < numSearchContexts; i++ {\n\t\t\terr := client.DeleteSearchContext(searchContextIDs[i])\n\t\t\trequire.NoError(t, err)\n\t\t}\n\t}()", "\torderBySpec := gqltestutil.SearchContextsOrderBySpec\n\tresultFirstPage, err := client.ListSearchContexts(gqltestutil.ListSearchContextsOptions{\n\t\tFirst: 5,\n\t\tOrderBy: &orderBySpec,\n\t\tDescending: true,\n\t})\n\trequire.NoError(t, err)\n\tif len(resultFirstPage.Nodes) != 5 {\n\t\tt.Fatalf(\"expected 5 search contexts, got %d\", len(resultFirstPage.Nodes))\n\t}\n\tif resultFirstPage.Nodes[0].Spec != \"SearchContext9\" {\n\t\tt.Fatalf(\"expected first page first search context spec to be SearchContext9, got %s\", resultFirstPage.Nodes[0].Spec)\n\t}", "\tresultSecondPage, err := client.ListSearchContexts(gqltestutil.ListSearchContextsOptions{\n\t\tFirst: 5,\n\t\tAfter: resultFirstPage.PageInfo.EndCursor,\n\t\tOrderBy: &orderBySpec,\n\t\tDescending: true,\n\t})\n\trequire.NoError(t, err)\n\tif len(resultSecondPage.Nodes) != 5 {\n\t\tt.Fatalf(\"expected 5 search contexts, got %d\", len(resultSecondPage.Nodes))\n\t}\n\tif resultSecondPage.Nodes[0].Spec != \"SearchContext4\" {\n\t\tt.Fatalf(\"expected second page search context spec to be SearchContext4, got %s\", resultSecondPage.Nodes[0].Spec)\n\t}\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [26, 1516, 36, 537], "buggy_code_start_loc": [26, 39, 33, 537], "filenames": ["CHANGELOG.md", "cmd/frontend/graphqlbackend/search_results.go", "dev/gqltest/README.md", "dev/gqltest/search_test.go"], "fixing_code_end_loc": [35, 1518, 36, 544], "fixing_code_start_loc": [27, 40, 33, 538], "message": "Sourcegraph is a code search and navigation engine. Sourcegraph prior to version 3.33.2 is vulnerable to a side-channel attack where strings in private source code could be guessed by an authenticated but unauthorized actor. This issue affects the Saved Searches and Code Monitoring features. A successful attack would require an authenticated bad actor to create many Saved Searches or Code Monitors to receive confirmation that a specific string exists. This could allow an attacker to guess formatted tokens in source code, such as API keys. This issue was patched in version 3.33.2 and any future versions of Sourcegraph. We strongly encourage upgrading to secure versions. If you are unable to, you may disable Saved Searches and Code Monitors.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:sourcegraph:sourcegraph:*:*:*:*:*:*:*:*", "matchCriteriaId": "8AC67147-DAE3-4326-9027-0DEB53C55D32", "versionEndExcluding": "3.33.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Sourcegraph is a code search and navigation engine. Sourcegraph prior to version 3.33.2 is vulnerable to a side-channel attack where strings in private source code could be guessed by an authenticated but unauthorized actor. This issue affects the Saved Searches and Code Monitoring features. A successful attack would require an authenticated bad actor to create many Saved Searches or Code Monitors to receive confirmation that a specific string exists. This could allow an attacker to guess formatted tokens in source code, such as API keys. This issue was patched in version 3.33.2 and any future versions of Sourcegraph. We strongly encourage upgrading to secure versions. If you are unable to, you may disable Saved Searches and Code Monitors."}, {"lang": "es", "value": "Sourcegraph es un motor de b\u00fasqueda y navegaci\u00f3n de c\u00f3digo. Sourcegraph versiones anteriores a 3.33.2 es vulnerable a un ataque de canal lateral en el que las cadenas del c\u00f3digo fuente privado podr\u00edan ser adivinadas por un actor autenticado pero no autorizado. Este problema afecta a las funciones de B\u00fasquedas Guardadas y Monitorizaci\u00f3n de C\u00f3digo. Un ataque con \u00e9xito requerir\u00eda que un actor malo autenticado creara muchas B\u00fasquedas Guardadas o Monitores de C\u00f3digo para recibir la confirmaci\u00f3n de que una cadena espec\u00edfica esta presente. Esto podr\u00eda permitir a un atacante adivinar los tokens formateados en el c\u00f3digo fuente, como las claves de la API. Este problema ha sido parcheado en la versi\u00f3n 3.33.2 y en las futuras versiones de Sourcegraph. Recomendamos encarecidamente que se actualice a las versiones seguras. Si no puede hacerlo, puede deshabilitar las B\u00fasquedas Guardadas y los Monitores de C\u00f3digo"}], "evaluatorComment": null, "id": "CVE-2021-43823", "lastModified": "2021-12-16T15:00:25.970", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Primary"}]}, "published": "2021-12-13T20:15:07.813", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/sourcegraph/sourcegraph/commit/a88d90a8302c492282186d39718cd8fb093c14fa"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/sourcegraph/sourcegraph/security/advisories/GHSA-cpq7-hmvv-29w9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-203"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/sourcegraph/sourcegraph/commit/a88d90a8302c492282186d39718cd8fb093c14fa"}, "type": "CWE-203"}
326
Determine whether the {function_name} code is vulnerable or not.
[ "import base64\nimport logging\nimport pathlib\nimport uuid", "from django.conf import settings", "", "from django.utils.functional import cached_property\nfrom storages.utils import safe_join", "from s3file.storages import storage", "logger = logging.getLogger(\"s3file\")", "\nclass S3FileInputMixin:\n \"\"\"FileInput that uses JavaScript to directly upload to Amazon S3.\"\"\"", " needs_multipart_form = False", " upload_path = str(\n getattr(settings, \"S3FILE_UPLOAD_PATH\", pathlib.PurePosixPath(\"tmp\", \"s3file\"))", " )", " upload_path = safe_join(str(storage.location), upload_path)", " expires = settings.SESSION_COOKIE_AGE", " @property\n def bucket_name(self):\n return storage.bucket.name", " @property\n def client(self):\n return storage.connection.meta.client", " def build_attrs(self, *args, **kwargs):\n attrs = super().build_attrs(*args, **kwargs)", " accept = attrs.get(\"accept\")\n response = self.client.generate_presigned_post(\n self.bucket_name,\n str(pathlib.PurePosixPath(self.upload_folder, \"${filename}\")),\n Conditions=self.get_conditions(accept),\n ExpiresIn=self.expires,\n )", " defaults = {\n \"data-fields-%s\" % key: value for key, value in response[\"fields\"].items()\n }\n defaults[\"data-url\"] = response[\"url\"]", "", " defaults.update(attrs)", " try:\n defaults[\"class\"] += \" s3file\"\n except KeyError:\n defaults[\"class\"] = \"s3file\"\n return defaults", " def get_conditions(self, accept):\n conditions = [\n {\"bucket\": self.bucket_name},\n [\"starts-with\", \"$key\", str(self.upload_folder)],\n {\"success_action_status\": \"201\"},\n ]\n if accept and \",\" not in accept:\n top_type, sub_type = accept.split(\"/\", 1)\n if sub_type == \"*\":\n conditions.append([\"starts-with\", \"$Content-Type\", \"%s/\" % top_type])\n else:\n conditions.append({\"Content-Type\": accept})\n else:\n conditions.append([\"starts-with\", \"$Content-Type\", \"\"])", " return conditions", " @cached_property\n def upload_folder(self):\n return str(\n pathlib.PurePosixPath(\n self.upload_path,\n base64.urlsafe_b64encode(uuid.uuid4().bytes)\n .decode(\"utf-8\")\n .rstrip(\"=\\n\"),\n )\n ) # S3 uses POSIX paths", " class Media:\n js = (\"s3file/js/s3file.js\" if settings.DEBUG else \"s3file/js/s3file.min.js\",)" ]
[ 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 37, 96, 4, 49, 215, 80], "buggy_code_start_loc": [6, 4, 96, 4, 1, 34, 2], "filenames": ["s3file/forms.py", "s3file/middleware.py", "s3file/static/s3file/js/s3file.js", "s3file/views.py", "tests/conftest.py", "tests/test_forms.py", "tests/test_middleware.py"], "fixing_code_end_loc": [58, 66, 103, 6, 70, 223, 134], "fixing_code_start_loc": [7, 4, 97, 5, 0, 34, 3], "message": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:django-s3file_project:django-s3file:*:*:*:*:*:*:*:*", "matchCriteriaId": "A7EFD2FC-D3B5-4C07-ABA9-66B318FD04F1", "versionEndExcluding": "5.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version."}, {"lang": "es", "value": "django-s3file es una entrada ligera de subida de archivos para Django y Amazon S3 . En versiones anteriores a 5.5.1, era posible recorrer todo el bucket de AWS S3 y en la mayor\u00eda de los casos acceder o eliminar archivos. Si el ajuste \"AWS_LOCATION\" estaba configurado, el recorrido se limitaba s\u00f3lo a esa ubicaci\u00f3n. El problema fue detectado por el mantenedor. No se presentan informes de que la vulnerabilidad sea conocida o explotada por terceros, antes de la publicaci\u00f3n del parche. La vulnerabilidad ha sido corregida en versi\u00f3n 5.5.1 y superiores. No se presenta ninguna mitigaci\u00f3n viable. Debemos instar a todos los usuarios a actualizar inmediatamente a la versi\u00f3n parcheada"}], "evaluatorComment": null, "id": "CVE-2022-24840", "lastModified": "2022-06-17T15:50:50.613", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 9.1, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-06-09T04:15:10.707", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/security/advisories/GHSA-4w8f-hjm9-xwgf"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, "type": "CWE-22"}
327
Determine whether the {function_name} code is vulnerable or not.
[ "import base64\nimport logging\nimport pathlib\nimport uuid", "from django.conf import settings", "from django.core import signing", "from django.utils.functional import cached_property\nfrom storages.utils import safe_join", "from s3file.storages import storage", "logger = logging.getLogger(\"s3file\")", "\nclass S3FileInputMixin:\n \"\"\"FileInput that uses JavaScript to directly upload to Amazon S3.\"\"\"", " needs_multipart_form = False", " upload_path = safe_join(\n str(storage.aws_location),\n str(\n getattr(\n settings, \"S3FILE_UPLOAD_PATH\", pathlib.PurePosixPath(\"tmp\", \"s3file\")\n )\n ),", " )", "", " expires = settings.SESSION_COOKIE_AGE", " @property\n def bucket_name(self):\n return storage.bucket.name", " @property\n def client(self):\n return storage.connection.meta.client", " def build_attrs(self, *args, **kwargs):\n attrs = super().build_attrs(*args, **kwargs)", " accept = attrs.get(\"accept\")\n response = self.client.generate_presigned_post(\n self.bucket_name,\n str(pathlib.PurePosixPath(self.upload_folder, \"${filename}\")),\n Conditions=self.get_conditions(accept),\n ExpiresIn=self.expires,\n )", " defaults = {\n \"data-fields-%s\" % key: value for key, value in response[\"fields\"].items()\n }\n defaults[\"data-url\"] = response[\"url\"]", " signer = signing.Signer(\n salt=f\"{S3FileInputMixin.__module__}.{S3FileInputMixin.__name__}\"\n )\n print(self.upload_folder)\n defaults[\"data-s3f-signature\"] = signer.signature(self.upload_folder)", " defaults.update(attrs)", " try:\n defaults[\"class\"] += \" s3file\"\n except KeyError:\n defaults[\"class\"] = \"s3file\"\n return defaults", " def get_conditions(self, accept):\n conditions = [\n {\"bucket\": self.bucket_name},\n [\"starts-with\", \"$key\", str(self.upload_folder)],\n {\"success_action_status\": \"201\"},\n ]\n if accept and \",\" not in accept:\n top_type, sub_type = accept.split(\"/\", 1)\n if sub_type == \"*\":\n conditions.append([\"starts-with\", \"$Content-Type\", \"%s/\" % top_type])\n else:\n conditions.append({\"Content-Type\": accept})\n else:\n conditions.append([\"starts-with\", \"$Content-Type\", \"\"])", " return conditions", " @cached_property\n def upload_folder(self):\n return str(\n pathlib.PurePosixPath(\n self.upload_path,\n base64.urlsafe_b64encode(uuid.uuid4().bytes)\n .decode(\"utf-8\")\n .rstrip(\"=\\n\"),\n )\n ) # S3 uses POSIX paths", " class Media:\n js = (\"s3file/js/s3file.js\" if settings.DEBUG else \"s3file/js/s3file.min.js\",)" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 37, 96, 4, 49, 215, 80], "buggy_code_start_loc": [6, 4, 96, 4, 1, 34, 2], "filenames": ["s3file/forms.py", "s3file/middleware.py", "s3file/static/s3file/js/s3file.js", "s3file/views.py", "tests/conftest.py", "tests/test_forms.py", "tests/test_middleware.py"], "fixing_code_end_loc": [58, 66, 103, 6, 70, 223, 134], "fixing_code_start_loc": [7, 4, 97, 5, 0, 34, 3], "message": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:django-s3file_project:django-s3file:*:*:*:*:*:*:*:*", "matchCriteriaId": "A7EFD2FC-D3B5-4C07-ABA9-66B318FD04F1", "versionEndExcluding": "5.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version."}, {"lang": "es", "value": "django-s3file es una entrada ligera de subida de archivos para Django y Amazon S3 . En versiones anteriores a 5.5.1, era posible recorrer todo el bucket de AWS S3 y en la mayor\u00eda de los casos acceder o eliminar archivos. Si el ajuste \"AWS_LOCATION\" estaba configurado, el recorrido se limitaba s\u00f3lo a esa ubicaci\u00f3n. El problema fue detectado por el mantenedor. No se presentan informes de que la vulnerabilidad sea conocida o explotada por terceros, antes de la publicaci\u00f3n del parche. La vulnerabilidad ha sido corregida en versi\u00f3n 5.5.1 y superiores. No se presenta ninguna mitigaci\u00f3n viable. Debemos instar a todos los usuarios a actualizar inmediatamente a la versi\u00f3n parcheada"}], "evaluatorComment": null, "id": "CVE-2022-24840", "lastModified": "2022-06-17T15:50:50.613", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 9.1, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-06-09T04:15:10.707", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/security/advisories/GHSA-4w8f-hjm9-xwgf"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, "type": "CWE-22"}
327
Determine whether the {function_name} code is vulnerable or not.
[ "import logging\nimport pathlib\n", "from s3file.storages import local_dev, storage", "\nfrom . import views", "", "\nlogger = logging.getLogger(\"s3file\")", "\nclass S3FileMiddleware:\n def __init__(self, get_response):\n self.get_response = get_response", " def __call__(self, request):\n file_fields = request.POST.getlist(\"s3file\")\n for field_name in file_fields:", "", " paths = request.POST.getlist(field_name)", " request.FILES.setlist(field_name, list(self.get_files_from_storage(paths)))", "\n if local_dev and request.path == \"/__s3_mock__/\":\n return views.S3MockView.as_view()(request)", " return self.get_response(request)", " @staticmethod", " def get_files_from_storage(paths):", " \"\"\"Return S3 file where the name does not include the path.\"\"\"", "", " for path in paths:\n path = pathlib.PurePosixPath(path)", "", " try:", " location = storage.aws_location\n except AttributeError:\n location = storage.location", " try:", " f = storage.open(str(path.relative_to(location)))", " f.name = path.name\n yield f\n except (OSError, ValueError):\n logger.exception(\"File not found: %s\", path)" ]
[ 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 37, 96, 4, 49, 215, 80], "buggy_code_start_loc": [6, 4, 96, 4, 1, 34, 2], "filenames": ["s3file/forms.py", "s3file/middleware.py", "s3file/static/s3file/js/s3file.js", "s3file/views.py", "tests/conftest.py", "tests/test_forms.py", "tests/test_middleware.py"], "fixing_code_end_loc": [58, 66, 103, 6, 70, 223, 134], "fixing_code_start_loc": [7, 4, 97, 5, 0, 34, 3], "message": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:django-s3file_project:django-s3file:*:*:*:*:*:*:*:*", "matchCriteriaId": "A7EFD2FC-D3B5-4C07-ABA9-66B318FD04F1", "versionEndExcluding": "5.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version."}, {"lang": "es", "value": "django-s3file es una entrada ligera de subida de archivos para Django y Amazon S3 . En versiones anteriores a 5.5.1, era posible recorrer todo el bucket de AWS S3 y en la mayor\u00eda de los casos acceder o eliminar archivos. Si el ajuste \"AWS_LOCATION\" estaba configurado, el recorrido se limitaba s\u00f3lo a esa ubicaci\u00f3n. El problema fue detectado por el mantenedor. No se presentan informes de que la vulnerabilidad sea conocida o explotada por terceros, antes de la publicaci\u00f3n del parche. La vulnerabilidad ha sido corregida en versi\u00f3n 5.5.1 y superiores. No se presenta ninguna mitigaci\u00f3n viable. Debemos instar a todos los usuarios a actualizar inmediatamente a la versi\u00f3n parcheada"}], "evaluatorComment": null, "id": "CVE-2022-24840", "lastModified": "2022-06-17T15:50:50.613", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 9.1, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-06-09T04:15:10.707", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/security/advisories/GHSA-4w8f-hjm9-xwgf"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, "type": "CWE-22"}
327
Determine whether the {function_name} code is vulnerable or not.
[ "import logging\nimport pathlib\n", "from django.core import signing\nfrom django.core.exceptions import PermissionDenied, SuspiciousFileOperation\nfrom django.utils.crypto import constant_time_compare", "\nfrom . import views", "from .forms import S3FileInputMixin\nfrom .storages import local_dev, storage", "\nlogger = logging.getLogger(\"s3file\")", "\nclass S3FileMiddleware:\n def __init__(self, get_response):\n self.get_response = get_response", " def __call__(self, request):\n file_fields = request.POST.getlist(\"s3file\")\n for field_name in file_fields:", "", " paths = request.POST.getlist(field_name)", " if paths:\n try:\n signature = request.POST[f\"{field_name}-s3f-signature\"]\n except KeyError:\n raise PermissionDenied(\"No signature provided.\")\n try:\n request.FILES.setlist(\n field_name, list(self.get_files_from_storage(paths, signature))\n )\n except SuspiciousFileOperation as e:\n raise PermissionDenied(\"Illegal file name!\") from e", "\n if local_dev and request.path == \"/__s3_mock__/\":\n return views.S3MockView.as_view()(request)", " return self.get_response(request)", " @staticmethod", " def get_files_from_storage(paths, signature):", " \"\"\"Return S3 file where the name does not include the path.\"\"\"", " try:\n location = storage.aws_location\n except AttributeError:\n location = storage.location\n signer = signing.Signer(\n salt=f\"{S3FileInputMixin.__module__}.{S3FileInputMixin.__name__}\"\n )", " for path in paths:\n path = pathlib.PurePosixPath(path)", " print(path)\n print(signer.signature(path.parent), signature)\n if not constant_time_compare(signer.signature(path.parent), signature):\n raise PermissionDenied(\"Illegal signature!\")", " try:", " relative_path = str(path.relative_to(location))\n except ValueError as e:\n raise SuspiciousFileOperation(\n f\"Path is not inside the designated upload location: {path}\"\n ) from e\n", " try:", " f = storage.open(relative_path)", " f.name = path.name\n yield f\n except (OSError, ValueError):\n logger.exception(\"File not found: %s\", path)" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 37, 96, 4, 49, 215, 80], "buggy_code_start_loc": [6, 4, 96, 4, 1, 34, 2], "filenames": ["s3file/forms.py", "s3file/middleware.py", "s3file/static/s3file/js/s3file.js", "s3file/views.py", "tests/conftest.py", "tests/test_forms.py", "tests/test_middleware.py"], "fixing_code_end_loc": [58, 66, 103, 6, 70, 223, 134], "fixing_code_start_loc": [7, 4, 97, 5, 0, 34, 3], "message": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:django-s3file_project:django-s3file:*:*:*:*:*:*:*:*", "matchCriteriaId": "A7EFD2FC-D3B5-4C07-ABA9-66B318FD04F1", "versionEndExcluding": "5.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version."}, {"lang": "es", "value": "django-s3file es una entrada ligera de subida de archivos para Django y Amazon S3 . En versiones anteriores a 5.5.1, era posible recorrer todo el bucket de AWS S3 y en la mayor\u00eda de los casos acceder o eliminar archivos. Si el ajuste \"AWS_LOCATION\" estaba configurado, el recorrido se limitaba s\u00f3lo a esa ubicaci\u00f3n. El problema fue detectado por el mantenedor. No se presentan informes de que la vulnerabilidad sea conocida o explotada por terceros, antes de la publicaci\u00f3n del parche. La vulnerabilidad ha sido corregida en versi\u00f3n 5.5.1 y superiores. No se presenta ninguna mitigaci\u00f3n viable. Debemos instar a todos los usuarios a actualizar inmediatamente a la versi\u00f3n parcheada"}], "evaluatorComment": null, "id": "CVE-2022-24840", "lastModified": "2022-06-17T15:50:50.613", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 9.1, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-06-09T04:15:10.707", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/security/advisories/GHSA-4w8f-hjm9-xwgf"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, "type": "CWE-22"}
327
Determine whether the {function_name} code is vulnerable or not.
[ "'use strict';", "(function () {\n function parseURL (text) {\n var xml = new window.DOMParser().parseFromString(text, 'text/xml')\n var tag = xml.getElementsByTagName('Key')[0]\n return decodeURI(tag.childNodes[0].nodeValue)\n }", " function waitForAllFiles (form) {\n if (window.uploading !== 0) {\n setTimeout(function () {\n waitForAllFiles(form)\n }, 100)\n } else {\n window.HTMLFormElement.prototype.submit.call(form)\n }\n }", " function request (method, url, data, fileInput, file, form) {\n file.loaded = 0\n return new Promise(function (resolve, reject) {\n var xhr = new window.XMLHttpRequest()", " xhr.onload = function () {\n if (xhr.status === 201) {\n resolve(xhr.responseText)\n } else {\n reject(xhr.statusText)\n }\n }", " xhr.upload.onprogress = function (e) {\n var diff = e.loaded - file.loaded\n form.loaded += diff\n fileInput.loaded += diff\n file.loaded = e.loaded\n var defaultEventData = {\n currentFile: file,\n currentFileName: file.name,\n currentFileProgress: Math.min(e.loaded / e.total, 1),\n originalEvent: e\n }\n form.dispatchEvent(new window.CustomEvent('progress', {\n detail: Object.assign({\n progress: Math.min(form.loaded / form.total, 1),\n loaded: form.loaded,\n total: form.total\n }, defaultEventData)\n }))\n fileInput.dispatchEvent(new window.CustomEvent('progress', {\n detail: Object.assign({\n progress: Math.min(fileInput.loaded / fileInput.total, 1),\n loaded: fileInput.loaded,\n total: fileInput.total\n }, defaultEventData)\n }))\n }", " xhr.onerror = function () {\n reject(xhr.statusText)\n }", " xhr.open(method, url)\n xhr.send(data)\n })\n }", " function uploadFiles (form, fileInput, name) {\n var url = fileInput.getAttribute('data-url')\n fileInput.loaded = 0\n fileInput.total = 0\n var promises = Array.from(fileInput.files).map(function (file) {\n form.total += file.size\n fileInput.total += file.size\n var s3Form = new window.FormData()\n Array.from(fileInput.attributes).forEach(function (attr) {\n var name = attr.name", " if (name.startsWith('data-fields')) {\n name = name.replace('data-fields-', '')\n s3Form.append(name, attr.value)\n }\n })\n s3Form.append('success_action_status', '201')\n s3Form.append('Content-Type', file.type)\n s3Form.append('file', file)\n return request('POST', url, s3Form, fileInput, file, form)\n })\n Promise.all(promises).then(function (results) {\n results.forEach(function (result) {\n var hiddenFileInput = document.createElement('input')\n hiddenFileInput.type = 'hidden'\n hiddenFileInput.name = name\n hiddenFileInput.value = parseURL(result)\n form.appendChild(hiddenFileInput)", "", " })\n fileInput.name = ''\n window.uploading -= 1\n }, function (err) {\n console.log(err)\n fileInput.setCustomValidity(err)\n fileInput.reportValidity()\n })\n }", " function clickSubmit (e) {\n var submitButton = e.target\n var form = submitButton.closest('form')\n var submitInput = document.createElement('input')\n submitInput.type = 'hidden'\n submitInput.value = submitButton.value || '1'\n submitInput.name = submitButton.name\n form.appendChild(submitInput)\n }", " function uploadS3Inputs (form) {\n window.uploading = 0\n form.loaded = 0\n form.total = 0\n var inputs = Array.from(form.querySelectorAll('.s3file'))", " inputs.forEach(function (input) {\n var hiddenS3Input = document.createElement('input')\n hiddenS3Input.type = 'hidden'\n hiddenS3Input.name = 's3file'\n hiddenS3Input.value = input.name\n form.appendChild(hiddenS3Input)\n })\n inputs.forEach(function (input) {\n window.uploading += 1\n uploadFiles(form, input, input.name)\n })\n waitForAllFiles(form)\n }", " document.addEventListener('DOMContentLoaded', function () {\n var forms = Array.from(document.querySelectorAll('.s3file')).map(function (input) {\n return input.closest('form')\n })\n forms = new Set(forms)\n forms.forEach(function (form) {\n form.addEventListener('submit', function (e) {\n e.preventDefault()\n uploadS3Inputs(e.target)\n })\n var submitButtons = form.querySelectorAll('input[type=submit], button[type=submit]')\n Array.from(submitButtons).forEach(function (submitButton) {\n submitButton.addEventListener('click', clickSubmit)\n })\n })\n })\n})()" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 37, 96, 4, 49, 215, 80], "buggy_code_start_loc": [6, 4, 96, 4, 1, 34, 2], "filenames": ["s3file/forms.py", "s3file/middleware.py", "s3file/static/s3file/js/s3file.js", "s3file/views.py", "tests/conftest.py", "tests/test_forms.py", "tests/test_middleware.py"], "fixing_code_end_loc": [58, 66, 103, 6, 70, 223, 134], "fixing_code_start_loc": [7, 4, 97, 5, 0, 34, 3], "message": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:django-s3file_project:django-s3file:*:*:*:*:*:*:*:*", "matchCriteriaId": "A7EFD2FC-D3B5-4C07-ABA9-66B318FD04F1", "versionEndExcluding": "5.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version."}, {"lang": "es", "value": "django-s3file es una entrada ligera de subida de archivos para Django y Amazon S3 . En versiones anteriores a 5.5.1, era posible recorrer todo el bucket de AWS S3 y en la mayor\u00eda de los casos acceder o eliminar archivos. Si el ajuste \"AWS_LOCATION\" estaba configurado, el recorrido se limitaba s\u00f3lo a esa ubicaci\u00f3n. El problema fue detectado por el mantenedor. No se presentan informes de que la vulnerabilidad sea conocida o explotada por terceros, antes de la publicaci\u00f3n del parche. La vulnerabilidad ha sido corregida en versi\u00f3n 5.5.1 y superiores. No se presenta ninguna mitigaci\u00f3n viable. Debemos instar a todos los usuarios a actualizar inmediatamente a la versi\u00f3n parcheada"}], "evaluatorComment": null, "id": "CVE-2022-24840", "lastModified": "2022-06-17T15:50:50.613", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 9.1, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-06-09T04:15:10.707", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/security/advisories/GHSA-4w8f-hjm9-xwgf"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, "type": "CWE-22"}
327
Determine whether the {function_name} code is vulnerable or not.
[ "'use strict';", "(function () {\n function parseURL (text) {\n var xml = new window.DOMParser().parseFromString(text, 'text/xml')\n var tag = xml.getElementsByTagName('Key')[0]\n return decodeURI(tag.childNodes[0].nodeValue)\n }", " function waitForAllFiles (form) {\n if (window.uploading !== 0) {\n setTimeout(function () {\n waitForAllFiles(form)\n }, 100)\n } else {\n window.HTMLFormElement.prototype.submit.call(form)\n }\n }", " function request (method, url, data, fileInput, file, form) {\n file.loaded = 0\n return new Promise(function (resolve, reject) {\n var xhr = new window.XMLHttpRequest()", " xhr.onload = function () {\n if (xhr.status === 201) {\n resolve(xhr.responseText)\n } else {\n reject(xhr.statusText)\n }\n }", " xhr.upload.onprogress = function (e) {\n var diff = e.loaded - file.loaded\n form.loaded += diff\n fileInput.loaded += diff\n file.loaded = e.loaded\n var defaultEventData = {\n currentFile: file,\n currentFileName: file.name,\n currentFileProgress: Math.min(e.loaded / e.total, 1),\n originalEvent: e\n }\n form.dispatchEvent(new window.CustomEvent('progress', {\n detail: Object.assign({\n progress: Math.min(form.loaded / form.total, 1),\n loaded: form.loaded,\n total: form.total\n }, defaultEventData)\n }))\n fileInput.dispatchEvent(new window.CustomEvent('progress', {\n detail: Object.assign({\n progress: Math.min(fileInput.loaded / fileInput.total, 1),\n loaded: fileInput.loaded,\n total: fileInput.total\n }, defaultEventData)\n }))\n }", " xhr.onerror = function () {\n reject(xhr.statusText)\n }", " xhr.open(method, url)\n xhr.send(data)\n })\n }", " function uploadFiles (form, fileInput, name) {\n var url = fileInput.getAttribute('data-url')\n fileInput.loaded = 0\n fileInput.total = 0\n var promises = Array.from(fileInput.files).map(function (file) {\n form.total += file.size\n fileInput.total += file.size\n var s3Form = new window.FormData()\n Array.from(fileInput.attributes).forEach(function (attr) {\n var name = attr.name", " if (name.startsWith('data-fields')) {\n name = name.replace('data-fields-', '')\n s3Form.append(name, attr.value)\n }\n })\n s3Form.append('success_action_status', '201')\n s3Form.append('Content-Type', file.type)\n s3Form.append('file', file)\n return request('POST', url, s3Form, fileInput, file, form)\n })\n Promise.all(promises).then(function (results) {\n results.forEach(function (result) {\n var hiddenFileInput = document.createElement('input')\n hiddenFileInput.type = 'hidden'\n hiddenFileInput.name = name\n hiddenFileInput.value = parseURL(result)\n form.appendChild(hiddenFileInput)", " var hiddenSignatureInput = document.createElement('input')\n hiddenSignatureInput.type = 'hidden'\n hiddenSignatureInput.name = name + '-s3f-signature'\n console.log(fileInput.dataset.s3fSignature)\n hiddenSignatureInput.value = fileInput.dataset.s3fSignature\n form.appendChild(hiddenSignatureInput)", " })\n fileInput.name = ''\n window.uploading -= 1\n }, function (err) {\n console.log(err)\n fileInput.setCustomValidity(err)\n fileInput.reportValidity()\n })\n }", " function clickSubmit (e) {\n var submitButton = e.target\n var form = submitButton.closest('form')\n var submitInput = document.createElement('input')\n submitInput.type = 'hidden'\n submitInput.value = submitButton.value || '1'\n submitInput.name = submitButton.name\n form.appendChild(submitInput)\n }", " function uploadS3Inputs (form) {\n window.uploading = 0\n form.loaded = 0\n form.total = 0\n var inputs = Array.from(form.querySelectorAll('.s3file'))", " inputs.forEach(function (input) {\n var hiddenS3Input = document.createElement('input')\n hiddenS3Input.type = 'hidden'\n hiddenS3Input.name = 's3file'\n hiddenS3Input.value = input.name\n form.appendChild(hiddenS3Input)\n })\n inputs.forEach(function (input) {\n window.uploading += 1\n uploadFiles(form, input, input.name)\n })\n waitForAllFiles(form)\n }", " document.addEventListener('DOMContentLoaded', function () {\n var forms = Array.from(document.querySelectorAll('.s3file')).map(function (input) {\n return input.closest('form')\n })\n forms = new Set(forms)\n forms.forEach(function (form) {\n form.addEventListener('submit', function (e) {\n e.preventDefault()\n uploadS3Inputs(e.target)\n })\n var submitButtons = form.querySelectorAll('input[type=submit], button[type=submit]')\n Array.from(submitButtons).forEach(function (submitButton) {\n submitButton.addEventListener('click', clickSubmit)\n })\n })\n })\n})()" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 37, 96, 4, 49, 215, 80], "buggy_code_start_loc": [6, 4, 96, 4, 1, 34, 2], "filenames": ["s3file/forms.py", "s3file/middleware.py", "s3file/static/s3file/js/s3file.js", "s3file/views.py", "tests/conftest.py", "tests/test_forms.py", "tests/test_middleware.py"], "fixing_code_end_loc": [58, 66, 103, 6, 70, 223, 134], "fixing_code_start_loc": [7, 4, 97, 5, 0, 34, 3], "message": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:django-s3file_project:django-s3file:*:*:*:*:*:*:*:*", "matchCriteriaId": "A7EFD2FC-D3B5-4C07-ABA9-66B318FD04F1", "versionEndExcluding": "5.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version."}, {"lang": "es", "value": "django-s3file es una entrada ligera de subida de archivos para Django y Amazon S3 . En versiones anteriores a 5.5.1, era posible recorrer todo el bucket de AWS S3 y en la mayor\u00eda de los casos acceder o eliminar archivos. Si el ajuste \"AWS_LOCATION\" estaba configurado, el recorrido se limitaba s\u00f3lo a esa ubicaci\u00f3n. El problema fue detectado por el mantenedor. No se presentan informes de que la vulnerabilidad sea conocida o explotada por terceros, antes de la publicaci\u00f3n del parche. La vulnerabilidad ha sido corregida en versi\u00f3n 5.5.1 y superiores. No se presenta ninguna mitigaci\u00f3n viable. Debemos instar a todos los usuarios a actualizar inmediatamente a la versi\u00f3n parcheada"}], "evaluatorComment": null, "id": "CVE-2022-24840", "lastModified": "2022-06-17T15:50:50.613", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 9.1, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-06-09T04:15:10.707", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/security/advisories/GHSA-4w8f-hjm9-xwgf"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, "type": "CWE-22"}
327
Determine whether the {function_name} code is vulnerable or not.
[ "import base64\nimport hashlib\nimport hmac\nimport logging", "", "\nfrom django import http\nfrom django.conf import settings\nfrom django.core.files.storage import default_storage\nfrom django.views import generic", "logger = logging.getLogger(\"s3file\")", "\nclass S3MockView(generic.View):\n def post(self, request):\n success_action_status = request.POST.get(\"success_action_status\", 201)\n try:\n file = request.FILES[\"file\"]\n key = request.POST[\"key\"]\n date = request.POST[\"x-amz-date\"]\n signature = request.POST[\"x-amz-signature\"]\n policy = request.POST[\"policy\"]\n except KeyError:\n logger.exception(\"bad request\")\n return http.HttpResponseBadRequest()", " try:\n signature = base64.b64decode(signature.encode())\n policy = base64.b64decode(policy.encode())", " calc_sign = hmac.new(\n settings.SECRET_KEY.encode(), policy + date.encode(), \"sha256\"\n ).digest()\n except ValueError:\n logger.exception(\"bad request\")\n return http.HttpResponseBadRequest()", " if not hmac.compare_digest(signature, calc_sign):\n logger.warning(\"bad signature\")\n return http.HttpResponseForbidden()", " key = key.replace(\"${filename}\", file.name)\n etag = hashlib.md5(file.read()).hexdigest() # nosec\n file.seek(0)\n key = default_storage.save(key, file)\n return http.HttpResponse(\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'\n \"<PostResponse>\"\n f\"<Location>{settings.MEDIA_URL}{key}</Location>\"\n f\"<Bucket>{getattr(settings, 'AWS_STORAGE_BUCKET_NAME')}</Bucket>\"\n f\"<Key>{key}</Key>\"\n f'<ETag>\"{etag}\"</ETag>'\n \"</PostResponse>\",\n status=success_action_status,\n )" ]
[ 1, 0, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 37, 96, 4, 49, 215, 80], "buggy_code_start_loc": [6, 4, 96, 4, 1, 34, 2], "filenames": ["s3file/forms.py", "s3file/middleware.py", "s3file/static/s3file/js/s3file.js", "s3file/views.py", "tests/conftest.py", "tests/test_forms.py", "tests/test_middleware.py"], "fixing_code_end_loc": [58, 66, 103, 6, 70, 223, 134], "fixing_code_start_loc": [7, 4, 97, 5, 0, 34, 3], "message": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:django-s3file_project:django-s3file:*:*:*:*:*:*:*:*", "matchCriteriaId": "A7EFD2FC-D3B5-4C07-ABA9-66B318FD04F1", "versionEndExcluding": "5.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version."}, {"lang": "es", "value": "django-s3file es una entrada ligera de subida de archivos para Django y Amazon S3 . En versiones anteriores a 5.5.1, era posible recorrer todo el bucket de AWS S3 y en la mayor\u00eda de los casos acceder o eliminar archivos. Si el ajuste \"AWS_LOCATION\" estaba configurado, el recorrido se limitaba s\u00f3lo a esa ubicaci\u00f3n. El problema fue detectado por el mantenedor. No se presentan informes de que la vulnerabilidad sea conocida o explotada por terceros, antes de la publicaci\u00f3n del parche. La vulnerabilidad ha sido corregida en versi\u00f3n 5.5.1 y superiores. No se presenta ninguna mitigaci\u00f3n viable. Debemos instar a todos los usuarios a actualizar inmediatamente a la versi\u00f3n parcheada"}], "evaluatorComment": null, "id": "CVE-2022-24840", "lastModified": "2022-06-17T15:50:50.613", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 9.1, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-06-09T04:15:10.707", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/security/advisories/GHSA-4w8f-hjm9-xwgf"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, "type": "CWE-22"}
327
Determine whether the {function_name} code is vulnerable or not.
[ "import base64\nimport hashlib\nimport hmac\nimport logging", "from pathlib import Path", "\nfrom django import http\nfrom django.conf import settings\nfrom django.core.files.storage import default_storage\nfrom django.views import generic", "logger = logging.getLogger(\"s3file\")", "\nclass S3MockView(generic.View):\n def post(self, request):\n success_action_status = request.POST.get(\"success_action_status\", 201)\n try:\n file = request.FILES[\"file\"]\n key = request.POST[\"key\"]\n date = request.POST[\"x-amz-date\"]\n signature = request.POST[\"x-amz-signature\"]\n policy = request.POST[\"policy\"]\n except KeyError:\n logger.exception(\"bad request\")\n return http.HttpResponseBadRequest()", " try:\n signature = base64.b64decode(signature.encode())\n policy = base64.b64decode(policy.encode())", " calc_sign = hmac.new(\n settings.SECRET_KEY.encode(), policy + date.encode(), \"sha256\"\n ).digest()\n except ValueError:\n logger.exception(\"bad request\")\n return http.HttpResponseBadRequest()", " if not hmac.compare_digest(signature, calc_sign):\n logger.warning(\"bad signature\")\n return http.HttpResponseForbidden()", " key = key.replace(\"${filename}\", file.name)\n etag = hashlib.md5(file.read()).hexdigest() # nosec\n file.seek(0)\n key = default_storage.save(key, file)\n return http.HttpResponse(\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'\n \"<PostResponse>\"\n f\"<Location>{settings.MEDIA_URL}{key}</Location>\"\n f\"<Bucket>{getattr(settings, 'AWS_STORAGE_BUCKET_NAME')}</Bucket>\"\n f\"<Key>{key}</Key>\"\n f'<ETag>\"{etag}\"</ETag>'\n \"</PostResponse>\",\n status=success_action_status,\n )" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 37, 96, 4, 49, 215, 80], "buggy_code_start_loc": [6, 4, 96, 4, 1, 34, 2], "filenames": ["s3file/forms.py", "s3file/middleware.py", "s3file/static/s3file/js/s3file.js", "s3file/views.py", "tests/conftest.py", "tests/test_forms.py", "tests/test_middleware.py"], "fixing_code_end_loc": [58, 66, 103, 6, 70, 223, 134], "fixing_code_start_loc": [7, 4, 97, 5, 0, 34, 3], "message": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:django-s3file_project:django-s3file:*:*:*:*:*:*:*:*", "matchCriteriaId": "A7EFD2FC-D3B5-4C07-ABA9-66B318FD04F1", "versionEndExcluding": "5.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version."}, {"lang": "es", "value": "django-s3file es una entrada ligera de subida de archivos para Django y Amazon S3 . En versiones anteriores a 5.5.1, era posible recorrer todo el bucket de AWS S3 y en la mayor\u00eda de los casos acceder o eliminar archivos. Si el ajuste \"AWS_LOCATION\" estaba configurado, el recorrido se limitaba s\u00f3lo a esa ubicaci\u00f3n. El problema fue detectado por el mantenedor. No se presentan informes de que la vulnerabilidad sea conocida o explotada por terceros, antes de la publicaci\u00f3n del parche. La vulnerabilidad ha sido corregida en versi\u00f3n 5.5.1 y superiores. No se presenta ninguna mitigaci\u00f3n viable. Debemos instar a todos los usuarios a actualizar inmediatamente a la versi\u00f3n parcheada"}], "evaluatorComment": null, "id": "CVE-2022-24840", "lastModified": "2022-06-17T15:50:50.613", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 9.1, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-06-09T04:15:10.707", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/security/advisories/GHSA-4w8f-hjm9-xwgf"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, "type": "CWE-22"}
327
Determine whether the {function_name} code is vulnerable or not.
[ "import os", "import tempfile", "", "\nimport pytest\nfrom django.core.files.base import ContentFile\nfrom django.utils.encoding import force_str\nfrom selenium import webdriver\nfrom selenium.common.exceptions import WebDriverException", "", "", "@pytest.fixture(scope=\"session\")\ndef driver():\n chrome_options = webdriver.ChromeOptions()\n chrome_options.headless = True\n try:\n b = webdriver.Chrome(options=chrome_options)\n except WebDriverException as e:\n pytest.skip(force_str(e))\n else:\n yield b\n b.quit()", "\n@pytest.fixture", "def upload_file(request):\n path = tempfile.mkdtemp()\n file_name = os.path.join(path, \"%s.txt\" % request.node.name)\n with open(file_name, \"w\") as f:\n f.write(request.node.name)\n return file_name", "", "@pytest.fixture", "def another_upload_file(request):\n path = tempfile.mkdtemp()\n file_name = os.path.join(path, \"another_%s.txt\" % request.node.name)\n with open(file_name, \"w\") as f:", " f.write(request.node.name)", " return file_name", "", "@pytest.fixture", "def yet_another_upload_file(request):\n path = tempfile.mkdtemp()\n file_name = os.path.join(path, \"yet_another_%s.txt\" % request.node.name)\n with open(file_name, \"w\") as f:", " f.write(request.node.name)", " return file_name", "", "@pytest.fixture\ndef filemodel(request, db):\n from tests.testapp.models import FileModel", " return FileModel.objects.create(\n file=ContentFile(request.node.name, \"%s.txt\" % request.node.name)\n )" ]
[ 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 37, 96, 4, 49, 215, 80], "buggy_code_start_loc": [6, 4, 96, 4, 1, 34, 2], "filenames": ["s3file/forms.py", "s3file/middleware.py", "s3file/static/s3file/js/s3file.js", "s3file/views.py", "tests/conftest.py", "tests/test_forms.py", "tests/test_middleware.py"], "fixing_code_end_loc": [58, 66, 103, 6, 70, 223, 134], "fixing_code_start_loc": [7, 4, 97, 5, 0, 34, 3], "message": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:django-s3file_project:django-s3file:*:*:*:*:*:*:*:*", "matchCriteriaId": "A7EFD2FC-D3B5-4C07-ABA9-66B318FD04F1", "versionEndExcluding": "5.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version."}, {"lang": "es", "value": "django-s3file es una entrada ligera de subida de archivos para Django y Amazon S3 . En versiones anteriores a 5.5.1, era posible recorrer todo el bucket de AWS S3 y en la mayor\u00eda de los casos acceder o eliminar archivos. Si el ajuste \"AWS_LOCATION\" estaba configurado, el recorrido se limitaba s\u00f3lo a esa ubicaci\u00f3n. El problema fue detectado por el mantenedor. No se presentan informes de que la vulnerabilidad sea conocida o explotada por terceros, antes de la publicaci\u00f3n del parche. La vulnerabilidad ha sido corregida en versi\u00f3n 5.5.1 y superiores. No se presenta ninguna mitigaci\u00f3n viable. Debemos instar a todos los usuarios a actualizar inmediatamente a la versi\u00f3n parcheada"}], "evaluatorComment": null, "id": "CVE-2022-24840", "lastModified": "2022-06-17T15:50:50.613", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 9.1, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-06-09T04:15:10.707", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/security/advisories/GHSA-4w8f-hjm9-xwgf"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, "type": "CWE-22"}
327
Determine whether the {function_name} code is vulnerable or not.
[ "", "import tempfile", "from pathlib import Path", "\nimport pytest\nfrom django.core.files.base import ContentFile\nfrom django.utils.encoding import force_str\nfrom selenium import webdriver\nfrom selenium.common.exceptions import WebDriverException", "\nfrom s3file.storages import storage", "", "@pytest.fixture(scope=\"session\")\ndef driver():\n chrome_options = webdriver.ChromeOptions()\n chrome_options.headless = True\n try:\n b = webdriver.Chrome(options=chrome_options)\n except WebDriverException as e:\n pytest.skip(force_str(e))\n else:\n yield b\n b.quit()", "\n@pytest.fixture", "def freeze_upload_folder(monkeypatch):\n \"\"\"Freeze datetime and UUID.\"\"\"\n upload_folder = Path(storage.aws_location) / \"tmp\" / \"s3file\"\n monkeypatch.setattr(\n \"s3file.forms.S3FileInputMixin.upload_folder\",\n str(upload_folder),\n )\n return upload_folder", "", "@pytest.fixture", "def upload_file(request, freeze_upload_folder):\n path = Path(tempfile.mkdtemp()) / freeze_upload_folder / f\"{request.node.name}.txt\"\n path.parent.mkdir(parents=True, exist_ok=True)\n with path.open(\"w\") as f:", " f.write(request.node.name)", " return str(path.absolute())", "", "@pytest.fixture", "def another_upload_file(request, freeze_upload_folder):\n path = (\n Path(tempfile.mkdtemp())\n / freeze_upload_folder\n / f\"another_{request.node.name}.txt\"\n )\n path.parent.mkdir(parents=True, exist_ok=True)\n with path.open(\"w\") as f:", " f.write(request.node.name)", " return str(path.absolute())", "\n@pytest.fixture\ndef yet_another_upload_file(request, freeze_upload_folder):\n path = (\n Path(tempfile.mkdtemp())\n / freeze_upload_folder\n / f\"yet_another_{request.node.name}.txt\"\n )\n path.parent.mkdir(parents=True, exist_ok=True)\n with path.open(\"w\") as f:\n f.write(request.node.name)\n return str(path.absolute())", "", "@pytest.fixture\ndef filemodel(request, db):\n from tests.testapp.models import FileModel", " return FileModel.objects.create(\n file=ContentFile(request.node.name, \"%s.txt\" % request.node.name)\n )" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 37, 96, 4, 49, 215, 80], "buggy_code_start_loc": [6, 4, 96, 4, 1, 34, 2], "filenames": ["s3file/forms.py", "s3file/middleware.py", "s3file/static/s3file/js/s3file.js", "s3file/views.py", "tests/conftest.py", "tests/test_forms.py", "tests/test_middleware.py"], "fixing_code_end_loc": [58, 66, 103, 6, 70, 223, 134], "fixing_code_start_loc": [7, 4, 97, 5, 0, 34, 3], "message": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:django-s3file_project:django-s3file:*:*:*:*:*:*:*:*", "matchCriteriaId": "A7EFD2FC-D3B5-4C07-ABA9-66B318FD04F1", "versionEndExcluding": "5.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version."}, {"lang": "es", "value": "django-s3file es una entrada ligera de subida de archivos para Django y Amazon S3 . En versiones anteriores a 5.5.1, era posible recorrer todo el bucket de AWS S3 y en la mayor\u00eda de los casos acceder o eliminar archivos. Si el ajuste \"AWS_LOCATION\" estaba configurado, el recorrido se limitaba s\u00f3lo a esa ubicaci\u00f3n. El problema fue detectado por el mantenedor. No se presentan informes de que la vulnerabilidad sea conocida o explotada por terceros, antes de la publicaci\u00f3n del parche. La vulnerabilidad ha sido corregida en versi\u00f3n 5.5.1 y superiores. No se presenta ninguna mitigaci\u00f3n viable. Debemos instar a todos los usuarios a actualizar inmediatamente a la versi\u00f3n parcheada"}], "evaluatorComment": null, "id": "CVE-2022-24840", "lastModified": "2022-06-17T15:50:50.613", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 9.1, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-06-09T04:15:10.707", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/security/advisories/GHSA-4w8f-hjm9-xwgf"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, "type": "CWE-22"}
327
Determine whether the {function_name} code is vulnerable or not.
[ "import json\nimport os\nfrom contextlib import contextmanager", "import pytest\nfrom django.forms import ClearableFileInput\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.expected_conditions import staleness_of\nfrom selenium.webdriver.support.wait import WebDriverWait", "from s3file.storages import storage\nfrom tests.testapp.forms import UploadForm", "try:\n from django.urls import reverse\nexcept ImportError:\n # Django 1.8 support\n from django.core.urlresolvers import reverse", "\n@contextmanager\ndef wait_for_page_load(driver, timeout=30):\n old_page = driver.find_element(By.TAG_NAME, \"html\")\n yield\n WebDriverWait(driver, timeout).until(staleness_of(old_page))", "\nclass TestS3FileInput:\n @property\n def url(self):\n return reverse(\"upload\")\n", " @pytest.fixture\n def freeze(self, monkeypatch):\n \"\"\"Freeze datetime and UUID.\"\"\"\n monkeypatch.setattr(\n \"s3file.forms.S3FileInputMixin.upload_folder\",\n os.path.join(storage.aws_location, \"tmp\"),\n )", " def test_value_from_datadict(self, client, upload_file):\n print(storage.location)", " with open(upload_file) as f:", " uploaded_file = storage.save(\"test.jpg\", f)", " response = client.post(\n reverse(\"upload\"),\n {", " \"file\": json.dumps([uploaded_file]),\n \"s3file\": '[\"file\"]',", " },\n )", " assert response.status_code == 201", " def test_value_from_datadict_initial_data(self, filemodel):\n form = UploadForm(instance=filemodel)\n assert filemodel.file.name in form.as_p(), form.as_p()\n assert not form.is_valid()", " def test_file_does_not_exist_no_fallback(self, filemodel):\n form = UploadForm(\n data={\"file\": \"foo.bar\", \"s3file\": \"file\"},\n instance=filemodel,\n )\n assert form.is_valid()\n assert form.cleaned_data[\"file\"] == filemodel.file", " def test_initial_no_file_uploaded(self, filemodel):\n form = UploadForm(data={\"file\": \"\"}, instance=filemodel)\n assert form.is_valid(), form.errors\n assert not form.has_changed()\n assert form.cleaned_data[\"file\"] == filemodel.file", " def test_initial_fallback(self, filemodel):\n form = UploadForm(data={\"file\": \"\"}, instance=filemodel)\n assert form.is_valid()\n assert form.cleaned_data[\"file\"] == filemodel.file", " def test_clear(self, filemodel):\n form = UploadForm(data={\"file-clear\": \"1\"}, instance=filemodel)\n assert form.is_valid()\n assert not form.cleaned_data[\"file\"]\n", " def test_build_attr(self):", " assert set(ClearableFileInput().build_attrs({}).keys()) == {\n \"class\",\n \"data-url\",\n \"data-fields-x-amz-algorithm\",\n \"data-fields-x-amz-date\",\n \"data-fields-x-amz-signature\",\n \"data-fields-x-amz-credential\",\n \"data-fields-policy\",\n \"data-fields-key\",", "", " }", "", " assert ClearableFileInput().build_attrs({})[\"class\"] == \"s3file\"\n assert (\n ClearableFileInput().build_attrs({\"class\": \"my-class\"})[\"class\"]\n == \"my-class s3file\"\n )\n", " def test_get_conditions(self, freeze):", " conditions = ClearableFileInput().get_conditions(None)\n assert all(\n condition in conditions\n for condition in [\n {\"bucket\": \"test-bucket\"},\n {\"success_action_status\": \"201\"},", " [\"starts-with\", \"$key\", \"custom/location/tmp\"],", " [\"starts-with\", \"$Content-Type\", \"\"],\n ]\n ), conditions", " def test_accept(self):\n widget = ClearableFileInput()\n assert \"accept\" not in widget.render(name=\"file\", value=\"test.jpg\")\n assert [\"starts-with\", \"$Content-Type\", \"\"] in widget.get_conditions(None)", " widget = ClearableFileInput(attrs={\"accept\": \"image/*\"})\n assert 'accept=\"image/*\"' in widget.render(name=\"file\", value=\"test.jpg\")\n assert [\"starts-with\", \"$Content-Type\", \"image/\"] in widget.get_conditions(\n \"image/*\"\n )", " widget = ClearableFileInput(attrs={\"accept\": \"image/jpeg\"})\n assert 'accept=\"image/jpeg\"' in widget.render(name=\"file\", value=\"test.jpg\")\n assert {\"Content-Type\": \"image/jpeg\"} in widget.get_conditions(\"image/jpeg\")", " widget = ClearableFileInput(attrs={\"accept\": \"application/pdf,image/*\"})\n assert 'accept=\"application/pdf,image/*\"' in widget.render(\n name=\"file\",\n value=\"test.jpg\",\n )\n assert [\"starts-with\", \"$Content-Type\", \"\"] in widget.get_conditions(\n \"application/pdf,image/*\"\n )\n assert {\"Content-Type\": \"application/pdf\"} not in widget.get_conditions(\n \"application/pdf,image/*\"\n )", " def test_no_js_error(self, driver, live_server):\n driver.get(live_server + self.url)", " with pytest.raises(NoSuchElementException):\n error = driver.find_element(By.XPATH, \"//body[@JSError]\")\n pytest.fail(error.get_attribute(\"JSError\"))\n", " def test_file_insert(self, request, driver, live_server, upload_file, freeze):", " driver.get(live_server + self.url)\n file_input = driver.find_element(By.XPATH, \"//input[@name='file']\")\n file_input.send_keys(upload_file)\n assert file_input.get_attribute(\"name\") == \"file\"\n with wait_for_page_load(driver, timeout=10):\n file_input.submit()", " assert storage.exists(\"tmp/%s.txt\" % request.node.name)", "\n with pytest.raises(NoSuchElementException):\n error = driver.find_element(By.XPATH, \"//body[@JSError]\")\n pytest.fail(error.get_attribute(\"JSError\"))\n", " def test_file_insert_submit_value(self, driver, live_server, upload_file, freeze):", " driver.get(live_server + self.url)\n file_input = driver.find_element(By.XPATH, \"//input[@name='file']\")\n file_input.send_keys(upload_file)\n assert file_input.get_attribute(\"name\") == \"file\"\n save_button = driver.find_element(By.XPATH, \"//input[@name='save']\")\n with wait_for_page_load(driver, timeout=10):\n save_button.click()\n assert \"save\" in driver.page_source", " driver.get(live_server + self.url)\n file_input = driver.find_element(By.XPATH, \"//input[@name='file']\")\n file_input.send_keys(upload_file)\n assert file_input.get_attribute(\"name\") == \"file\"\n save_button = driver.find_element(By.XPATH, \"//button[@name='save_continue']\")\n with wait_for_page_load(driver, timeout=10):\n save_button.click()\n assert \"save_continue\" in driver.page_source\n assert \"continue_value\" in driver.page_source\n", " def test_progress(self, driver, live_server, upload_file, freeze):", " driver.get(live_server + self.url)\n file_input = driver.find_element(By.XPATH, \"//input[@name='file']\")\n file_input.send_keys(upload_file)\n assert file_input.get_attribute(\"name\") == \"file\"\n save_button = driver.find_element(By.XPATH, \"//input[@name='save']\")\n with wait_for_page_load(driver, timeout=10):\n save_button.click()\n assert \"save\" in driver.page_source", " driver.get(live_server + self.url)\n file_input = driver.find_element(By.XPATH, \"//input[@name='file']\")\n file_input.send_keys(upload_file)\n assert file_input.get_attribute(\"name\") == \"file\"\n save_button = driver.find_element(By.XPATH, \"//button[@name='save_continue']\")\n with wait_for_page_load(driver, timeout=10):\n save_button.click()\n response = json.loads(driver.find_elements(By.CSS_SELECTOR, \"pre\")[0].text)\n assert response[\"POST\"][\"progress\"] == \"1\"", " def test_multi_file(\n self,\n driver,\n live_server,", " freeze,", " upload_file,\n another_upload_file,\n yet_another_upload_file,\n ):\n driver.get(live_server + self.url)\n file_input = driver.find_element(By.XPATH, \"//input[@name='file']\")", " file_input.send_keys(\" \\n \".join([upload_file, another_upload_file]))", " file_input = driver.find_element(By.XPATH, \"//input[@name='other_file']\")", " file_input.send_keys(yet_another_upload_file)", " save_button = driver.find_element(By.XPATH, \"//input[@name='save']\")\n with wait_for_page_load(driver, timeout=10):\n save_button.click()\n response = json.loads(driver.find_elements(By.CSS_SELECTOR, \"pre\")[0].text)\n assert response[\"FILES\"] == {\n \"file\": [\n os.path.basename(upload_file),\n os.path.basename(another_upload_file),\n ],\n \"other_file\": [os.path.basename(yet_another_upload_file)],\n }", " def test_media(self):\n assert ClearableFileInput().media._js == [\"s3file/js/s3file.js\"]", " def test_upload_folder(self):\n assert \"custom/location/tmp/s3file/\" in ClearableFileInput().upload_folder\n assert len(os.path.basename(ClearableFileInput().upload_folder)) == 22" ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 37, 96, 4, 49, 215, 80], "buggy_code_start_loc": [6, 4, 96, 4, 1, 34, 2], "filenames": ["s3file/forms.py", "s3file/middleware.py", "s3file/static/s3file/js/s3file.js", "s3file/views.py", "tests/conftest.py", "tests/test_forms.py", "tests/test_middleware.py"], "fixing_code_end_loc": [58, 66, 103, 6, 70, 223, 134], "fixing_code_start_loc": [7, 4, 97, 5, 0, 34, 3], "message": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:django-s3file_project:django-s3file:*:*:*:*:*:*:*:*", "matchCriteriaId": "A7EFD2FC-D3B5-4C07-ABA9-66B318FD04F1", "versionEndExcluding": "5.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version."}, {"lang": "es", "value": "django-s3file es una entrada ligera de subida de archivos para Django y Amazon S3 . En versiones anteriores a 5.5.1, era posible recorrer todo el bucket de AWS S3 y en la mayor\u00eda de los casos acceder o eliminar archivos. Si el ajuste \"AWS_LOCATION\" estaba configurado, el recorrido se limitaba s\u00f3lo a esa ubicaci\u00f3n. El problema fue detectado por el mantenedor. No se presentan informes de que la vulnerabilidad sea conocida o explotada por terceros, antes de la publicaci\u00f3n del parche. La vulnerabilidad ha sido corregida en versi\u00f3n 5.5.1 y superiores. No se presenta ninguna mitigaci\u00f3n viable. Debemos instar a todos los usuarios a actualizar inmediatamente a la versi\u00f3n parcheada"}], "evaluatorComment": null, "id": "CVE-2022-24840", "lastModified": "2022-06-17T15:50:50.613", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 9.1, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-06-09T04:15:10.707", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/security/advisories/GHSA-4w8f-hjm9-xwgf"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, "type": "CWE-22"}
327
Determine whether the {function_name} code is vulnerable or not.
[ "import json\nimport os\nfrom contextlib import contextmanager", "import pytest\nfrom django.forms import ClearableFileInput\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.expected_conditions import staleness_of\nfrom selenium.webdriver.support.wait import WebDriverWait", "from s3file.storages import storage\nfrom tests.testapp.forms import UploadForm", "try:\n from django.urls import reverse\nexcept ImportError:\n # Django 1.8 support\n from django.core.urlresolvers import reverse", "\n@contextmanager\ndef wait_for_page_load(driver, timeout=30):\n old_page = driver.find_element(By.TAG_NAME, \"html\")\n yield\n WebDriverWait(driver, timeout).until(staleness_of(old_page))", "\nclass TestS3FileInput:\n @property\n def url(self):\n return reverse(\"upload\")\n", " def test_value_from_datadict(self, freeze_upload_folder, client, upload_file):", " with open(upload_file) as f:", " uploaded_file = storage.save(freeze_upload_folder / \"test.jpg\", f)", " response = client.post(\n reverse(\"upload\"),\n {", " \"file\": f\"custom/location/{uploaded_file}\",\n \"file-s3f-signature\": \"m94qBxBsnMIuIICiY133kX18KkllSPMVbhGAdAwNn1A\",\n \"s3file\": \"file\",", " },\n )", " assert response.status_code == 201", " def test_value_from_datadict_initial_data(self, filemodel):\n form = UploadForm(instance=filemodel)\n assert filemodel.file.name in form.as_p(), form.as_p()\n assert not form.is_valid()", " def test_file_does_not_exist_no_fallback(self, filemodel):\n form = UploadForm(\n data={\"file\": \"foo.bar\", \"s3file\": \"file\"},\n instance=filemodel,\n )\n assert form.is_valid()\n assert form.cleaned_data[\"file\"] == filemodel.file", " def test_initial_no_file_uploaded(self, filemodel):\n form = UploadForm(data={\"file\": \"\"}, instance=filemodel)\n assert form.is_valid(), form.errors\n assert not form.has_changed()\n assert form.cleaned_data[\"file\"] == filemodel.file", " def test_initial_fallback(self, filemodel):\n form = UploadForm(data={\"file\": \"\"}, instance=filemodel)\n assert form.is_valid()\n assert form.cleaned_data[\"file\"] == filemodel.file", " def test_clear(self, filemodel):\n form = UploadForm(data={\"file-clear\": \"1\"}, instance=filemodel)\n assert form.is_valid()\n assert not form.cleaned_data[\"file\"]\n", " def test_build_attr(self, freeze_upload_folder):", " assert set(ClearableFileInput().build_attrs({}).keys()) == {\n \"class\",\n \"data-url\",\n \"data-fields-x-amz-algorithm\",\n \"data-fields-x-amz-date\",\n \"data-fields-x-amz-signature\",\n \"data-fields-x-amz-credential\",\n \"data-fields-policy\",\n \"data-fields-key\",", " \"data-s3f-signature\",", " }", " assert (\n ClearableFileInput().build_attrs({})[\"data-s3f-signature\"]\n == \"tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc\"\n )", " assert ClearableFileInput().build_attrs({})[\"class\"] == \"s3file\"\n assert (\n ClearableFileInput().build_attrs({\"class\": \"my-class\"})[\"class\"]\n == \"my-class s3file\"\n )\n", " def test_get_conditions(self, freeze_upload_folder):", " conditions = ClearableFileInput().get_conditions(None)\n assert all(\n condition in conditions\n for condition in [\n {\"bucket\": \"test-bucket\"},\n {\"success_action_status\": \"201\"},", " [\"starts-with\", \"$key\", \"custom/location/tmp/s3file\"],", " [\"starts-with\", \"$Content-Type\", \"\"],\n ]\n ), conditions", " def test_accept(self):\n widget = ClearableFileInput()\n assert \"accept\" not in widget.render(name=\"file\", value=\"test.jpg\")\n assert [\"starts-with\", \"$Content-Type\", \"\"] in widget.get_conditions(None)", " widget = ClearableFileInput(attrs={\"accept\": \"image/*\"})\n assert 'accept=\"image/*\"' in widget.render(name=\"file\", value=\"test.jpg\")\n assert [\"starts-with\", \"$Content-Type\", \"image/\"] in widget.get_conditions(\n \"image/*\"\n )", " widget = ClearableFileInput(attrs={\"accept\": \"image/jpeg\"})\n assert 'accept=\"image/jpeg\"' in widget.render(name=\"file\", value=\"test.jpg\")\n assert {\"Content-Type\": \"image/jpeg\"} in widget.get_conditions(\"image/jpeg\")", " widget = ClearableFileInput(attrs={\"accept\": \"application/pdf,image/*\"})\n assert 'accept=\"application/pdf,image/*\"' in widget.render(\n name=\"file\",\n value=\"test.jpg\",\n )\n assert [\"starts-with\", \"$Content-Type\", \"\"] in widget.get_conditions(\n \"application/pdf,image/*\"\n )\n assert {\"Content-Type\": \"application/pdf\"} not in widget.get_conditions(\n \"application/pdf,image/*\"\n )", " def test_no_js_error(self, driver, live_server):\n driver.get(live_server + self.url)", " with pytest.raises(NoSuchElementException):\n error = driver.find_element(By.XPATH, \"//body[@JSError]\")\n pytest.fail(error.get_attribute(\"JSError\"))\n", " def test_file_insert(\n self, request, driver, live_server, upload_file, freeze_upload_folder\n ):", " driver.get(live_server + self.url)\n file_input = driver.find_element(By.XPATH, \"//input[@name='file']\")\n file_input.send_keys(upload_file)\n assert file_input.get_attribute(\"name\") == \"file\"\n with wait_for_page_load(driver, timeout=10):\n file_input.submit()", " assert storage.exists(\"tmp/s3file/%s.txt\" % request.node.name)", "\n with pytest.raises(NoSuchElementException):\n error = driver.find_element(By.XPATH, \"//body[@JSError]\")\n pytest.fail(error.get_attribute(\"JSError\"))\n", " def test_file_insert_submit_value(\n self, driver, live_server, upload_file, freeze_upload_folder\n ):", " driver.get(live_server + self.url)\n file_input = driver.find_element(By.XPATH, \"//input[@name='file']\")\n file_input.send_keys(upload_file)\n assert file_input.get_attribute(\"name\") == \"file\"\n save_button = driver.find_element(By.XPATH, \"//input[@name='save']\")\n with wait_for_page_load(driver, timeout=10):\n save_button.click()\n assert \"save\" in driver.page_source", " driver.get(live_server + self.url)\n file_input = driver.find_element(By.XPATH, \"//input[@name='file']\")\n file_input.send_keys(upload_file)\n assert file_input.get_attribute(\"name\") == \"file\"\n save_button = driver.find_element(By.XPATH, \"//button[@name='save_continue']\")\n with wait_for_page_load(driver, timeout=10):\n save_button.click()\n assert \"save_continue\" in driver.page_source\n assert \"continue_value\" in driver.page_source\n", " def test_progress(self, driver, live_server, upload_file, freeze_upload_folder):", " driver.get(live_server + self.url)\n file_input = driver.find_element(By.XPATH, \"//input[@name='file']\")\n file_input.send_keys(upload_file)\n assert file_input.get_attribute(\"name\") == \"file\"\n save_button = driver.find_element(By.XPATH, \"//input[@name='save']\")\n with wait_for_page_load(driver, timeout=10):\n save_button.click()\n assert \"save\" in driver.page_source", " driver.get(live_server + self.url)\n file_input = driver.find_element(By.XPATH, \"//input[@name='file']\")\n file_input.send_keys(upload_file)\n assert file_input.get_attribute(\"name\") == \"file\"\n save_button = driver.find_element(By.XPATH, \"//button[@name='save_continue']\")\n with wait_for_page_load(driver, timeout=10):\n save_button.click()\n response = json.loads(driver.find_elements(By.CSS_SELECTOR, \"pre\")[0].text)\n assert response[\"POST\"][\"progress\"] == \"1\"", " def test_multi_file(\n self,\n driver,\n live_server,", " freeze_upload_folder,", " upload_file,\n another_upload_file,\n yet_another_upload_file,\n ):\n driver.get(live_server + self.url)\n file_input = driver.find_element(By.XPATH, \"//input[@name='file']\")", " file_input.send_keys(\n \" \\n \".join(\n [\n str(freeze_upload_folder / upload_file),\n str(freeze_upload_folder / another_upload_file),\n ]\n )\n )", " file_input = driver.find_element(By.XPATH, \"//input[@name='other_file']\")", " file_input.send_keys(str(freeze_upload_folder / yet_another_upload_file))", " save_button = driver.find_element(By.XPATH, \"//input[@name='save']\")\n with wait_for_page_load(driver, timeout=10):\n save_button.click()\n response = json.loads(driver.find_elements(By.CSS_SELECTOR, \"pre\")[0].text)\n assert response[\"FILES\"] == {\n \"file\": [\n os.path.basename(upload_file),\n os.path.basename(another_upload_file),\n ],\n \"other_file\": [os.path.basename(yet_another_upload_file)],\n }", " def test_media(self):\n assert ClearableFileInput().media._js == [\"s3file/js/s3file.js\"]", " def test_upload_folder(self):\n assert \"custom/location/tmp/s3file/\" in ClearableFileInput().upload_folder\n assert len(os.path.basename(ClearableFileInput().upload_folder)) == 22" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 37, 96, 4, 49, 215, 80], "buggy_code_start_loc": [6, 4, 96, 4, 1, 34, 2], "filenames": ["s3file/forms.py", "s3file/middleware.py", "s3file/static/s3file/js/s3file.js", "s3file/views.py", "tests/conftest.py", "tests/test_forms.py", "tests/test_middleware.py"], "fixing_code_end_loc": [58, 66, 103, 6, 70, 223, 134], "fixing_code_start_loc": [7, 4, 97, 5, 0, 34, 3], "message": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:django-s3file_project:django-s3file:*:*:*:*:*:*:*:*", "matchCriteriaId": "A7EFD2FC-D3B5-4C07-ABA9-66B318FD04F1", "versionEndExcluding": "5.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version."}, {"lang": "es", "value": "django-s3file es una entrada ligera de subida de archivos para Django y Amazon S3 . En versiones anteriores a 5.5.1, era posible recorrer todo el bucket de AWS S3 y en la mayor\u00eda de los casos acceder o eliminar archivos. Si el ajuste \"AWS_LOCATION\" estaba configurado, el recorrido se limitaba s\u00f3lo a esa ubicaci\u00f3n. El problema fue detectado por el mantenedor. No se presentan informes de que la vulnerabilidad sea conocida o explotada por terceros, antes de la publicaci\u00f3n del parche. La vulnerabilidad ha sido corregida en versi\u00f3n 5.5.1 y superiores. No se presenta ninguna mitigaci\u00f3n viable. Debemos instar a todos los usuarios a actualizar inmediatamente a la versi\u00f3n parcheada"}], "evaluatorComment": null, "id": "CVE-2022-24840", "lastModified": "2022-06-17T15:50:50.613", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 9.1, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-06-09T04:15:10.707", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/security/advisories/GHSA-4w8f-hjm9-xwgf"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, "type": "CWE-22"}
327
Determine whether the {function_name} code is vulnerable or not.
[ "import os\n", "", "from django.core.files.base import ContentFile\nfrom django.core.files.uploadedfile import SimpleUploadedFile", "from s3file.middleware import S3FileMiddleware\nfrom s3file.storages import storage", "\nclass TestS3FileMiddleware:", " def test_get_files_from_storage(self):", " content = b\"test_get_files_from_storage\"\n name = storage.save(\n \"tmp/s3file/test_get_files_from_storage\", ContentFile(content)\n )\n files = S3FileMiddleware.get_files_from_storage(", " [os.path.join(storage.aws_location, name)]", " )\n file = next(files)\n assert file.read() == content\n", " def test_process_request(self, rf):", " uploaded_file = SimpleUploadedFile(\"uploaded_file.txt\", b\"uploaded\")\n request = rf.post(\"/\", data={\"file\": uploaded_file})\n S3FileMiddleware(lambda x: None)(request)\n assert request.FILES.getlist(\"file\")\n assert request.FILES.get(\"file\").read() == b\"uploaded\"", " storage.save(\"tmp/s3file/s3_file.txt\", ContentFile(b\"s3file\"))\n request = rf.post(\n \"/\",\n data={\n \"file\": \"custom/location/tmp/s3file/s3_file.txt\",\n \"s3file\": \"file\",", "", " },\n )\n S3FileMiddleware(lambda x: None)(request)\n assert request.FILES.getlist(\"file\")\n assert request.FILES.get(\"file\").read() == b\"s3file\"\n", " def test_process_request__multiple_files(self, rf):", " storage.save(\"tmp/s3file/s3_file.txt\", ContentFile(b\"s3file\"))\n storage.save(\"tmp/s3file/s3_other_file.txt\", ContentFile(b\"other s3file\"))\n request = rf.post(\n \"/\",\n data={\n \"file\": [\n \"custom/location/tmp/s3file/s3_file.txt\",\n \"custom/location/tmp/s3file/s3_other_file.txt\",\n ],", "", " \"s3file\": [\"file\", \"other_file\"],\n },\n )\n S3FileMiddleware(lambda x: None)(request)\n files = request.FILES.getlist(\"file\")\n assert files[0].read() == b\"s3file\"\n assert files[1].read() == b\"other s3file\"\n", " def test_process_request__no_location(self, rf, settings):", " settings.AWS_LOCATION = \"\"\n uploaded_file = SimpleUploadedFile(\"uploaded_file.txt\", b\"uploaded\")\n request = rf.post(\"/\", data={\"file\": uploaded_file})\n S3FileMiddleware(lambda x: None)(request)\n assert request.FILES.getlist(\"file\")\n assert request.FILES.get(\"file\").read() == b\"uploaded\"", " storage.save(\"tmp/s3file/s3_file.txt\", ContentFile(b\"s3file\"))\n request = rf.post(", " \"/\", data={\"file\": \"tmp/s3file/s3_file.txt\", \"s3file\": \"file\"}", " )\n S3FileMiddleware(lambda x: None)(request)\n assert request.FILES.getlist(\"file\")\n assert request.FILES.get(\"file\").read() == b\"s3file\"\n", " def test_process_request__no_file(self, rf, caplog):\n request = rf.post(\"/\", data={\"file\": \"does_not_exist.txt\", \"s3file\": \"file\"})", " S3FileMiddleware(lambda x: None)(request)\n assert not request.FILES.getlist(\"file\")", " assert \"File not found: does_not_exist.txt\" in caplog.text" ]
[ 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0 ]
PreciseBugs
{"buggy_code_end_loc": [47, 37, 96, 4, 49, 215, 80], "buggy_code_start_loc": [6, 4, 96, 4, 1, 34, 2], "filenames": ["s3file/forms.py", "s3file/middleware.py", "s3file/static/s3file/js/s3file.js", "s3file/views.py", "tests/conftest.py", "tests/test_forms.py", "tests/test_middleware.py"], "fixing_code_end_loc": [58, 66, 103, 6, 70, 223, 134], "fixing_code_start_loc": [7, 4, 97, 5, 0, 34, 3], "message": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:django-s3file_project:django-s3file:*:*:*:*:*:*:*:*", "matchCriteriaId": "A7EFD2FC-D3B5-4C07-ABA9-66B318FD04F1", "versionEndExcluding": "5.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version."}, {"lang": "es", "value": "django-s3file es una entrada ligera de subida de archivos para Django y Amazon S3 . En versiones anteriores a 5.5.1, era posible recorrer todo el bucket de AWS S3 y en la mayor\u00eda de los casos acceder o eliminar archivos. Si el ajuste \"AWS_LOCATION\" estaba configurado, el recorrido se limitaba s\u00f3lo a esa ubicaci\u00f3n. El problema fue detectado por el mantenedor. No se presentan informes de que la vulnerabilidad sea conocida o explotada por terceros, antes de la publicaci\u00f3n del parche. La vulnerabilidad ha sido corregida en versi\u00f3n 5.5.1 y superiores. No se presenta ninguna mitigaci\u00f3n viable. Debemos instar a todos los usuarios a actualizar inmediatamente a la versi\u00f3n parcheada"}], "evaluatorComment": null, "id": "CVE-2022-24840", "lastModified": "2022-06-17T15:50:50.613", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 9.1, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-06-09T04:15:10.707", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/security/advisories/GHSA-4w8f-hjm9-xwgf"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, "type": "CWE-22"}
327
Determine whether the {function_name} code is vulnerable or not.
[ "import os\n", "import pytest\nfrom django.core.exceptions import PermissionDenied, SuspiciousFileOperation", "from django.core.files.base import ContentFile\nfrom django.core.files.uploadedfile import SimpleUploadedFile", "from s3file.middleware import S3FileMiddleware\nfrom s3file.storages import storage", "\nclass TestS3FileMiddleware:", " def test_get_files_from_storage(self, freeze_upload_folder):", " content = b\"test_get_files_from_storage\"\n name = storage.save(\n \"tmp/s3file/test_get_files_from_storage\", ContentFile(content)\n )\n files = S3FileMiddleware.get_files_from_storage(", " [os.path.join(storage.aws_location, name)],\n \"tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc\",", " )\n file = next(files)\n assert file.read() == content\n", " def test_process_request(self, freeze_upload_folder, rf):", " uploaded_file = SimpleUploadedFile(\"uploaded_file.txt\", b\"uploaded\")\n request = rf.post(\"/\", data={\"file\": uploaded_file})\n S3FileMiddleware(lambda x: None)(request)\n assert request.FILES.getlist(\"file\")\n assert request.FILES.get(\"file\").read() == b\"uploaded\"", " storage.save(\"tmp/s3file/s3_file.txt\", ContentFile(b\"s3file\"))\n request = rf.post(\n \"/\",\n data={\n \"file\": \"custom/location/tmp/s3file/s3_file.txt\",\n \"s3file\": \"file\",", " \"file-s3f-signature\": \"tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc\",", " },\n )\n S3FileMiddleware(lambda x: None)(request)\n assert request.FILES.getlist(\"file\")\n assert request.FILES.get(\"file\").read() == b\"s3file\"\n", " def test_process_request__location_escape(self, freeze_upload_folder, rf):\n storage.save(\"secrets/passwords.txt\", ContentFile(b\"keep this secret\"))\n request = rf.post(\n \"/\",\n data={\n \"file\": \"custom/location/secrets/passwords.txt\",\n \"s3file\": \"file\",\n \"file-s3f-signature\": \"tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc\",\n },\n )\n with pytest.raises(PermissionDenied) as e:\n S3FileMiddleware(lambda x: None)(request)\n assert \"Illegal signature!\" in str(e.value)", " def test_process_request__multiple_files(self, freeze_upload_folder, rf):", " storage.save(\"tmp/s3file/s3_file.txt\", ContentFile(b\"s3file\"))\n storage.save(\"tmp/s3file/s3_other_file.txt\", ContentFile(b\"other s3file\"))\n request = rf.post(\n \"/\",\n data={\n \"file\": [\n \"custom/location/tmp/s3file/s3_file.txt\",\n \"custom/location/tmp/s3file/s3_other_file.txt\",\n ],", " \"file-s3f-signature\": \"tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc\",\n \"other_file-s3f-signature\": \"tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc\",", " \"s3file\": [\"file\", \"other_file\"],\n },\n )\n S3FileMiddleware(lambda x: None)(request)\n files = request.FILES.getlist(\"file\")\n assert files[0].read() == b\"s3file\"\n assert files[1].read() == b\"other s3file\"\n", " def test_process_request__no_location(self, freeze_upload_folder, rf, settings):", " settings.AWS_LOCATION = \"\"\n uploaded_file = SimpleUploadedFile(\"uploaded_file.txt\", b\"uploaded\")\n request = rf.post(\"/\", data={\"file\": uploaded_file})\n S3FileMiddleware(lambda x: None)(request)\n assert request.FILES.getlist(\"file\")\n assert request.FILES.get(\"file\").read() == b\"uploaded\"", " storage.save(\"tmp/s3file/s3_file.txt\", ContentFile(b\"s3file\"))\n request = rf.post(", " \"/\",\n data={\n \"file\": f\"tmp/s3file/s3_file.txt\",\n \"s3file\": \"file\",\n \"file-s3f-signature\": \"scjzm3N8njBQIVSGEhOchtM0TkGyb2U6OXGLVlRUZhY\",\n },", " )\n S3FileMiddleware(lambda x: None)(request)\n assert request.FILES.getlist(\"file\")\n assert request.FILES.get(\"file\").read() == b\"s3file\"\n", " def test_process_request__no_file(self, freeze_upload_folder, rf, caplog):\n request = rf.post(\n \"/\",\n data={\n \"file\": \"custom/location/tmp/s3file/does_not_exist.txt\",\n \"s3file\": \"file\",\n \"file-s3f-signature\": \"tFV9nGZlq9WX1I5Sotit18z1f4C_3lPnj33_zo4LZRc\",\n },\n )", " S3FileMiddleware(lambda x: None)(request)\n assert not request.FILES.getlist(\"file\")", " assert (\n \"File not found: custom/location/tmp/s3file/does_not_exist.txt\"\n in caplog.text\n )", " def test_process_request__no_signature(self, rf, caplog):\n request = rf.post(\n \"/\", data={\"file\": \"tmp/s3file/does_not_exist.txt\", \"s3file\": \"file\"}\n )\n with pytest.raises(PermissionDenied) as e:\n S3FileMiddleware(lambda x: None)(request)", " def test_process_request__wrong_signature(self, rf, caplog):\n request = rf.post(\n \"/\",\n data={\n \"file\": \"tmp/s3file/does_not_exist.txt\",\n \"s3file\": \"file\",\n \"file-s3f-signature\": \"fake\",\n },\n )\n with pytest.raises(PermissionDenied) as e:\n S3FileMiddleware(lambda x: None)(request)" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [47, 37, 96, 4, 49, 215, 80], "buggy_code_start_loc": [6, 4, 96, 4, 1, 34, 2], "filenames": ["s3file/forms.py", "s3file/middleware.py", "s3file/static/s3file/js/s3file.js", "s3file/views.py", "tests/conftest.py", "tests/test_forms.py", "tests/test_middleware.py"], "fixing_code_end_loc": [58, 66, 103, 6, 70, 223, 134], "fixing_code_start_loc": [7, 4, 97, 5, 0, 34, 3], "message": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:django-s3file_project:django-s3file:*:*:*:*:*:*:*:*", "matchCriteriaId": "A7EFD2FC-D3B5-4C07-ABA9-66B318FD04F1", "versionEndExcluding": "5.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "django-s3file is a lightweight file upload input for Django and Amazon S3 . In versions prior to 5.5.1 it was possible to traverse the entire AWS S3 bucket and in most cases to access or delete files. If the `AWS_LOCATION` setting was set, traversal was limited to that location only. The issue was discovered by the maintainer. There were no reports of the vulnerability being known to or exploited by a third party, prior to the release of the patch. The vulnerability has been fixed in version 5.5.1 and above. There is no feasible workaround. We must urge all users to immediately updated to a patched version."}, {"lang": "es", "value": "django-s3file es una entrada ligera de subida de archivos para Django y Amazon S3 . En versiones anteriores a 5.5.1, era posible recorrer todo el bucket de AWS S3 y en la mayor\u00eda de los casos acceder o eliminar archivos. Si el ajuste \"AWS_LOCATION\" estaba configurado, el recorrido se limitaba s\u00f3lo a esa ubicaci\u00f3n. El problema fue detectado por el mantenedor. No se presentan informes de que la vulnerabilidad sea conocida o explotada por terceros, antes de la publicaci\u00f3n del parche. La vulnerabilidad ha sido corregida en versi\u00f3n 5.5.1 y superiores. No se presenta ninguna mitigaci\u00f3n viable. Debemos instar a todos los usuarios a actualizar inmediatamente a la versi\u00f3n parcheada"}], "evaluatorComment": null, "id": "CVE-2022-24840", "lastModified": "2022-06-17T15:50:50.613", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 9.1, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-06-09T04:15:10.707", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/codingjoe/django-s3file/security/advisories/GHSA-4w8f-hjm9-xwgf"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/codingjoe/django-s3file/commit/68ccd2c621a40eb66fdd6af2be9d5fcc9c373318"}, "type": "CWE-22"}
327
Determine whether the {function_name} code is vulnerable or not.
[ "__author__ = \"Gina Häußge <osd@foosel.net>\"\n__license__ = \"GNU Affero General Public License http://www.gnu.org/licenses/agpl.html\"\n__copyright__ = \"Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License\"", "import copy\nimport logging\nimport os\nimport shutil\nfrom contextlib import contextmanager\nfrom os import scandir, walk", "import pylru", "import octoprint.filemanager\nfrom octoprint.util import (\n atomic_write,\n is_hidden_path,\n time_this,\n to_bytes,\n to_unicode,\n yaml,\n)\nfrom octoprint.util.files import sanitize_filename", "\nclass StorageInterface:\n \"\"\"\n Interface of storage adapters for OctoPrint.\n \"\"\"", " # noinspection PyUnreachableCode\n @property\n def analysis_backlog(self):\n \"\"\"\n Get an iterator over all items stored in the storage that need to be analysed by the :class:`~octoprint.filemanager.AnalysisQueue`.", " The yielded elements are expected as storage specific absolute paths to the respective files. Don't forget\n to recurse into folders if your storage adapter supports those.", " :return: an iterator yielding all un-analysed files in the storage\n \"\"\"\n # empty generator pattern, yield is intentionally unreachable\n return\n yield", " # noinspection PyUnreachableCode\n def analysis_backlog_for_path(self, path=None):\n # empty generator pattern, yield is intentionally unreachable\n return\n yield", " def last_modified(self, path=None, recursive=False):\n \"\"\"\n Get the last modification date of the specified ``path`` or ``path``'s subtree.", " Args:\n path (str or None): Path for which to determine the subtree's last modification date. If left out or\n set to None, defatuls to storage root.\n recursive (bool): Whether to determine only the date of the specified ``path`` (False, default) or\n the whole ``path``'s subtree (True).", " Returns: (float) The last modification date of the indicated subtree\n \"\"\"\n raise NotImplementedError()", " def file_in_path(self, path, filepath):\n \"\"\"\n Returns whether the file indicated by ``file`` is inside ``path`` or not.\n :param string path: the path to check\n :param string filepath: path to the file\n :return: ``True`` if the file is inside the path, ``False`` otherwise\n \"\"\"\n return NotImplementedError()", " def file_exists(self, path):\n \"\"\"\n Returns whether the file indicated by ``path`` exists or not.\n :param string path: the path to check for existence\n :return: ``True`` if the file exists, ``False`` otherwise\n \"\"\"\n raise NotImplementedError()", " def folder_exists(self, path):\n \"\"\"\n Returns whether the folder indicated by ``path`` exists or not.\n :param string path: the path to check for existence\n :return: ``True`` if the folder exists, ``False`` otherwise\n \"\"\"\n raise NotImplementedError()", " def list_files(\n self, path=None, filter=None, recursive=True, level=0, force_refresh=False\n ):\n \"\"\"\n List all files in storage starting at ``path``. If ``recursive`` is set to True (the default), also dives into\n subfolders.", " An optional filter function can be supplied which will be called with a file name and file data and which has\n to return True if the file is to be included in the result or False if not.", " The data structure of the returned result will be a dictionary mapping from file names to entry data. File nodes\n will contain their metadata here, folder nodes will contain their contained files and folders. Example::", " {\n \"some_folder\": {\n \"name\": \"some_folder\",\n \"path\": \"some_folder\",\n \"type\": \"folder\",\n \"children\": {\n \"some_sub_folder\": {\n \"name\": \"some_sub_folder\",\n \"path\": \"some_folder/some_sub_folder\",\n \"type\": \"folder\",\n \"typePath\": [\"folder\"],\n \"children\": { ... }\n },\n \"some_file.gcode\": {\n \"name\": \"some_file.gcode\",\n \"path\": \"some_folder/some_file.gcode\",\n \"type\": \"machinecode\",\n \"typePath\": [\"machinecode\", \"gcode\"],\n \"hash\": \"<sha1 hash>\",\n \"links\": [ ... ],\n ...\n },\n ...\n }\n \"test.gcode\": {\n \"name\": \"test.gcode\",\n \"path\": \"test.gcode\",\n \"type\": \"machinecode\",\n \"typePath\": [\"machinecode\", \"gcode\"],\n \"hash\": \"<sha1 hash>\",\n \"links\": [...],\n ...\n },\n \"test.stl\": {\n \"name\": \"test.stl\",\n \"path\": \"test.stl\",\n \"type\": \"model\",\n \"typePath\": [\"model\", \"stl\"],\n \"hash\": \"<sha1 hash>\",\n \"links\": [...],\n ...\n },\n ...\n }", " :param string path: base path from which to recursively list all files, optional, if not supplied listing will start\n from root of base folder\n :param function filter: a filter that matches the files that are to be returned, may be left out in which case no\n filtering will take place\n :param bool recursive: will also step into sub folders for building the complete list if set to True, otherwise will only\n do one step down into sub folders to be able to populate the ``children``.\n :return: a dictionary mapping entry names to entry data that represents the whole file list\n \"\"\"\n raise NotImplementedError()", " def add_folder(self, path, ignore_existing=True, display=None):\n \"\"\"\n Adds a folder as ``path``", " The ``path`` will be sanitized.", " :param string path: the path of the new folder\n :param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists\n :param unicode display: display name of the folder\n :return: the sanitized name of the new folder to be used for future references to the folder\n \"\"\"\n raise NotImplementedError()", " def remove_folder(self, path, recursive=True):\n \"\"\"\n Removes the folder at ``path``", " :param string path: the path of the folder to remove\n :param bool recursive: if set to True, contained folders and files will also be removed, otherwise an error will\n be raised if the folder is not empty (apart from any metadata files) when it's to be removed\n \"\"\"\n raise NotImplementedError()", " def copy_folder(self, source, destination):\n \"\"\"\n Copies the folder ``source`` to ``destination``", " :param string source: path to the source folder\n :param string destination: path to destination", " :return: the path in the storage to the copy of the folder\n \"\"\"\n raise NotImplementedError()", " def move_folder(self, source, destination):\n \"\"\"\n Moves the folder ``source`` to ``destination``", " :param string source: path to the source folder\n :param string destination: path to destination", " :return: the new path in the storage to the folder\n \"\"\"\n raise NotImplementedError()", " def add_file(\n self,\n path,\n file_object,\n printer_profile=None,\n links=None,\n allow_overwrite=False,\n display=None,\n ):\n \"\"\"\n Adds the file ``file_object`` as ``path``", " :param string path: the file's new path, will be sanitized\n :param object file_object: a file object that provides a ``save`` method which will be called with the destination path\n where the object should then store its contents\n :param object printer_profile: the printer profile associated with this file (if any)\n :param list links: any links to add with the file\n :param bool allow_overwrite: if set to True no error will be raised if the file already exists and the existing file\n and its metadata will just be silently overwritten\n :param unicode display: display name of the file\n :return: the sanitized name of the file to be used for future references to it\n \"\"\"\n raise NotImplementedError()", " def remove_file(self, path):\n \"\"\"\n Removes the file at ``path``", " Will also take care of deleting the corresponding entries\n in the metadata and deleting all links pointing to the file.", " :param string path: path of the file to remove\n \"\"\"\n raise NotImplementedError()", " def copy_file(self, source, destination):\n \"\"\"\n Copies the file ``source`` to ``destination``", " :param string source: path to the source file\n :param string destination: path to destination", " :return: the path in the storage to the copy of the file\n \"\"\"\n raise NotImplementedError()", " def move_file(self, source, destination):\n \"\"\"\n Moves the file ``source`` to ``destination``", " :param string source: path to the source file\n :param string destination: path to destination", " :return: the new path in the storage to the file\n \"\"\"\n raise NotImplementedError()", " def has_analysis(self, path):\n \"\"\"\n Returns whether the file at path has been analysed yet", " :param path: virtual path to the file for which to retrieve the metadata\n \"\"\"\n raise NotImplementedError()", " def get_metadata(self, path):\n \"\"\"\n Retrieves the metadata for the file ``path``.", " :param path: virtual path to the file for which to retrieve the metadata\n :return: the metadata associated with the file\n \"\"\"\n raise NotImplementedError()", " def add_link(self, path, rel, data):\n \"\"\"\n Adds a link of relation ``rel`` to file ``path`` with the given ``data``.", " The following relation types are currently supported:", " * ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name``\n and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the\n current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode``\n referring to ``name`` and its hash will also be added to the linked ``model`` file\n * ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected\n additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved\n against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse\n link of type ``model`` referring to ``name`` and its hash will also be added to the linked ``model`` file.\n * ``web``: adds a location on the web associated with this file (e.g. a website where to download a model),\n expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved``\n attribute describing when the content was retrieved", " Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying\n as machine code will be refused.", " :param path: path of the file for which to add a link\n :param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported)\n :param data: additional data of the link to add\n \"\"\"\n raise NotImplementedError()", " def remove_link(self, path, rel, data):\n \"\"\"\n Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``.", " :param path: path of the file from which to remove the link\n :param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported)\n :param data: additional data of the link to remove, must match existing link\n \"\"\"\n raise NotImplementedError()", " def get_additional_metadata(self, path, key):\n \"\"\"\n Fetches additional metadata at ``key`` from the metadata of ``path``.", " :param path: the virtual path to the file for which to fetch additional metadata\n :param key: key of metadata to fetch\n \"\"\"\n raise NotImplementedError()", " def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):\n \"\"\"\n Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``.", " If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten.", " If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries,\n the two dictionaries will be merged recursively.", " :param path: the virtual path to the file for which to add additional metadata\n :param key: key of metadata to add\n :param data: metadata to add\n :param overwrite: if True and ``key`` already exists, it will be overwritten\n :param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they\n will be merged\n \"\"\"\n raise NotImplementedError()", " def remove_additional_metadata(self, path, key):\n \"\"\"\n Removes additional metadata under ``key`` for ``name`` on ``path``", " :param path: the virtual path to the file for which to remove the metadata under ``key``\n :param key: the key to remove\n \"\"\"\n raise NotImplementedError()", " def canonicalize(self, path):\n \"\"\"\n Canonicalizes the given ``path``. The ``path`` may consist of both folder and file name, the underlying\n implementation must separate those if necessary.", " By default, this calls :func:`~octoprint.filemanager.StorageInterface.sanitize`, which also takes care\n of stripping any invalid characters.", " Args:\n path: the path to canonicalize", " Returns:\n a 2-tuple containing the canonicalized path and file name", " \"\"\"\n return self.sanitize(path)", " def sanitize(self, path):\n \"\"\"\n Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both\n folder and file name, the underlying implementation must separate those if necessary and sanitize individually.", " :param string path: the path to sanitize\n :return: a 2-tuple containing the sanitized path and file name\n \"\"\"\n raise NotImplementedError()", " def sanitize_path(self, path):\n \"\"\"\n Sanitizes the given folder-only ``path``, stripping it of all invalid characters.\n :param string path: the path to sanitize\n :return: the sanitized path\n \"\"\"\n raise NotImplementedError()", " def sanitize_name(self, name):\n \"\"\"\n Sanitizes the given file ``name``, stripping it of all invalid characters.\n :param string name: the file name to sanitize\n :return: the sanitized name\n \"\"\"\n raise NotImplementedError()", " def split_path(self, path):\n \"\"\"\n Split ``path`` into base directory and file name.\n :param path: the path to split\n :return: a tuple (base directory, file name)\n \"\"\"\n raise NotImplementedError()", " def join_path(self, *path):\n \"\"\"\n Join path elements together\n :param path: path elements to join\n :return: joined representation of the path to be usable as fully qualified path for further operations\n \"\"\"\n raise NotImplementedError()", " def path_on_disk(self, path):\n \"\"\"\n Retrieves the path on disk for ``path``.", " Note: if the storage is not on disk and there exists no path on disk to refer to it, this method should\n raise an :class:`io.UnsupportedOperation`", " Opposite of :func:`path_in_storage`.", " :param string path: the virtual path for which to retrieve the path on disk\n :return: the path on disk to ``path``\n \"\"\"\n raise NotImplementedError()", " def path_in_storage(self, path):\n \"\"\"\n Retrieves the equivalent in the storage adapter for ``path``.", " Opposite of :func:`path_on_disk`.", " :param string path: the path for which to retrieve the storage path\n :return: the path in storage to ``path``\n \"\"\"\n raise NotImplementedError()", "\nclass StorageError(Exception):\n UNKNOWN = \"unknown\"\n INVALID_DIRECTORY = \"invalid_directory\"\n INVALID_FILE = \"invalid_file\"\n INVALID_SOURCE = \"invalid_source\"\n INVALID_DESTINATION = \"invalid_destination\"\n DOES_NOT_EXIST = \"does_not_exist\"\n ALREADY_EXISTS = \"already_exists\"\n SOURCE_EQUALS_DESTINATION = \"source_equals_destination\"\n NOT_EMPTY = \"not_empty\"", " def __init__(self, message, code=None, cause=None):\n BaseException.__init__(self)\n self.message = message\n self.cause = cause", " if code is None:\n code = StorageError.UNKNOWN\n self.code = code", "\nclass LocalFileStorage(StorageInterface):\n \"\"\"\n The ``LocalFileStorage`` is a storage implementation which holds all files, folders and metadata on disk.", " Metadata is managed inside ``.metadata.json`` files in the respective folders, indexed by the sanitized filenames\n stored within the folder. Metadata access is managed through an LRU cache to minimize access overhead.", " This storage type implements :func:`path_on_disk`.\n \"\"\"", " def __init__(self, basefolder, create=False, really_universal=False):\n \"\"\"\n Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder\n if necessary and ``create`` is set to ``True``.", " :param string basefolder: the path to the folder under which to create the storage\n :param bool create: ``True`` if the folder should be created if it doesn't exist yet, ``False`` otherwise\n :param bool really_universal: ``True`` if the file names should be forced to really universal, ``False`` otherwise\n \"\"\"\n self._logger = logging.getLogger(__name__)", " self.basefolder = os.path.realpath(os.path.abspath(to_unicode(basefolder)))\n if not os.path.exists(self.basefolder) and create:\n os.makedirs(self.basefolder)\n if not os.path.exists(self.basefolder) or not os.path.isdir(self.basefolder):\n raise StorageError(\n f\"{basefolder} is not a valid directory\",\n code=StorageError.INVALID_DIRECTORY,\n )", " self._really_universal = really_universal", " import threading", " self._metadata_lock_mutex = threading.RLock()\n self._metadata_locks = {}\n self._persisted_metadata_lock_mutex = threading.RLock()\n self._persisted_metadata_locks = {}", " self._metadata_cache = pylru.lrucache(100)\n self._filelist_cache = {}\n self._filelist_cache_mutex = threading.RLock()", " self._old_metadata = None\n self._initialize_metadata()", " def _initialize_metadata(self):\n self._logger.info(f\"Initializing the file metadata for {self.basefolder}...\")", " old_metadata_path = os.path.join(self.basefolder, \"metadata.yaml\")\n backup_path = os.path.join(self.basefolder, \"metadata.yaml.backup\")", " if os.path.exists(old_metadata_path):\n # load the old metadata file\n try:\n self._old_metadata = yaml.load_from_file(path=old_metadata_path)\n except Exception:\n self._logger.exception(\"Error while loading old metadata file\")", " # make sure the metadata is initialized as far as possible\n self._list_folder(self.basefolder)", " # rename the old metadata file\n self._old_metadata = None\n try:\n import shutil", " shutil.move(old_metadata_path, backup_path)\n except Exception:\n self._logger.exception(\"Could not rename old metadata.yaml file\")", " else:\n # make sure the metadata is initialized as far as possible\n self._list_folder(self.basefolder)", " self._logger.info(\n f\"... file metadata for {self.basefolder} initialized successfully.\"\n )", " @property\n def analysis_backlog(self):\n return self.analysis_backlog_for_path()", " def analysis_backlog_for_path(self, path=None):\n if path:\n path = self.sanitize_path(path)", " yield from self._analysis_backlog_generator(path)", " def _analysis_backlog_generator(self, path=None):\n if path is None:\n path = self.basefolder", " metadata = self._get_metadata(path)\n if not metadata:\n metadata = {}\n for entry in scandir(path):\n if is_hidden_path(entry.name):\n continue", " if entry.is_file() and octoprint.filemanager.valid_file_type(entry.name):\n if (\n entry.name not in metadata\n or not isinstance(metadata[entry.name], dict)\n or \"analysis\" not in metadata[entry.name]\n ):\n printer_profile_rels = self.get_link(entry.path, \"printerprofile\")\n if printer_profile_rels:\n printer_profile_id = printer_profile_rels[0][\"id\"]\n else:\n printer_profile_id = None", " yield entry.name, entry.path, printer_profile_id\n elif os.path.isdir(entry.path):\n for sub_entry in self._analysis_backlog_generator(entry.path):\n yield self.join_path(entry.name, sub_entry[0]), sub_entry[\n 1\n ], sub_entry[2]", " def last_modified(self, path=None, recursive=False):\n if path is None:\n path = self.basefolder\n else:\n path = os.path.join(self.basefolder, path)", " def last_modified_for_path(p):\n metadata = os.path.join(p, \".metadata.json\")\n if os.path.exists(metadata):\n return max(os.stat(p).st_mtime, os.stat(metadata).st_mtime)\n else:\n return os.stat(p).st_mtime", " if recursive:\n return max(last_modified_for_path(root) for root, _, _ in walk(path))\n else:\n return last_modified_for_path(path)", " def file_in_path(self, path, filepath):\n filepath = self.sanitize_path(filepath)\n path = self.sanitize_path(path)", " return filepath == path or filepath.startswith(path + os.sep)", " def file_exists(self, path):\n path, name = self.sanitize(path)\n file_path = os.path.join(path, name)\n return os.path.exists(file_path) and os.path.isfile(file_path)", " def folder_exists(self, path):\n path, name = self.sanitize(path)\n folder_path = os.path.join(path, name)\n return os.path.exists(folder_path) and os.path.isdir(folder_path)", " def list_files(\n self, path=None, filter=None, recursive=True, level=0, force_refresh=False\n ):\n if path:\n path = self.sanitize_path(to_unicode(path))\n base = self.path_in_storage(path)\n if base:\n base += \"/\"\n else:\n path = self.basefolder\n base = \"\"", " def strip_children(nodes):\n result = {}\n for key, node in nodes.items():\n if node[\"type\"] == \"folder\":\n node = copy.copy(node)\n node[\"children\"] = {}\n result[key] = node\n return result", " def strip_grandchildren(nodes):\n result = {}\n for key, node in nodes.items():\n if node[\"type\"] == \"folder\":\n node = copy.copy(node)\n node[\"children\"] = strip_children(node[\"children\"])\n result[key] = node\n return result", " def apply_filter(nodes, filter_func):\n result = {}\n for key, node in nodes.items():\n if filter_func(node) or node[\"type\"] == \"folder\":\n if node[\"type\"] == \"folder\":\n node = copy.copy(node)\n node[\"children\"] = apply_filter(\n node.get(\"children\", {}), filter_func\n )\n result[key] = node\n return result", " result = self._list_folder(path, base=base, force_refresh=force_refresh)\n if not recursive:\n if level > 0:\n result = strip_grandchildren(result)\n else:\n result = strip_children(result)\n if callable(filter):\n result = apply_filter(result, filter)\n return result", " def add_folder(self, path, ignore_existing=True, display=None):\n display_path, display_name = self.canonicalize(path)\n path = self.sanitize_path(display_path)\n name = self.sanitize_name(display_name)", " if display is not None:\n display_name = display", " folder_path = os.path.join(path, name)\n if os.path.exists(folder_path):\n if not ignore_existing:\n raise StorageError(\n f\"{name} does already exist in {path}\",\n code=StorageError.ALREADY_EXISTS,\n )\n else:\n os.mkdir(folder_path)", " if display_name != name:\n metadata = self._get_metadata_entry(path, name, default={})\n metadata[\"display\"] = display_name\n self._update_metadata_entry(path, name, metadata)", " return self.path_in_storage((path, name))", " def remove_folder(self, path, recursive=True):\n path, name = self.sanitize(path)", " folder_path = os.path.join(path, name)\n if not os.path.exists(folder_path):\n return", " empty = True\n for entry in scandir(folder_path):\n if entry.name == \".metadata.json\" or entry.name == \".metadata.yaml\":\n continue\n empty = False\n break", " if not empty and not recursive:\n raise StorageError(\n f\"{name} in {path} is not empty\",\n code=StorageError.NOT_EMPTY,\n )", " import shutil", " shutil.rmtree(folder_path)", " self._remove_metadata_entry(path, name)", " def _get_source_destination_data(self, source, destination, must_not_equal=False):\n \"\"\"Prepares data dicts about source and destination for copy/move.\"\"\"\n source_path, source_name = self.sanitize(source)", " destination_canon_path, destination_canon_name = self.canonicalize(destination)\n destination_path = self.sanitize_path(destination_canon_path)\n destination_name = self.sanitize_name(destination_canon_name)", " source_fullpath = os.path.join(source_path, source_name)\n destination_fullpath = os.path.join(destination_path, destination_name)", " if not os.path.exists(source_fullpath):\n raise StorageError(\n f\"{source_name} in {source_path} does not exist\",\n code=StorageError.INVALID_SOURCE,\n )", " if not os.path.isdir(destination_path):\n raise StorageError(\n \"Destination path {} does not exist or is not a folder\".format(\n destination_path\n ),\n code=StorageError.INVALID_DESTINATION,\n )\n if (\n os.path.exists(destination_fullpath)\n and source_fullpath != destination_fullpath\n ):\n raise StorageError(\n f\"{destination_name} does already exist in {destination_path}\",\n code=StorageError.INVALID_DESTINATION,\n )", " source_meta = self._get_metadata_entry(source_path, source_name)\n if source_meta:\n source_display = source_meta.get(\"display\", source_name)\n else:\n source_display = source_name", " if (\n must_not_equal or source_display == destination_canon_name\n ) and source_fullpath == destination_fullpath:\n raise StorageError(\n \"Source {} and destination {} are the same folder\".format(\n source_path, destination_path\n ),\n code=StorageError.SOURCE_EQUALS_DESTINATION,\n )", " source_data = {\n \"path\": source_path,\n \"name\": source_name,\n \"display\": source_display,\n \"fullpath\": source_fullpath,\n }\n destination_data = {\n \"path\": destination_path,\n \"name\": destination_name,\n \"display\": destination_canon_name,\n \"fullpath\": destination_fullpath,\n }\n return source_data, destination_data", " def _set_display_metadata(self, destination_data, source_data=None):\n if (\n source_data\n and destination_data[\"name\"] == source_data[\"name\"]\n and source_data[\"name\"] != source_data[\"display\"]\n ):\n display = source_data[\"display\"]\n elif destination_data[\"name\"] != destination_data[\"display\"]:\n display = destination_data[\"display\"]\n else:\n display = None", " destination_meta = self._get_metadata_entry(\n destination_data[\"path\"], destination_data[\"name\"], default={}\n )\n if display:\n destination_meta[\"display\"] = display\n self._update_metadata_entry(\n destination_data[\"path\"], destination_data[\"name\"], destination_meta\n )\n elif \"display\" in destination_meta:\n del destination_meta[\"display\"]\n self._update_metadata_entry(\n destination_data[\"path\"], destination_data[\"name\"], destination_meta\n )", " def copy_folder(self, source, destination):\n source_data, destination_data = self._get_source_destination_data(\n source, destination, must_not_equal=True\n )", " try:\n shutil.copytree(source_data[\"fullpath\"], destination_data[\"fullpath\"])\n except Exception as e:\n raise StorageError(\n \"Could not copy %s in %s to %s in %s\"\n % (\n source_data[\"name\"],\n source_data[\"path\"],\n destination_data[\"name\"],\n destination_data[\"path\"],\n ),\n cause=e,\n )", " self._set_display_metadata(destination_data, source_data=source_data)", " return self.path_in_storage(destination_data[\"fullpath\"])", " def move_folder(self, source, destination):\n source_data, destination_data = self._get_source_destination_data(\n source, destination\n )", " # only a display rename? Update that and bail early\n if source_data[\"fullpath\"] == destination_data[\"fullpath\"]:\n self._set_display_metadata(destination_data)\n return self.path_in_storage(destination_data[\"fullpath\"])", " try:\n shutil.move(source_data[\"fullpath\"], destination_data[\"fullpath\"])\n except Exception as e:\n raise StorageError(\n \"Could not move %s in %s to %s in %s\"\n % (\n source_data[\"name\"],\n source_data[\"path\"],\n destination_data[\"name\"],\n destination_data[\"path\"],\n ),\n cause=e,\n )", " self._set_display_metadata(destination_data, source_data=source_data)\n self._remove_metadata_entry(source_data[\"path\"], source_data[\"name\"])\n self._delete_metadata(source_data[\"fullpath\"])", " return self.path_in_storage(destination_data[\"fullpath\"])", " def add_file(\n self,\n path,\n file_object,\n printer_profile=None,\n links=None,\n allow_overwrite=False,\n display=None,\n ):\n display_path, display_name = self.canonicalize(path)\n path = self.sanitize_path(display_path)\n name = self.sanitize_name(display_name)", " if display:\n display_name = display", " if not octoprint.filemanager.valid_file_type(name):\n raise StorageError(\n f\"{name} is an unrecognized file type\",\n code=StorageError.INVALID_FILE,\n )", " file_path = os.path.join(path, name)\n if os.path.exists(file_path) and not os.path.isfile(file_path):\n raise StorageError(\n f\"{name} does already exist in {path} and is not a file\",\n code=StorageError.ALREADY_EXISTS,\n )\n if os.path.exists(file_path) and not allow_overwrite:\n raise StorageError(\n f\"{name} does already exist in {path} and overwriting is prohibited\",\n code=StorageError.ALREADY_EXISTS,\n )", " # make sure folders exist\n if not os.path.exists(path):\n # TODO persist display names of path segments!\n os.makedirs(path)", " # save the file\n file_object.save(file_path)", " # save the file's hash to the metadata of the folder\n file_hash = self._create_hash(file_path)\n metadata = self._get_metadata_entry(path, name, default={})\n metadata_dirty = False\n if \"hash\" not in metadata or metadata[\"hash\"] != file_hash:\n # hash changed -> throw away old metadata\n metadata = {\"hash\": file_hash}\n metadata_dirty = True", " if \"display\" not in metadata and display_name != name:\n # display name is not the same as file name -> store in metadata\n metadata[\"display\"] = display_name\n metadata_dirty = True", " if metadata_dirty:\n self._update_metadata_entry(path, name, metadata)", " # process any links that were also provided for adding to the file\n if not links:\n links = []", " if printer_profile is not None:\n links.append(\n (\n \"printerprofile\",\n {\"id\": printer_profile[\"id\"], \"name\": printer_profile[\"name\"]},\n )\n )", " self._add_links(name, path, links)", " # touch the file to set last access and modification time to now\n os.utime(file_path, None)", " return self.path_in_storage((path, name))", " def remove_file(self, path):\n path, name = self.sanitize(path)", " file_path = os.path.join(path, name)\n if not os.path.exists(file_path):\n return\n if not os.path.isfile(file_path):\n raise StorageError(\n f\"{name} in {path} is not a file\",\n code=StorageError.INVALID_FILE,\n )", " try:\n os.remove(file_path)\n except Exception as e:\n raise StorageError(f\"Could not delete {name} in {path}\", cause=e)", " self._remove_metadata_entry(path, name)", " def copy_file(self, source, destination):\n source_data, destination_data = self._get_source_destination_data(\n source, destination, must_not_equal=True\n )\n", "", " try:\n shutil.copy2(source_data[\"fullpath\"], destination_data[\"fullpath\"])\n except Exception as e:\n raise StorageError(\n \"Could not copy %s in %s to %s in %s\"\n % (\n source_data[\"name\"],\n source_data[\"path\"],\n destination_data[\"name\"],\n destination_data[\"path\"],\n ),\n cause=e,\n )", " self._copy_metadata_entry(\n source_data[\"path\"],\n source_data[\"name\"],\n destination_data[\"path\"],\n destination_data[\"name\"],\n )\n self._set_display_metadata(destination_data, source_data=source_data)", " return self.path_in_storage(destination_data[\"fullpath\"])", " def move_file(self, source, destination, allow_overwrite=False):\n source_data, destination_data = self._get_source_destination_data(\n source, destination\n )", "", "\n # only a display rename? Update that and bail early\n if source_data[\"fullpath\"] == destination_data[\"fullpath\"]:\n self._set_display_metadata(destination_data)\n return self.path_in_storage(destination_data[\"fullpath\"])", " try:\n shutil.move(source_data[\"fullpath\"], destination_data[\"fullpath\"])\n except Exception as e:\n raise StorageError(\n \"Could not move %s in %s to %s in %s\"\n % (\n source_data[\"name\"],\n source_data[\"path\"],\n destination_data[\"name\"],\n destination_data[\"path\"],\n ),\n cause=e,\n )", " self._copy_metadata_entry(\n source_data[\"path\"],\n source_data[\"name\"],\n destination_data[\"path\"],\n destination_data[\"name\"],\n delete_source=True,\n )\n self._set_display_metadata(destination_data, source_data=source_data)", " return self.path_in_storage(destination_data[\"fullpath\"])", " def has_analysis(self, path):\n metadata = self.get_metadata(path)\n return \"analysis\" in metadata", " def get_metadata(self, path):\n path, name = self.sanitize(path)\n return self._get_metadata_entry(path, name)", " def get_link(self, path, rel):\n path, name = self.sanitize(path)\n return self._get_links(name, path, rel)", " def add_link(self, path, rel, data):\n path, name = self.sanitize(path)\n self._add_links(name, path, [(rel, data)])", " def remove_link(self, path, rel, data):\n path, name = self.sanitize(path)\n self._remove_links(name, path, [(rel, data)])", " def add_history(self, path, data):\n path, name = self.sanitize(path)\n self._add_history(name, path, data)", " def update_history(self, path, index, data):\n path, name = self.sanitize(path)\n self._update_history(name, path, index, data)", " def remove_history(self, path, index):\n path, name = self.sanitize(path)\n self._delete_history(name, path, index)", " def get_additional_metadata(self, path, key):\n path, name = self.sanitize(path)\n metadata = self._get_metadata(path)", " if name not in metadata:\n return", " return metadata[name].get(key)", " def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):\n path, name = self.sanitize(path)\n metadata = self._get_metadata(path)\n metadata_dirty = False", " if name not in metadata:\n return", " metadata = self._copied_metadata(metadata, name)", " if key not in metadata[name] or overwrite:\n metadata[name][key] = data\n metadata_dirty = True\n elif (\n key in metadata[name]\n and isinstance(metadata[name][key], dict)\n and isinstance(data, dict)\n and merge\n ):\n import octoprint.util", " metadata[name][key] = octoprint.util.dict_merge(\n metadata[name][key], data, in_place=True\n )\n metadata_dirty = True", " if metadata_dirty:\n self._save_metadata(path, metadata)", " def remove_additional_metadata(self, path, key):\n path, name = self.sanitize(path)\n metadata = self._get_metadata(path)", " if name not in metadata:\n return", " if key not in metadata[name]:\n return", " metadata = self._copied_metadata(metadata, name)\n del metadata[name][key]\n self._save_metadata(path, metadata)", " def split_path(self, path):\n path = to_unicode(path)\n split = path.split(\"/\")\n if len(split) == 1:\n return \"\", split[0]\n else:\n return self.join_path(*split[:-1]), split[-1]", " def join_path(self, *path):\n return \"/\".join(map(to_unicode, path))", " def sanitize(self, path):\n \"\"\"\n Returns a ``(path, name)`` tuple derived from the provided ``path``.", " ``path`` may be:\n * a storage path\n * an absolute file system path\n * a tuple or list containing all individual path elements\n * a string representation of the path\n * with or without a file name", " Note that for a ``path`` without a trailing slash the last part will be considered a file name and\n hence be returned at second position. If you only need to convert a folder path, be sure to\n include a trailing slash for a string ``path`` or an empty last element for a list ``path``.\n \"\"\"", " path, name = self.canonicalize(path)\n name = self.sanitize_name(name)\n path = self.sanitize_path(path)\n return path, name", " def canonicalize(self, path):\n name = None\n if isinstance(path, str):\n path = to_unicode(path)\n if path.startswith(self.basefolder):\n path = path[len(self.basefolder) :]\n path = path.replace(os.path.sep, \"/\")\n path = path.split(\"/\")\n if isinstance(path, (list, tuple)):\n if len(path) == 1:\n name = to_unicode(path[0])\n path = \"\"\n else:\n name = to_unicode(path[-1])\n path = self.join_path(*map(to_unicode, path[:-1]))\n if not path:\n path = \"\"", " return path, name", " def sanitize_name(self, name):\n \"\"\"\n Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\\\\``. Otherwise\n sanitizes the given ``name`` using ``octoprint.files.sanitize_filename``. Also\n strips any leading ``.``.\n \"\"\"\n return sanitize_filename(name, really_universal=self._really_universal)", " def sanitize_path(self, path):\n \"\"\"\n Ensures that the on disk representation of ``path`` is located under the configured basefolder. Resolves all\n relative path elements (e.g. ``..``) and sanitizes folder names using :func:`sanitize_name`. Final path is the\n absolute path including leading ``basefolder`` path.\n \"\"\"\n path = to_unicode(path)", " if len(path):\n if path[0] == \"/\":\n path = path[1:]\n elif path[0] == \".\" and path[1] == \"/\":\n path = path[2:]", " path_elements = path.split(\"/\")\n joined_path = self.basefolder\n for path_element in path_elements:\n if path_element == \"..\" or path_element == \".\":\n joined_path = os.path.join(joined_path, path_element)\n else:\n joined_path = os.path.join(joined_path, self.sanitize_name(path_element))\n path = os.path.realpath(joined_path)\n if not path.startswith(self.basefolder):\n raise ValueError(f\"path not contained in base folder: {path}\")\n return path", " def _sanitize_entry(self, entry, path, entry_path):\n entry = to_unicode(entry)\n sanitized = self.sanitize_name(entry)\n if sanitized != entry:\n # entry is not sanitized yet, let's take care of that\n sanitized_path = os.path.join(path, sanitized)\n sanitized_name, sanitized_ext = os.path.splitext(sanitized)", " counter = 1\n while os.path.exists(sanitized_path):\n counter += 1\n sanitized = self.sanitize_name(\n f\"{sanitized_name}_({counter}){sanitized_ext}\"\n )\n sanitized_path = os.path.join(path, sanitized)", " try:\n shutil.move(entry_path, sanitized_path)", " self._logger.info(f'Sanitized \"{entry_path}\" to \"{sanitized_path}\"')\n return sanitized, sanitized_path\n except Exception:\n self._logger.exception(\n 'Error while trying to rename \"{}\" to \"{}\", ignoring file'.format(\n entry_path, sanitized_path\n )\n )\n raise", " return entry, entry_path", " def path_in_storage(self, path):\n if isinstance(path, (tuple, list)):\n path = self.join_path(*path)\n if isinstance(path, str):\n path = to_unicode(path)\n if path.startswith(self.basefolder):\n path = path[len(self.basefolder) :]\n path = path.replace(os.path.sep, \"/\")\n if path.startswith(\"/\"):\n path = path[1:]", " return path", " def path_on_disk(self, path):\n path, name = self.sanitize(path)\n return os.path.join(path, name)", " ##~~ internals", " def _add_history(self, name, path, data):\n metadata = self._copied_metadata(self._get_metadata(path), name)", " if \"hash\" not in metadata[name]:\n metadata[name][\"hash\"] = self._create_hash(os.path.join(path, name))", " if \"history\" not in metadata[name]:\n metadata[name][\"history\"] = []", " metadata[name][\"history\"].append(data)\n self._calculate_stats_from_history(name, path, metadata=metadata, save=False)\n self._save_metadata(path, metadata)", " def _update_history(self, name, path, index, data):\n metadata = self._get_metadata(path)", " if name not in metadata or \"history\" not in metadata[name]:\n return", " metadata = self._copied_metadata(metadata, name)", " try:\n metadata[name][\"history\"][index].update(data)\n self._calculate_stats_from_history(name, path, metadata=metadata, save=False)\n self._save_metadata(path, metadata)\n except IndexError:\n pass", " def _delete_history(self, name, path, index):\n metadata = self._get_metadata(path)", " if name not in metadata or \"history\" not in metadata[name]:\n return", " metadata = self._copied_metadata(metadata, name)", " try:\n del metadata[name][\"history\"][index]\n self._calculate_stats_from_history(name, path, metadata=metadata, save=False)\n self._save_metadata(path, metadata)\n except IndexError:\n pass", " def _calculate_stats_from_history(self, name, path, metadata=None, save=True):\n if metadata is None:\n metadata = self._copied_metadata(self._get_metadata(path), name)", " if \"history\" not in metadata[name]:\n return", " # collect data from history\n former_print_times = {}\n last_print = {}", " for history_entry in metadata[name][\"history\"]:\n if (\n \"printTime\" not in history_entry\n or \"success\" not in history_entry\n or not history_entry[\"success\"]\n or \"printerProfile\" not in history_entry\n ):\n continue", " printer_profile = history_entry[\"printerProfile\"]\n if not printer_profile:\n continue", " print_time = history_entry[\"printTime\"]\n try:\n print_time = float(print_time)\n except Exception:\n self._logger.warning(\n \"Invalid print time value found in print history for {} in {}/.metadata.json: {!r}\".format(\n name, path, print_time\n )\n )\n continue", " if printer_profile not in former_print_times:\n former_print_times[printer_profile] = []\n former_print_times[printer_profile].append(print_time)", " if (\n printer_profile not in last_print\n or last_print[printer_profile] is None\n or (\n \"timestamp\" in history_entry\n and history_entry[\"timestamp\"]\n > last_print[printer_profile][\"timestamp\"]\n )\n ):\n last_print[printer_profile] = history_entry", " # calculate stats\n statistics = {\"averagePrintTime\": {}, \"lastPrintTime\": {}}", " for printer_profile in former_print_times:\n if not former_print_times[printer_profile]:\n continue\n statistics[\"averagePrintTime\"][printer_profile] = sum(\n former_print_times[printer_profile]\n ) / len(former_print_times[printer_profile])", " for printer_profile in last_print:\n if not last_print[printer_profile]:\n continue\n statistics[\"lastPrintTime\"][printer_profile] = last_print[printer_profile][\n \"printTime\"\n ]", " metadata[name][\"statistics\"] = statistics", " if save:\n self._save_metadata(path, metadata)", " def _get_links(self, name, path, searched_rel):\n metadata = self._get_metadata(path)\n result = []", " if name not in metadata:\n return result", " if \"links\" not in metadata[name]:\n return result", " for data in metadata[name][\"links\"]:\n if \"rel\" not in data or not data[\"rel\"] == searched_rel:\n continue\n result.append(data)\n return result", " def _add_links(self, name, path, links):\n file_type = octoprint.filemanager.get_file_type(name)\n if file_type:\n file_type = file_type[0]", " metadata = self._copied_metadata(self._get_metadata(path), name)\n metadata_dirty = False", " if \"hash\" not in metadata[name]:\n metadata[name][\"hash\"] = self._create_hash(os.path.join(path, name))", " if \"links\" not in metadata[name]:\n metadata[name][\"links\"] = []", " for rel, data in links:\n if (rel == \"model\" or rel == \"machinecode\") and \"name\" in data:\n if file_type == \"model\" and rel == \"model\":\n # adding a model link to a model doesn't make sense\n return\n elif file_type == \"machinecode\" and rel == \"machinecode\":\n # adding a machinecode link to a machinecode doesn't make sense\n return", " ref_path = os.path.join(path, data[\"name\"])\n if not os.path.exists(ref_path):\n # file doesn't exist, we won't create the link\n continue", " # fetch hash of target file\n if data[\"name\"] in metadata and \"hash\" in metadata[data[\"name\"]]:\n hash = metadata[data[\"name\"]][\"hash\"]\n else:\n hash = self._create_hash(ref_path)\n if data[\"name\"] not in metadata:\n metadata[data[\"name\"]] = {\"hash\": hash, \"links\": []}\n else:\n metadata[data[\"name\"]][\"hash\"] = hash", " if \"hash\" in data and not data[\"hash\"] == hash:\n # file doesn't have the correct hash, we won't create the link\n continue", " if \"links\" not in metadata[data[\"name\"]]:\n metadata[data[\"name\"]][\"links\"] = []", " # add reverse link to link target file\n metadata[data[\"name\"]][\"links\"].append(\n {\n \"rel\": \"machinecode\" if rel == \"model\" else \"model\",\n \"name\": name,\n \"hash\": metadata[name][\"hash\"],\n }\n )\n metadata_dirty = True", " link_dict = {\"rel\": rel, \"name\": data[\"name\"], \"hash\": hash}", " elif rel == \"web\" and \"href\" in data:\n link_dict = {\"rel\": rel, \"href\": data[\"href\"]}\n if \"retrieved\" in data:\n link_dict[\"retrieved\"] = data[\"retrieved\"]", " else:\n continue", " if link_dict:\n metadata[name][\"links\"].append(link_dict)\n metadata_dirty = True", " if metadata_dirty:\n self._save_metadata(path, metadata)", " def _remove_links(self, name, path, links):\n metadata = self._copied_metadata(self._get_metadata(path), name)\n metadata_dirty = False", " hash = metadata[name].get(\"hash\", self._create_hash(os.path.join(path, name)))", " for rel, data in links:\n if (rel == \"model\" or rel == \"machinecode\") and \"name\" in data:\n if data[\"name\"] in metadata and \"links\" in metadata[data[\"name\"]]:\n ref_rel = \"model\" if rel == \"machinecode\" else \"machinecode\"\n for link in metadata[data[\"name\"]][\"links\"]:\n if (\n link[\"rel\"] == ref_rel\n and \"name\" in link\n and link[\"name\"] == name\n and \"hash\" in link\n and link[\"hash\"] == hash\n ):\n metadata[data[\"name\"]] = copy.deepcopy(metadata[data[\"name\"]])\n metadata[data[\"name\"]][\"links\"].remove(link)\n metadata_dirty = True", " if \"links\" in metadata[name]:\n for link in metadata[name][\"links\"]:\n if not link[\"rel\"] == rel:\n continue", " matches = True\n for k, v in data.items():\n if k not in link or not link[k] == v:\n matches = False\n break", " if not matches:\n continue", " metadata[name][\"links\"].remove(link)\n metadata_dirty = True", " if metadata_dirty:\n self._save_metadata(path, metadata)", " @time_this(\n logtarget=__name__ + \".timings\",\n message=\"{func}({func_args},{func_kwargs}) took {timing:.2f}ms\",\n incl_func_args=True,\n log_enter=True,\n )\n def _list_folder(self, path, base=\"\", force_refresh=False, **kwargs):\n def get_size(nodes):\n total_size = 0\n for node in nodes.values():\n if \"size\" in node:\n total_size += node[\"size\"]\n return total_size", " def enrich_folders(nodes):\n nodes = copy.copy(nodes)\n for key, value in nodes.items():\n if value[\"type\"] == \"folder\":\n value = copy.copy(value)\n value[\"children\"] = self._list_folder(\n os.path.join(path, key),\n base=value[\"path\"] + \"/\",\n force_refresh=force_refresh,\n )\n value[\"size\"] = get_size(value[\"children\"])\n nodes[key] = value\n return nodes", " metadata_dirty = False\n try:\n with self._filelist_cache_mutex:\n cache = self._filelist_cache.get(path)\n lm = self.last_modified(path, recursive=True)\n if not force_refresh and cache and cache[0] >= lm:\n return enrich_folders(cache[1])", " metadata = self._get_metadata(path)\n if not metadata:\n metadata = {}", " result = {}", " for entry in scandir(path):\n if is_hidden_path(entry.name):\n # no hidden files and folders\n continue", " try:\n entry_name = entry_display = entry.name\n entry_path = entry.path\n entry_is_file = entry.is_file()\n entry_is_dir = entry.is_dir()\n entry_stat = entry.stat()\n except Exception:\n # error while trying to fetch file metadata, that might be thanks to file already having\n # been moved or deleted - ignore it and continue\n continue", " try:\n new_entry_name, new_entry_path = self._sanitize_entry(\n entry_name, path, entry_path\n )\n if entry_name != new_entry_name or entry_path != new_entry_path:\n entry_display = to_unicode(entry_name)\n entry_name = new_entry_name\n entry_path = new_entry_path\n entry_stat = os.stat(entry_path)\n except Exception:\n # error while trying to rename the file, we'll continue here and ignore it\n continue", " path_in_location = entry_name if not base else base + entry_name", " try:\n # file handling\n if entry_is_file:\n type_path = octoprint.filemanager.get_file_type(entry_name)\n if not type_path:\n # only supported extensions\n continue\n else:\n file_type = type_path[0]", " if entry_name in metadata and isinstance(\n metadata[entry_name], dict\n ):\n entry_metadata = metadata[entry_name]\n if (\n \"display\" not in entry_metadata\n and entry_display != entry_name\n ):\n if not metadata_dirty:\n metadata = self._copied_metadata(\n metadata, entry_name\n )\n metadata[entry_name][\"display\"] = entry_display\n entry_metadata[\"display\"] = entry_display\n metadata_dirty = True\n else:\n if not metadata_dirty:\n metadata = self._copied_metadata(metadata, entry_name)\n entry_metadata = self._add_basic_metadata(\n path,\n entry_name,\n display_name=entry_display,\n save=False,\n metadata=metadata,\n )\n metadata_dirty = True", " extended_entry_data = {}\n extended_entry_data.update(entry_metadata)\n extended_entry_data[\"name\"] = entry_name\n extended_entry_data[\"display\"] = entry_metadata.get(\n \"display\", entry_name\n )\n extended_entry_data[\"path\"] = path_in_location\n extended_entry_data[\"type\"] = file_type\n extended_entry_data[\"typePath\"] = type_path\n stat = entry_stat\n if stat:\n extended_entry_data[\"size\"] = stat.st_size\n extended_entry_data[\"date\"] = int(stat.st_mtime)", " result[entry_name] = extended_entry_data", " # folder recursion\n elif entry_is_dir:\n if entry_name in metadata and isinstance(\n metadata[entry_name], dict\n ):\n entry_metadata = metadata[entry_name]\n if (\n \"display\" not in entry_metadata\n and entry_display != entry_name\n ):\n if not metadata_dirty:\n metadata = self._copied_metadata(\n metadata, entry_name\n )\n metadata[entry_name][\"display\"] = entry_display\n entry_metadata[\"display\"] = entry_display\n metadata_dirty = True\n elif entry_name != entry_display:\n if not metadata_dirty:\n metadata = self._copied_metadata(metadata, entry_name)\n entry_metadata = self._add_basic_metadata(\n path,\n entry_name,\n display_name=entry_display,\n save=False,\n metadata=metadata,\n )\n metadata_dirty = True\n else:\n entry_metadata = {}", " entry_data = {\n \"name\": entry_name,\n \"display\": entry_metadata.get(\"display\", entry_name),\n \"path\": path_in_location,\n \"type\": \"folder\",\n \"typePath\": [\"folder\"],\n }", " result[entry_name] = entry_data\n except Exception:\n # So something went wrong somewhere while processing this file entry - log that and continue\n self._logger.exception(\n f\"Error while processing entry {entry_path}\"\n )\n continue", " self._filelist_cache[path] = (\n lm,\n result,\n )\n return enrich_folders(result)\n finally:\n # save metadata\n if metadata_dirty:\n self._save_metadata(path, metadata)", " def _add_basic_metadata(\n self,\n path,\n entry,\n display_name=None,\n additional_metadata=None,\n save=True,\n metadata=None,\n ):\n if additional_metadata is None:\n additional_metadata = {}", " if metadata is None:\n metadata = self._get_metadata(path)", " entry_path = os.path.join(path, entry)", " if os.path.isfile(entry_path):\n entry_data = {\n \"hash\": self._create_hash(os.path.join(path, entry)),\n \"links\": [],\n \"notes\": [],\n }\n if (\n path == self.basefolder\n and self._old_metadata is not None\n and entry in self._old_metadata\n and \"gcodeAnalysis\" in self._old_metadata[entry]\n ):\n # if there is still old metadata available and that contains an analysis for this file, use it!\n entry_data[\"analysis\"] = self._old_metadata[entry][\"gcodeAnalysis\"]", " elif os.path.isdir(entry_path):\n entry_data = {}", " else:\n return", " if display_name is not None and not display_name == entry:\n entry_data[\"display\"] = display_name", " entry_data.update(additional_metadata)", " metadata = copy.copy(metadata)\n metadata[entry] = entry_data", " if save:\n self._save_metadata(path, metadata)", " return entry_data", " def _create_hash(self, path):\n import hashlib", " blocksize = 65536\n hash = hashlib.sha1()\n with open(path, \"rb\") as f:\n buffer = f.read(blocksize)\n while len(buffer) > 0:\n hash.update(buffer)\n buffer = f.read(blocksize)", " return hash.hexdigest()", " def _get_metadata_entry(self, path, name, default=None):\n with self._get_metadata_lock(path):\n metadata = self._get_metadata(path)\n return metadata.get(name, default)", " def _remove_metadata_entry(self, path, name):\n with self._get_metadata_lock(path):\n metadata = self._get_metadata(path)\n if name not in metadata:\n return", " metadata = copy.copy(metadata)", " if \"hash\" in metadata[name]:\n hash = metadata[name][\"hash\"]\n for m in metadata.values():\n if \"links\" not in m:\n continue\n links_hash = (\n lambda link: \"hash\" in link\n and link[\"hash\"] == hash\n and \"rel\" in link\n and (link[\"rel\"] == \"model\" or link[\"rel\"] == \"machinecode\")\n )\n m[\"links\"] = [link for link in m[\"links\"] if not links_hash(link)]", " del metadata[name]\n self._save_metadata(path, metadata)", " def _update_metadata_entry(self, path, name, data):\n with self._get_metadata_lock(path):\n metadata = copy.copy(self._get_metadata(path))\n metadata[name] = data\n self._save_metadata(path, metadata)", " def _copy_metadata_entry(\n self,\n source_path,\n source_name,\n destination_path,\n destination_name,\n delete_source=False,\n updates=None,\n ):\n with self._get_metadata_lock(source_path):\n source_data = self._get_metadata_entry(source_path, source_name, default={})\n if not source_data:\n return", " if delete_source:\n self._remove_metadata_entry(source_path, source_name)", " if updates is not None:\n source_data.update(updates)", " with self._get_metadata_lock(destination_path):\n self._update_metadata_entry(destination_path, destination_name, source_data)", " def _get_metadata(self, path, force=False):\n import json", " if not force:\n metadata = self._metadata_cache.get(path)\n if metadata:\n return metadata", " self._migrate_metadata(path)", " metadata_path = os.path.join(path, \".metadata.json\")", " metadata = None\n with self._get_persisted_metadata_lock(path):\n if os.path.exists(metadata_path):\n with open(metadata_path, encoding=\"utf-8\") as f:\n try:\n metadata = json.load(f)\n except Exception:\n self._logger.exception(\n f\"Error while reading .metadata.json from {path}\"\n )", " def valid_json(value):\n try:\n json.dumps(value, allow_nan=False)\n return True\n except Exception:\n return False", " if isinstance(metadata, dict):\n old_size = len(metadata)\n metadata = {k: v for k, v in metadata.items() if valid_json(v)}\n metadata = {\n k: v for k, v in metadata.items() if os.path.exists(os.path.join(path, k))\n }\n new_size = len(metadata)\n if new_size != old_size:\n self._logger.info(\n \"Deleted {} stale or invalid entries from metadata for path {}\".format(\n old_size - new_size, path\n )\n )\n self._save_metadata(path, metadata)\n else:\n with self._get_metadata_lock(path):\n self._metadata_cache[path] = metadata\n return metadata\n else:\n return {}", " def _save_metadata(self, path, metadata):\n import json", " with self._get_metadata_lock(path):\n self._metadata_cache[path] = metadata", " with self._get_persisted_metadata_lock(path):\n metadata_path = os.path.join(path, \".metadata.json\")\n try:\n with atomic_write(metadata_path, mode=\"wb\") as f:\n f.write(\n to_bytes(json.dumps(metadata, indent=2, separators=(\",\", \": \")))\n )\n except Exception:\n self._logger.exception(f\"Error while writing .metadata.json to {path}\")", " def _delete_metadata(self, path):\n with self._get_metadata_lock(path):\n if path in self._metadata_cache:\n del self._metadata_cache[path]", " with self._get_persisted_metadata_lock(path):\n metadata_files = (\".metadata.json\", \".metadata.yaml\")\n for metadata_file in metadata_files:\n metadata_path = os.path.join(path, metadata_file)\n if os.path.exists(metadata_path):\n try:\n os.remove(metadata_path)\n except Exception:\n self._logger.exception(\n f\"Error while deleting {metadata_file} from {path}\"\n )", " @staticmethod\n def _copied_metadata(metadata, name):\n metadata = copy.copy(metadata)\n metadata[name] = copy.deepcopy(metadata.get(name, {}))\n return metadata", " def _migrate_metadata(self, path):\n # we switched to json in 1.3.9 - if we still have yaml here, migrate it now\n import json", " with self._get_persisted_metadata_lock(path):\n metadata_path_yaml = os.path.join(path, \".metadata.yaml\")\n metadata_path_json = os.path.join(path, \".metadata.json\")", " if not os.path.exists(metadata_path_yaml):\n # nothing to migrate\n return", " if os.path.exists(metadata_path_json):\n # already migrated\n try:\n os.remove(metadata_path_yaml)\n except Exception:\n self._logger.exception(\n f\"Error while removing .metadata.yaml from {path}\"\n )\n return", " try:\n metadata = yaml.load_from_file(path=metadata_path_yaml)\n except Exception:\n self._logger.exception(f\"Error while reading .metadata.yaml from {path}\")\n return", " if not isinstance(metadata, dict):\n # looks invalid, ignore it\n return", " with atomic_write(metadata_path_json, mode=\"wb\") as f:\n f.write(to_bytes(json.dumps(metadata, indent=2, separators=(\",\", \": \"))))", " try:\n os.remove(metadata_path_yaml)\n except Exception:\n self._logger.exception(f\"Error while removing .metadata.yaml from {path}\")", " @contextmanager\n def _get_metadata_lock(self, path):\n with self._metadata_lock_mutex:\n if path not in self._metadata_locks:\n import threading", " self._metadata_locks[path] = (0, threading.RLock())", " counter, lock = self._metadata_locks[path]\n counter += 1\n self._metadata_locks[path] = (counter, lock)", " yield lock", " with self._metadata_lock_mutex:\n counter = self._metadata_locks[path][0]\n counter -= 1\n if counter <= 0:\n del self._metadata_locks[path]\n else:\n self._metadata_locks[path] = (counter, lock)", " @contextmanager\n def _get_persisted_metadata_lock(self, path):\n with self._persisted_metadata_lock_mutex:\n if path not in self._persisted_metadata_locks:\n import threading", " self._persisted_metadata_locks[path] = (0, threading.RLock())", " counter, lock = self._persisted_metadata_locks[path]\n counter += 1\n self._persisted_metadata_locks[path] = (counter, lock)", " yield lock", " with self._persisted_metadata_lock_mutex:\n counter = self._persisted_metadata_locks[path][0]\n counter -= 1\n if counter <= 0:\n del self._persisted_metadata_locks[path]\n else:\n self._persisted_metadata_locks[path] = (counter, lock)" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [984, 842, 1177], "buggy_code_start_loc": [956, 42, 1141], "filenames": ["src/octoprint/filemanager/storage.py", "src/octoprint/server/__init__.py", "src/octoprint/server/api/files.py"], "fixing_code_end_loc": [997, 854, 1190], "fixing_code_start_loc": [957, 43, 1141], "message": "Unrestricted Upload of File with Dangerous Type in GitHub repository octoprint/octoprint prior to 1.8.3.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:octoprint:octoprint:*:*:*:*:*:*:*:*", "matchCriteriaId": "900F81F7-9FC4-44CE-ABD6-1E82DC120B4B", "versionEndExcluding": "1.8.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Unrestricted Upload of File with Dangerous Type in GitHub repository octoprint/octoprint prior to 1.8.3."}, {"lang": "es", "value": "Una Descarga sin Restricciones de Archivos de Tipo Peligroso en el repositorio GitHub octoprint/octoprint versiones anteriores a 1.8.3"}], "evaluatorComment": null, "id": "CVE-2022-2872", "lastModified": "2022-09-23T17:58:22.120", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:L/UI:R/S:U/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 1.2, "impactScore": 2.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-09-21T10:15:09.327", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/octoprint/octoprint/commit/3e3c11811e216fb371a33e28412df83f9701e5b0"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/b966c74d-6f3f-49fe-b40a-eaf25e362c56"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-434"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/octoprint/octoprint/commit/3e3c11811e216fb371a33e28412df83f9701e5b0"}, "type": "CWE-434"}
328
Determine whether the {function_name} code is vulnerable or not.
[ "__author__ = \"Gina Häußge <osd@foosel.net>\"\n__license__ = \"GNU Affero General Public License http://www.gnu.org/licenses/agpl.html\"\n__copyright__ = \"Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License\"", "import copy\nimport logging\nimport os\nimport shutil\nfrom contextlib import contextmanager\nfrom os import scandir, walk", "import pylru", "import octoprint.filemanager\nfrom octoprint.util import (\n atomic_write,\n is_hidden_path,\n time_this,\n to_bytes,\n to_unicode,\n yaml,\n)\nfrom octoprint.util.files import sanitize_filename", "\nclass StorageInterface:\n \"\"\"\n Interface of storage adapters for OctoPrint.\n \"\"\"", " # noinspection PyUnreachableCode\n @property\n def analysis_backlog(self):\n \"\"\"\n Get an iterator over all items stored in the storage that need to be analysed by the :class:`~octoprint.filemanager.AnalysisQueue`.", " The yielded elements are expected as storage specific absolute paths to the respective files. Don't forget\n to recurse into folders if your storage adapter supports those.", " :return: an iterator yielding all un-analysed files in the storage\n \"\"\"\n # empty generator pattern, yield is intentionally unreachable\n return\n yield", " # noinspection PyUnreachableCode\n def analysis_backlog_for_path(self, path=None):\n # empty generator pattern, yield is intentionally unreachable\n return\n yield", " def last_modified(self, path=None, recursive=False):\n \"\"\"\n Get the last modification date of the specified ``path`` or ``path``'s subtree.", " Args:\n path (str or None): Path for which to determine the subtree's last modification date. If left out or\n set to None, defatuls to storage root.\n recursive (bool): Whether to determine only the date of the specified ``path`` (False, default) or\n the whole ``path``'s subtree (True).", " Returns: (float) The last modification date of the indicated subtree\n \"\"\"\n raise NotImplementedError()", " def file_in_path(self, path, filepath):\n \"\"\"\n Returns whether the file indicated by ``file`` is inside ``path`` or not.\n :param string path: the path to check\n :param string filepath: path to the file\n :return: ``True`` if the file is inside the path, ``False`` otherwise\n \"\"\"\n return NotImplementedError()", " def file_exists(self, path):\n \"\"\"\n Returns whether the file indicated by ``path`` exists or not.\n :param string path: the path to check for existence\n :return: ``True`` if the file exists, ``False`` otherwise\n \"\"\"\n raise NotImplementedError()", " def folder_exists(self, path):\n \"\"\"\n Returns whether the folder indicated by ``path`` exists or not.\n :param string path: the path to check for existence\n :return: ``True`` if the folder exists, ``False`` otherwise\n \"\"\"\n raise NotImplementedError()", " def list_files(\n self, path=None, filter=None, recursive=True, level=0, force_refresh=False\n ):\n \"\"\"\n List all files in storage starting at ``path``. If ``recursive`` is set to True (the default), also dives into\n subfolders.", " An optional filter function can be supplied which will be called with a file name and file data and which has\n to return True if the file is to be included in the result or False if not.", " The data structure of the returned result will be a dictionary mapping from file names to entry data. File nodes\n will contain their metadata here, folder nodes will contain their contained files and folders. Example::", " {\n \"some_folder\": {\n \"name\": \"some_folder\",\n \"path\": \"some_folder\",\n \"type\": \"folder\",\n \"children\": {\n \"some_sub_folder\": {\n \"name\": \"some_sub_folder\",\n \"path\": \"some_folder/some_sub_folder\",\n \"type\": \"folder\",\n \"typePath\": [\"folder\"],\n \"children\": { ... }\n },\n \"some_file.gcode\": {\n \"name\": \"some_file.gcode\",\n \"path\": \"some_folder/some_file.gcode\",\n \"type\": \"machinecode\",\n \"typePath\": [\"machinecode\", \"gcode\"],\n \"hash\": \"<sha1 hash>\",\n \"links\": [ ... ],\n ...\n },\n ...\n }\n \"test.gcode\": {\n \"name\": \"test.gcode\",\n \"path\": \"test.gcode\",\n \"type\": \"machinecode\",\n \"typePath\": [\"machinecode\", \"gcode\"],\n \"hash\": \"<sha1 hash>\",\n \"links\": [...],\n ...\n },\n \"test.stl\": {\n \"name\": \"test.stl\",\n \"path\": \"test.stl\",\n \"type\": \"model\",\n \"typePath\": [\"model\", \"stl\"],\n \"hash\": \"<sha1 hash>\",\n \"links\": [...],\n ...\n },\n ...\n }", " :param string path: base path from which to recursively list all files, optional, if not supplied listing will start\n from root of base folder\n :param function filter: a filter that matches the files that are to be returned, may be left out in which case no\n filtering will take place\n :param bool recursive: will also step into sub folders for building the complete list if set to True, otherwise will only\n do one step down into sub folders to be able to populate the ``children``.\n :return: a dictionary mapping entry names to entry data that represents the whole file list\n \"\"\"\n raise NotImplementedError()", " def add_folder(self, path, ignore_existing=True, display=None):\n \"\"\"\n Adds a folder as ``path``", " The ``path`` will be sanitized.", " :param string path: the path of the new folder\n :param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists\n :param unicode display: display name of the folder\n :return: the sanitized name of the new folder to be used for future references to the folder\n \"\"\"\n raise NotImplementedError()", " def remove_folder(self, path, recursive=True):\n \"\"\"\n Removes the folder at ``path``", " :param string path: the path of the folder to remove\n :param bool recursive: if set to True, contained folders and files will also be removed, otherwise an error will\n be raised if the folder is not empty (apart from any metadata files) when it's to be removed\n \"\"\"\n raise NotImplementedError()", " def copy_folder(self, source, destination):\n \"\"\"\n Copies the folder ``source`` to ``destination``", " :param string source: path to the source folder\n :param string destination: path to destination", " :return: the path in the storage to the copy of the folder\n \"\"\"\n raise NotImplementedError()", " def move_folder(self, source, destination):\n \"\"\"\n Moves the folder ``source`` to ``destination``", " :param string source: path to the source folder\n :param string destination: path to destination", " :return: the new path in the storage to the folder\n \"\"\"\n raise NotImplementedError()", " def add_file(\n self,\n path,\n file_object,\n printer_profile=None,\n links=None,\n allow_overwrite=False,\n display=None,\n ):\n \"\"\"\n Adds the file ``file_object`` as ``path``", " :param string path: the file's new path, will be sanitized\n :param object file_object: a file object that provides a ``save`` method which will be called with the destination path\n where the object should then store its contents\n :param object printer_profile: the printer profile associated with this file (if any)\n :param list links: any links to add with the file\n :param bool allow_overwrite: if set to True no error will be raised if the file already exists and the existing file\n and its metadata will just be silently overwritten\n :param unicode display: display name of the file\n :return: the sanitized name of the file to be used for future references to it\n \"\"\"\n raise NotImplementedError()", " def remove_file(self, path):\n \"\"\"\n Removes the file at ``path``", " Will also take care of deleting the corresponding entries\n in the metadata and deleting all links pointing to the file.", " :param string path: path of the file to remove\n \"\"\"\n raise NotImplementedError()", " def copy_file(self, source, destination):\n \"\"\"\n Copies the file ``source`` to ``destination``", " :param string source: path to the source file\n :param string destination: path to destination", " :return: the path in the storage to the copy of the file\n \"\"\"\n raise NotImplementedError()", " def move_file(self, source, destination):\n \"\"\"\n Moves the file ``source`` to ``destination``", " :param string source: path to the source file\n :param string destination: path to destination", " :return: the new path in the storage to the file\n \"\"\"\n raise NotImplementedError()", " def has_analysis(self, path):\n \"\"\"\n Returns whether the file at path has been analysed yet", " :param path: virtual path to the file for which to retrieve the metadata\n \"\"\"\n raise NotImplementedError()", " def get_metadata(self, path):\n \"\"\"\n Retrieves the metadata for the file ``path``.", " :param path: virtual path to the file for which to retrieve the metadata\n :return: the metadata associated with the file\n \"\"\"\n raise NotImplementedError()", " def add_link(self, path, rel, data):\n \"\"\"\n Adds a link of relation ``rel`` to file ``path`` with the given ``data``.", " The following relation types are currently supported:", " * ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name``\n and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the\n current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode``\n referring to ``name`` and its hash will also be added to the linked ``model`` file\n * ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected\n additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved\n against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse\n link of type ``model`` referring to ``name`` and its hash will also be added to the linked ``model`` file.\n * ``web``: adds a location on the web associated with this file (e.g. a website where to download a model),\n expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved``\n attribute describing when the content was retrieved", " Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying\n as machine code will be refused.", " :param path: path of the file for which to add a link\n :param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported)\n :param data: additional data of the link to add\n \"\"\"\n raise NotImplementedError()", " def remove_link(self, path, rel, data):\n \"\"\"\n Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``.", " :param path: path of the file from which to remove the link\n :param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported)\n :param data: additional data of the link to remove, must match existing link\n \"\"\"\n raise NotImplementedError()", " def get_additional_metadata(self, path, key):\n \"\"\"\n Fetches additional metadata at ``key`` from the metadata of ``path``.", " :param path: the virtual path to the file for which to fetch additional metadata\n :param key: key of metadata to fetch\n \"\"\"\n raise NotImplementedError()", " def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):\n \"\"\"\n Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``.", " If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten.", " If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries,\n the two dictionaries will be merged recursively.", " :param path: the virtual path to the file for which to add additional metadata\n :param key: key of metadata to add\n :param data: metadata to add\n :param overwrite: if True and ``key`` already exists, it will be overwritten\n :param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they\n will be merged\n \"\"\"\n raise NotImplementedError()", " def remove_additional_metadata(self, path, key):\n \"\"\"\n Removes additional metadata under ``key`` for ``name`` on ``path``", " :param path: the virtual path to the file for which to remove the metadata under ``key``\n :param key: the key to remove\n \"\"\"\n raise NotImplementedError()", " def canonicalize(self, path):\n \"\"\"\n Canonicalizes the given ``path``. The ``path`` may consist of both folder and file name, the underlying\n implementation must separate those if necessary.", " By default, this calls :func:`~octoprint.filemanager.StorageInterface.sanitize`, which also takes care\n of stripping any invalid characters.", " Args:\n path: the path to canonicalize", " Returns:\n a 2-tuple containing the canonicalized path and file name", " \"\"\"\n return self.sanitize(path)", " def sanitize(self, path):\n \"\"\"\n Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both\n folder and file name, the underlying implementation must separate those if necessary and sanitize individually.", " :param string path: the path to sanitize\n :return: a 2-tuple containing the sanitized path and file name\n \"\"\"\n raise NotImplementedError()", " def sanitize_path(self, path):\n \"\"\"\n Sanitizes the given folder-only ``path``, stripping it of all invalid characters.\n :param string path: the path to sanitize\n :return: the sanitized path\n \"\"\"\n raise NotImplementedError()", " def sanitize_name(self, name):\n \"\"\"\n Sanitizes the given file ``name``, stripping it of all invalid characters.\n :param string name: the file name to sanitize\n :return: the sanitized name\n \"\"\"\n raise NotImplementedError()", " def split_path(self, path):\n \"\"\"\n Split ``path`` into base directory and file name.\n :param path: the path to split\n :return: a tuple (base directory, file name)\n \"\"\"\n raise NotImplementedError()", " def join_path(self, *path):\n \"\"\"\n Join path elements together\n :param path: path elements to join\n :return: joined representation of the path to be usable as fully qualified path for further operations\n \"\"\"\n raise NotImplementedError()", " def path_on_disk(self, path):\n \"\"\"\n Retrieves the path on disk for ``path``.", " Note: if the storage is not on disk and there exists no path on disk to refer to it, this method should\n raise an :class:`io.UnsupportedOperation`", " Opposite of :func:`path_in_storage`.", " :param string path: the virtual path for which to retrieve the path on disk\n :return: the path on disk to ``path``\n \"\"\"\n raise NotImplementedError()", " def path_in_storage(self, path):\n \"\"\"\n Retrieves the equivalent in the storage adapter for ``path``.", " Opposite of :func:`path_on_disk`.", " :param string path: the path for which to retrieve the storage path\n :return: the path in storage to ``path``\n \"\"\"\n raise NotImplementedError()", "\nclass StorageError(Exception):\n UNKNOWN = \"unknown\"\n INVALID_DIRECTORY = \"invalid_directory\"\n INVALID_FILE = \"invalid_file\"\n INVALID_SOURCE = \"invalid_source\"\n INVALID_DESTINATION = \"invalid_destination\"\n DOES_NOT_EXIST = \"does_not_exist\"\n ALREADY_EXISTS = \"already_exists\"\n SOURCE_EQUALS_DESTINATION = \"source_equals_destination\"\n NOT_EMPTY = \"not_empty\"", " def __init__(self, message, code=None, cause=None):\n BaseException.__init__(self)\n self.message = message\n self.cause = cause", " if code is None:\n code = StorageError.UNKNOWN\n self.code = code", "\nclass LocalFileStorage(StorageInterface):\n \"\"\"\n The ``LocalFileStorage`` is a storage implementation which holds all files, folders and metadata on disk.", " Metadata is managed inside ``.metadata.json`` files in the respective folders, indexed by the sanitized filenames\n stored within the folder. Metadata access is managed through an LRU cache to minimize access overhead.", " This storage type implements :func:`path_on_disk`.\n \"\"\"", " def __init__(self, basefolder, create=False, really_universal=False):\n \"\"\"\n Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder\n if necessary and ``create`` is set to ``True``.", " :param string basefolder: the path to the folder under which to create the storage\n :param bool create: ``True`` if the folder should be created if it doesn't exist yet, ``False`` otherwise\n :param bool really_universal: ``True`` if the file names should be forced to really universal, ``False`` otherwise\n \"\"\"\n self._logger = logging.getLogger(__name__)", " self.basefolder = os.path.realpath(os.path.abspath(to_unicode(basefolder)))\n if not os.path.exists(self.basefolder) and create:\n os.makedirs(self.basefolder)\n if not os.path.exists(self.basefolder) or not os.path.isdir(self.basefolder):\n raise StorageError(\n f\"{basefolder} is not a valid directory\",\n code=StorageError.INVALID_DIRECTORY,\n )", " self._really_universal = really_universal", " import threading", " self._metadata_lock_mutex = threading.RLock()\n self._metadata_locks = {}\n self._persisted_metadata_lock_mutex = threading.RLock()\n self._persisted_metadata_locks = {}", " self._metadata_cache = pylru.lrucache(100)\n self._filelist_cache = {}\n self._filelist_cache_mutex = threading.RLock()", " self._old_metadata = None\n self._initialize_metadata()", " def _initialize_metadata(self):\n self._logger.info(f\"Initializing the file metadata for {self.basefolder}...\")", " old_metadata_path = os.path.join(self.basefolder, \"metadata.yaml\")\n backup_path = os.path.join(self.basefolder, \"metadata.yaml.backup\")", " if os.path.exists(old_metadata_path):\n # load the old metadata file\n try:\n self._old_metadata = yaml.load_from_file(path=old_metadata_path)\n except Exception:\n self._logger.exception(\"Error while loading old metadata file\")", " # make sure the metadata is initialized as far as possible\n self._list_folder(self.basefolder)", " # rename the old metadata file\n self._old_metadata = None\n try:\n import shutil", " shutil.move(old_metadata_path, backup_path)\n except Exception:\n self._logger.exception(\"Could not rename old metadata.yaml file\")", " else:\n # make sure the metadata is initialized as far as possible\n self._list_folder(self.basefolder)", " self._logger.info(\n f\"... file metadata for {self.basefolder} initialized successfully.\"\n )", " @property\n def analysis_backlog(self):\n return self.analysis_backlog_for_path()", " def analysis_backlog_for_path(self, path=None):\n if path:\n path = self.sanitize_path(path)", " yield from self._analysis_backlog_generator(path)", " def _analysis_backlog_generator(self, path=None):\n if path is None:\n path = self.basefolder", " metadata = self._get_metadata(path)\n if not metadata:\n metadata = {}\n for entry in scandir(path):\n if is_hidden_path(entry.name):\n continue", " if entry.is_file() and octoprint.filemanager.valid_file_type(entry.name):\n if (\n entry.name not in metadata\n or not isinstance(metadata[entry.name], dict)\n or \"analysis\" not in metadata[entry.name]\n ):\n printer_profile_rels = self.get_link(entry.path, \"printerprofile\")\n if printer_profile_rels:\n printer_profile_id = printer_profile_rels[0][\"id\"]\n else:\n printer_profile_id = None", " yield entry.name, entry.path, printer_profile_id\n elif os.path.isdir(entry.path):\n for sub_entry in self._analysis_backlog_generator(entry.path):\n yield self.join_path(entry.name, sub_entry[0]), sub_entry[\n 1\n ], sub_entry[2]", " def last_modified(self, path=None, recursive=False):\n if path is None:\n path = self.basefolder\n else:\n path = os.path.join(self.basefolder, path)", " def last_modified_for_path(p):\n metadata = os.path.join(p, \".metadata.json\")\n if os.path.exists(metadata):\n return max(os.stat(p).st_mtime, os.stat(metadata).st_mtime)\n else:\n return os.stat(p).st_mtime", " if recursive:\n return max(last_modified_for_path(root) for root, _, _ in walk(path))\n else:\n return last_modified_for_path(path)", " def file_in_path(self, path, filepath):\n filepath = self.sanitize_path(filepath)\n path = self.sanitize_path(path)", " return filepath == path or filepath.startswith(path + os.sep)", " def file_exists(self, path):\n path, name = self.sanitize(path)\n file_path = os.path.join(path, name)\n return os.path.exists(file_path) and os.path.isfile(file_path)", " def folder_exists(self, path):\n path, name = self.sanitize(path)\n folder_path = os.path.join(path, name)\n return os.path.exists(folder_path) and os.path.isdir(folder_path)", " def list_files(\n self, path=None, filter=None, recursive=True, level=0, force_refresh=False\n ):\n if path:\n path = self.sanitize_path(to_unicode(path))\n base = self.path_in_storage(path)\n if base:\n base += \"/\"\n else:\n path = self.basefolder\n base = \"\"", " def strip_children(nodes):\n result = {}\n for key, node in nodes.items():\n if node[\"type\"] == \"folder\":\n node = copy.copy(node)\n node[\"children\"] = {}\n result[key] = node\n return result", " def strip_grandchildren(nodes):\n result = {}\n for key, node in nodes.items():\n if node[\"type\"] == \"folder\":\n node = copy.copy(node)\n node[\"children\"] = strip_children(node[\"children\"])\n result[key] = node\n return result", " def apply_filter(nodes, filter_func):\n result = {}\n for key, node in nodes.items():\n if filter_func(node) or node[\"type\"] == \"folder\":\n if node[\"type\"] == \"folder\":\n node = copy.copy(node)\n node[\"children\"] = apply_filter(\n node.get(\"children\", {}), filter_func\n )\n result[key] = node\n return result", " result = self._list_folder(path, base=base, force_refresh=force_refresh)\n if not recursive:\n if level > 0:\n result = strip_grandchildren(result)\n else:\n result = strip_children(result)\n if callable(filter):\n result = apply_filter(result, filter)\n return result", " def add_folder(self, path, ignore_existing=True, display=None):\n display_path, display_name = self.canonicalize(path)\n path = self.sanitize_path(display_path)\n name = self.sanitize_name(display_name)", " if display is not None:\n display_name = display", " folder_path = os.path.join(path, name)\n if os.path.exists(folder_path):\n if not ignore_existing:\n raise StorageError(\n f\"{name} does already exist in {path}\",\n code=StorageError.ALREADY_EXISTS,\n )\n else:\n os.mkdir(folder_path)", " if display_name != name:\n metadata = self._get_metadata_entry(path, name, default={})\n metadata[\"display\"] = display_name\n self._update_metadata_entry(path, name, metadata)", " return self.path_in_storage((path, name))", " def remove_folder(self, path, recursive=True):\n path, name = self.sanitize(path)", " folder_path = os.path.join(path, name)\n if not os.path.exists(folder_path):\n return", " empty = True\n for entry in scandir(folder_path):\n if entry.name == \".metadata.json\" or entry.name == \".metadata.yaml\":\n continue\n empty = False\n break", " if not empty and not recursive:\n raise StorageError(\n f\"{name} in {path} is not empty\",\n code=StorageError.NOT_EMPTY,\n )", " import shutil", " shutil.rmtree(folder_path)", " self._remove_metadata_entry(path, name)", " def _get_source_destination_data(self, source, destination, must_not_equal=False):\n \"\"\"Prepares data dicts about source and destination for copy/move.\"\"\"\n source_path, source_name = self.sanitize(source)", " destination_canon_path, destination_canon_name = self.canonicalize(destination)\n destination_path = self.sanitize_path(destination_canon_path)\n destination_name = self.sanitize_name(destination_canon_name)", " source_fullpath = os.path.join(source_path, source_name)\n destination_fullpath = os.path.join(destination_path, destination_name)", " if not os.path.exists(source_fullpath):\n raise StorageError(\n f\"{source_name} in {source_path} does not exist\",\n code=StorageError.INVALID_SOURCE,\n )", " if not os.path.isdir(destination_path):\n raise StorageError(\n \"Destination path {} does not exist or is not a folder\".format(\n destination_path\n ),\n code=StorageError.INVALID_DESTINATION,\n )\n if (\n os.path.exists(destination_fullpath)\n and source_fullpath != destination_fullpath\n ):\n raise StorageError(\n f\"{destination_name} does already exist in {destination_path}\",\n code=StorageError.INVALID_DESTINATION,\n )", " source_meta = self._get_metadata_entry(source_path, source_name)\n if source_meta:\n source_display = source_meta.get(\"display\", source_name)\n else:\n source_display = source_name", " if (\n must_not_equal or source_display == destination_canon_name\n ) and source_fullpath == destination_fullpath:\n raise StorageError(\n \"Source {} and destination {} are the same folder\".format(\n source_path, destination_path\n ),\n code=StorageError.SOURCE_EQUALS_DESTINATION,\n )", " source_data = {\n \"path\": source_path,\n \"name\": source_name,\n \"display\": source_display,\n \"fullpath\": source_fullpath,\n }\n destination_data = {\n \"path\": destination_path,\n \"name\": destination_name,\n \"display\": destination_canon_name,\n \"fullpath\": destination_fullpath,\n }\n return source_data, destination_data", " def _set_display_metadata(self, destination_data, source_data=None):\n if (\n source_data\n and destination_data[\"name\"] == source_data[\"name\"]\n and source_data[\"name\"] != source_data[\"display\"]\n ):\n display = source_data[\"display\"]\n elif destination_data[\"name\"] != destination_data[\"display\"]:\n display = destination_data[\"display\"]\n else:\n display = None", " destination_meta = self._get_metadata_entry(\n destination_data[\"path\"], destination_data[\"name\"], default={}\n )\n if display:\n destination_meta[\"display\"] = display\n self._update_metadata_entry(\n destination_data[\"path\"], destination_data[\"name\"], destination_meta\n )\n elif \"display\" in destination_meta:\n del destination_meta[\"display\"]\n self._update_metadata_entry(\n destination_data[\"path\"], destination_data[\"name\"], destination_meta\n )", " def copy_folder(self, source, destination):\n source_data, destination_data = self._get_source_destination_data(\n source, destination, must_not_equal=True\n )", " try:\n shutil.copytree(source_data[\"fullpath\"], destination_data[\"fullpath\"])\n except Exception as e:\n raise StorageError(\n \"Could not copy %s in %s to %s in %s\"\n % (\n source_data[\"name\"],\n source_data[\"path\"],\n destination_data[\"name\"],\n destination_data[\"path\"],\n ),\n cause=e,\n )", " self._set_display_metadata(destination_data, source_data=source_data)", " return self.path_in_storage(destination_data[\"fullpath\"])", " def move_folder(self, source, destination):\n source_data, destination_data = self._get_source_destination_data(\n source, destination\n )", " # only a display rename? Update that and bail early\n if source_data[\"fullpath\"] == destination_data[\"fullpath\"]:\n self._set_display_metadata(destination_data)\n return self.path_in_storage(destination_data[\"fullpath\"])", " try:\n shutil.move(source_data[\"fullpath\"], destination_data[\"fullpath\"])\n except Exception as e:\n raise StorageError(\n \"Could not move %s in %s to %s in %s\"\n % (\n source_data[\"name\"],\n source_data[\"path\"],\n destination_data[\"name\"],\n destination_data[\"path\"],\n ),\n cause=e,\n )", " self._set_display_metadata(destination_data, source_data=source_data)\n self._remove_metadata_entry(source_data[\"path\"], source_data[\"name\"])\n self._delete_metadata(source_data[\"fullpath\"])", " return self.path_in_storage(destination_data[\"fullpath\"])", " def add_file(\n self,\n path,\n file_object,\n printer_profile=None,\n links=None,\n allow_overwrite=False,\n display=None,\n ):\n display_path, display_name = self.canonicalize(path)\n path = self.sanitize_path(display_path)\n name = self.sanitize_name(display_name)", " if display:\n display_name = display", " if not octoprint.filemanager.valid_file_type(name):\n raise StorageError(\n f\"{name} is an unrecognized file type\",\n code=StorageError.INVALID_FILE,\n )", " file_path = os.path.join(path, name)\n if os.path.exists(file_path) and not os.path.isfile(file_path):\n raise StorageError(\n f\"{name} does already exist in {path} and is not a file\",\n code=StorageError.ALREADY_EXISTS,\n )\n if os.path.exists(file_path) and not allow_overwrite:\n raise StorageError(\n f\"{name} does already exist in {path} and overwriting is prohibited\",\n code=StorageError.ALREADY_EXISTS,\n )", " # make sure folders exist\n if not os.path.exists(path):\n # TODO persist display names of path segments!\n os.makedirs(path)", " # save the file\n file_object.save(file_path)", " # save the file's hash to the metadata of the folder\n file_hash = self._create_hash(file_path)\n metadata = self._get_metadata_entry(path, name, default={})\n metadata_dirty = False\n if \"hash\" not in metadata or metadata[\"hash\"] != file_hash:\n # hash changed -> throw away old metadata\n metadata = {\"hash\": file_hash}\n metadata_dirty = True", " if \"display\" not in metadata and display_name != name:\n # display name is not the same as file name -> store in metadata\n metadata[\"display\"] = display_name\n metadata_dirty = True", " if metadata_dirty:\n self._update_metadata_entry(path, name, metadata)", " # process any links that were also provided for adding to the file\n if not links:\n links = []", " if printer_profile is not None:\n links.append(\n (\n \"printerprofile\",\n {\"id\": printer_profile[\"id\"], \"name\": printer_profile[\"name\"]},\n )\n )", " self._add_links(name, path, links)", " # touch the file to set last access and modification time to now\n os.utime(file_path, None)", " return self.path_in_storage((path, name))", " def remove_file(self, path):\n path, name = self.sanitize(path)", " file_path = os.path.join(path, name)\n if not os.path.exists(file_path):\n return\n if not os.path.isfile(file_path):\n raise StorageError(\n f\"{name} in {path} is not a file\",\n code=StorageError.INVALID_FILE,\n )", " try:\n os.remove(file_path)\n except Exception as e:\n raise StorageError(f\"Could not delete {name} in {path}\", cause=e)", " self._remove_metadata_entry(path, name)", " def copy_file(self, source, destination):\n source_data, destination_data = self._get_source_destination_data(\n source, destination, must_not_equal=True\n )\n", " if not octoprint.filemanager.valid_file_type(destination_data[\"name\"]):\n raise StorageError(\n f\"{destination_data['name']} is an unrecognized file type\",\n code=StorageError.INVALID_FILE,\n )\n", " try:\n shutil.copy2(source_data[\"fullpath\"], destination_data[\"fullpath\"])\n except Exception as e:\n raise StorageError(\n \"Could not copy %s in %s to %s in %s\"\n % (\n source_data[\"name\"],\n source_data[\"path\"],\n destination_data[\"name\"],\n destination_data[\"path\"],\n ),\n cause=e,\n )", " self._copy_metadata_entry(\n source_data[\"path\"],\n source_data[\"name\"],\n destination_data[\"path\"],\n destination_data[\"name\"],\n )\n self._set_display_metadata(destination_data, source_data=source_data)", " return self.path_in_storage(destination_data[\"fullpath\"])", " def move_file(self, source, destination, allow_overwrite=False):\n source_data, destination_data = self._get_source_destination_data(\n source, destination\n )", "\n if not octoprint.filemanager.valid_file_type(destination_data[\"name\"]):\n raise StorageError(\n f\"{destination_data['name']} is an unrecognized file type\",\n code=StorageError.INVALID_FILE,\n )", "\n # only a display rename? Update that and bail early\n if source_data[\"fullpath\"] == destination_data[\"fullpath\"]:\n self._set_display_metadata(destination_data)\n return self.path_in_storage(destination_data[\"fullpath\"])", " try:\n shutil.move(source_data[\"fullpath\"], destination_data[\"fullpath\"])\n except Exception as e:\n raise StorageError(\n \"Could not move %s in %s to %s in %s\"\n % (\n source_data[\"name\"],\n source_data[\"path\"],\n destination_data[\"name\"],\n destination_data[\"path\"],\n ),\n cause=e,\n )", " self._copy_metadata_entry(\n source_data[\"path\"],\n source_data[\"name\"],\n destination_data[\"path\"],\n destination_data[\"name\"],\n delete_source=True,\n )\n self._set_display_metadata(destination_data, source_data=source_data)", " return self.path_in_storage(destination_data[\"fullpath\"])", " def has_analysis(self, path):\n metadata = self.get_metadata(path)\n return \"analysis\" in metadata", " def get_metadata(self, path):\n path, name = self.sanitize(path)\n return self._get_metadata_entry(path, name)", " def get_link(self, path, rel):\n path, name = self.sanitize(path)\n return self._get_links(name, path, rel)", " def add_link(self, path, rel, data):\n path, name = self.sanitize(path)\n self._add_links(name, path, [(rel, data)])", " def remove_link(self, path, rel, data):\n path, name = self.sanitize(path)\n self._remove_links(name, path, [(rel, data)])", " def add_history(self, path, data):\n path, name = self.sanitize(path)\n self._add_history(name, path, data)", " def update_history(self, path, index, data):\n path, name = self.sanitize(path)\n self._update_history(name, path, index, data)", " def remove_history(self, path, index):\n path, name = self.sanitize(path)\n self._delete_history(name, path, index)", " def get_additional_metadata(self, path, key):\n path, name = self.sanitize(path)\n metadata = self._get_metadata(path)", " if name not in metadata:\n return", " return metadata[name].get(key)", " def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):\n path, name = self.sanitize(path)\n metadata = self._get_metadata(path)\n metadata_dirty = False", " if name not in metadata:\n return", " metadata = self._copied_metadata(metadata, name)", " if key not in metadata[name] or overwrite:\n metadata[name][key] = data\n metadata_dirty = True\n elif (\n key in metadata[name]\n and isinstance(metadata[name][key], dict)\n and isinstance(data, dict)\n and merge\n ):\n import octoprint.util", " metadata[name][key] = octoprint.util.dict_merge(\n metadata[name][key], data, in_place=True\n )\n metadata_dirty = True", " if metadata_dirty:\n self._save_metadata(path, metadata)", " def remove_additional_metadata(self, path, key):\n path, name = self.sanitize(path)\n metadata = self._get_metadata(path)", " if name not in metadata:\n return", " if key not in metadata[name]:\n return", " metadata = self._copied_metadata(metadata, name)\n del metadata[name][key]\n self._save_metadata(path, metadata)", " def split_path(self, path):\n path = to_unicode(path)\n split = path.split(\"/\")\n if len(split) == 1:\n return \"\", split[0]\n else:\n return self.join_path(*split[:-1]), split[-1]", " def join_path(self, *path):\n return \"/\".join(map(to_unicode, path))", " def sanitize(self, path):\n \"\"\"\n Returns a ``(path, name)`` tuple derived from the provided ``path``.", " ``path`` may be:\n * a storage path\n * an absolute file system path\n * a tuple or list containing all individual path elements\n * a string representation of the path\n * with or without a file name", " Note that for a ``path`` without a trailing slash the last part will be considered a file name and\n hence be returned at second position. If you only need to convert a folder path, be sure to\n include a trailing slash for a string ``path`` or an empty last element for a list ``path``.\n \"\"\"", " path, name = self.canonicalize(path)\n name = self.sanitize_name(name)\n path = self.sanitize_path(path)\n return path, name", " def canonicalize(self, path):\n name = None\n if isinstance(path, str):\n path = to_unicode(path)\n if path.startswith(self.basefolder):\n path = path[len(self.basefolder) :]\n path = path.replace(os.path.sep, \"/\")\n path = path.split(\"/\")\n if isinstance(path, (list, tuple)):\n if len(path) == 1:\n name = to_unicode(path[0])\n path = \"\"\n else:\n name = to_unicode(path[-1])\n path = self.join_path(*map(to_unicode, path[:-1]))\n if not path:\n path = \"\"", " return path, name", " def sanitize_name(self, name):\n \"\"\"\n Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\\\\``. Otherwise\n sanitizes the given ``name`` using ``octoprint.files.sanitize_filename``. Also\n strips any leading ``.``.\n \"\"\"\n return sanitize_filename(name, really_universal=self._really_universal)", " def sanitize_path(self, path):\n \"\"\"\n Ensures that the on disk representation of ``path`` is located under the configured basefolder. Resolves all\n relative path elements (e.g. ``..``) and sanitizes folder names using :func:`sanitize_name`. Final path is the\n absolute path including leading ``basefolder`` path.\n \"\"\"\n path = to_unicode(path)", " if len(path):\n if path[0] == \"/\":\n path = path[1:]\n elif path[0] == \".\" and path[1] == \"/\":\n path = path[2:]", " path_elements = path.split(\"/\")\n joined_path = self.basefolder\n for path_element in path_elements:\n if path_element == \"..\" or path_element == \".\":\n joined_path = os.path.join(joined_path, path_element)\n else:\n joined_path = os.path.join(joined_path, self.sanitize_name(path_element))\n path = os.path.realpath(joined_path)\n if not path.startswith(self.basefolder):\n raise ValueError(f\"path not contained in base folder: {path}\")\n return path", " def _sanitize_entry(self, entry, path, entry_path):\n entry = to_unicode(entry)\n sanitized = self.sanitize_name(entry)\n if sanitized != entry:\n # entry is not sanitized yet, let's take care of that\n sanitized_path = os.path.join(path, sanitized)\n sanitized_name, sanitized_ext = os.path.splitext(sanitized)", " counter = 1\n while os.path.exists(sanitized_path):\n counter += 1\n sanitized = self.sanitize_name(\n f\"{sanitized_name}_({counter}){sanitized_ext}\"\n )\n sanitized_path = os.path.join(path, sanitized)", " try:\n shutil.move(entry_path, sanitized_path)", " self._logger.info(f'Sanitized \"{entry_path}\" to \"{sanitized_path}\"')\n return sanitized, sanitized_path\n except Exception:\n self._logger.exception(\n 'Error while trying to rename \"{}\" to \"{}\", ignoring file'.format(\n entry_path, sanitized_path\n )\n )\n raise", " return entry, entry_path", " def path_in_storage(self, path):\n if isinstance(path, (tuple, list)):\n path = self.join_path(*path)\n if isinstance(path, str):\n path = to_unicode(path)\n if path.startswith(self.basefolder):\n path = path[len(self.basefolder) :]\n path = path.replace(os.path.sep, \"/\")\n if path.startswith(\"/\"):\n path = path[1:]", " return path", " def path_on_disk(self, path):\n path, name = self.sanitize(path)\n return os.path.join(path, name)", " ##~~ internals", " def _add_history(self, name, path, data):\n metadata = self._copied_metadata(self._get_metadata(path), name)", " if \"hash\" not in metadata[name]:\n metadata[name][\"hash\"] = self._create_hash(os.path.join(path, name))", " if \"history\" not in metadata[name]:\n metadata[name][\"history\"] = []", " metadata[name][\"history\"].append(data)\n self._calculate_stats_from_history(name, path, metadata=metadata, save=False)\n self._save_metadata(path, metadata)", " def _update_history(self, name, path, index, data):\n metadata = self._get_metadata(path)", " if name not in metadata or \"history\" not in metadata[name]:\n return", " metadata = self._copied_metadata(metadata, name)", " try:\n metadata[name][\"history\"][index].update(data)\n self._calculate_stats_from_history(name, path, metadata=metadata, save=False)\n self._save_metadata(path, metadata)\n except IndexError:\n pass", " def _delete_history(self, name, path, index):\n metadata = self._get_metadata(path)", " if name not in metadata or \"history\" not in metadata[name]:\n return", " metadata = self._copied_metadata(metadata, name)", " try:\n del metadata[name][\"history\"][index]\n self._calculate_stats_from_history(name, path, metadata=metadata, save=False)\n self._save_metadata(path, metadata)\n except IndexError:\n pass", " def _calculate_stats_from_history(self, name, path, metadata=None, save=True):\n if metadata is None:\n metadata = self._copied_metadata(self._get_metadata(path), name)", " if \"history\" not in metadata[name]:\n return", " # collect data from history\n former_print_times = {}\n last_print = {}", " for history_entry in metadata[name][\"history\"]:\n if (\n \"printTime\" not in history_entry\n or \"success\" not in history_entry\n or not history_entry[\"success\"]\n or \"printerProfile\" not in history_entry\n ):\n continue", " printer_profile = history_entry[\"printerProfile\"]\n if not printer_profile:\n continue", " print_time = history_entry[\"printTime\"]\n try:\n print_time = float(print_time)\n except Exception:\n self._logger.warning(\n \"Invalid print time value found in print history for {} in {}/.metadata.json: {!r}\".format(\n name, path, print_time\n )\n )\n continue", " if printer_profile not in former_print_times:\n former_print_times[printer_profile] = []\n former_print_times[printer_profile].append(print_time)", " if (\n printer_profile not in last_print\n or last_print[printer_profile] is None\n or (\n \"timestamp\" in history_entry\n and history_entry[\"timestamp\"]\n > last_print[printer_profile][\"timestamp\"]\n )\n ):\n last_print[printer_profile] = history_entry", " # calculate stats\n statistics = {\"averagePrintTime\": {}, \"lastPrintTime\": {}}", " for printer_profile in former_print_times:\n if not former_print_times[printer_profile]:\n continue\n statistics[\"averagePrintTime\"][printer_profile] = sum(\n former_print_times[printer_profile]\n ) / len(former_print_times[printer_profile])", " for printer_profile in last_print:\n if not last_print[printer_profile]:\n continue\n statistics[\"lastPrintTime\"][printer_profile] = last_print[printer_profile][\n \"printTime\"\n ]", " metadata[name][\"statistics\"] = statistics", " if save:\n self._save_metadata(path, metadata)", " def _get_links(self, name, path, searched_rel):\n metadata = self._get_metadata(path)\n result = []", " if name not in metadata:\n return result", " if \"links\" not in metadata[name]:\n return result", " for data in metadata[name][\"links\"]:\n if \"rel\" not in data or not data[\"rel\"] == searched_rel:\n continue\n result.append(data)\n return result", " def _add_links(self, name, path, links):\n file_type = octoprint.filemanager.get_file_type(name)\n if file_type:\n file_type = file_type[0]", " metadata = self._copied_metadata(self._get_metadata(path), name)\n metadata_dirty = False", " if \"hash\" not in metadata[name]:\n metadata[name][\"hash\"] = self._create_hash(os.path.join(path, name))", " if \"links\" not in metadata[name]:\n metadata[name][\"links\"] = []", " for rel, data in links:\n if (rel == \"model\" or rel == \"machinecode\") and \"name\" in data:\n if file_type == \"model\" and rel == \"model\":\n # adding a model link to a model doesn't make sense\n return\n elif file_type == \"machinecode\" and rel == \"machinecode\":\n # adding a machinecode link to a machinecode doesn't make sense\n return", " ref_path = os.path.join(path, data[\"name\"])\n if not os.path.exists(ref_path):\n # file doesn't exist, we won't create the link\n continue", " # fetch hash of target file\n if data[\"name\"] in metadata and \"hash\" in metadata[data[\"name\"]]:\n hash = metadata[data[\"name\"]][\"hash\"]\n else:\n hash = self._create_hash(ref_path)\n if data[\"name\"] not in metadata:\n metadata[data[\"name\"]] = {\"hash\": hash, \"links\": []}\n else:\n metadata[data[\"name\"]][\"hash\"] = hash", " if \"hash\" in data and not data[\"hash\"] == hash:\n # file doesn't have the correct hash, we won't create the link\n continue", " if \"links\" not in metadata[data[\"name\"]]:\n metadata[data[\"name\"]][\"links\"] = []", " # add reverse link to link target file\n metadata[data[\"name\"]][\"links\"].append(\n {\n \"rel\": \"machinecode\" if rel == \"model\" else \"model\",\n \"name\": name,\n \"hash\": metadata[name][\"hash\"],\n }\n )\n metadata_dirty = True", " link_dict = {\"rel\": rel, \"name\": data[\"name\"], \"hash\": hash}", " elif rel == \"web\" and \"href\" in data:\n link_dict = {\"rel\": rel, \"href\": data[\"href\"]}\n if \"retrieved\" in data:\n link_dict[\"retrieved\"] = data[\"retrieved\"]", " else:\n continue", " if link_dict:\n metadata[name][\"links\"].append(link_dict)\n metadata_dirty = True", " if metadata_dirty:\n self._save_metadata(path, metadata)", " def _remove_links(self, name, path, links):\n metadata = self._copied_metadata(self._get_metadata(path), name)\n metadata_dirty = False", " hash = metadata[name].get(\"hash\", self._create_hash(os.path.join(path, name)))", " for rel, data in links:\n if (rel == \"model\" or rel == \"machinecode\") and \"name\" in data:\n if data[\"name\"] in metadata and \"links\" in metadata[data[\"name\"]]:\n ref_rel = \"model\" if rel == \"machinecode\" else \"machinecode\"\n for link in metadata[data[\"name\"]][\"links\"]:\n if (\n link[\"rel\"] == ref_rel\n and \"name\" in link\n and link[\"name\"] == name\n and \"hash\" in link\n and link[\"hash\"] == hash\n ):\n metadata[data[\"name\"]] = copy.deepcopy(metadata[data[\"name\"]])\n metadata[data[\"name\"]][\"links\"].remove(link)\n metadata_dirty = True", " if \"links\" in metadata[name]:\n for link in metadata[name][\"links\"]:\n if not link[\"rel\"] == rel:\n continue", " matches = True\n for k, v in data.items():\n if k not in link or not link[k] == v:\n matches = False\n break", " if not matches:\n continue", " metadata[name][\"links\"].remove(link)\n metadata_dirty = True", " if metadata_dirty:\n self._save_metadata(path, metadata)", " @time_this(\n logtarget=__name__ + \".timings\",\n message=\"{func}({func_args},{func_kwargs}) took {timing:.2f}ms\",\n incl_func_args=True,\n log_enter=True,\n )\n def _list_folder(self, path, base=\"\", force_refresh=False, **kwargs):\n def get_size(nodes):\n total_size = 0\n for node in nodes.values():\n if \"size\" in node:\n total_size += node[\"size\"]\n return total_size", " def enrich_folders(nodes):\n nodes = copy.copy(nodes)\n for key, value in nodes.items():\n if value[\"type\"] == \"folder\":\n value = copy.copy(value)\n value[\"children\"] = self._list_folder(\n os.path.join(path, key),\n base=value[\"path\"] + \"/\",\n force_refresh=force_refresh,\n )\n value[\"size\"] = get_size(value[\"children\"])\n nodes[key] = value\n return nodes", " metadata_dirty = False\n try:\n with self._filelist_cache_mutex:\n cache = self._filelist_cache.get(path)\n lm = self.last_modified(path, recursive=True)\n if not force_refresh and cache and cache[0] >= lm:\n return enrich_folders(cache[1])", " metadata = self._get_metadata(path)\n if not metadata:\n metadata = {}", " result = {}", " for entry in scandir(path):\n if is_hidden_path(entry.name):\n # no hidden files and folders\n continue", " try:\n entry_name = entry_display = entry.name\n entry_path = entry.path\n entry_is_file = entry.is_file()\n entry_is_dir = entry.is_dir()\n entry_stat = entry.stat()\n except Exception:\n # error while trying to fetch file metadata, that might be thanks to file already having\n # been moved or deleted - ignore it and continue\n continue", " try:\n new_entry_name, new_entry_path = self._sanitize_entry(\n entry_name, path, entry_path\n )\n if entry_name != new_entry_name or entry_path != new_entry_path:\n entry_display = to_unicode(entry_name)\n entry_name = new_entry_name\n entry_path = new_entry_path\n entry_stat = os.stat(entry_path)\n except Exception:\n # error while trying to rename the file, we'll continue here and ignore it\n continue", " path_in_location = entry_name if not base else base + entry_name", " try:\n # file handling\n if entry_is_file:\n type_path = octoprint.filemanager.get_file_type(entry_name)\n if not type_path:\n # only supported extensions\n continue\n else:\n file_type = type_path[0]", " if entry_name in metadata and isinstance(\n metadata[entry_name], dict\n ):\n entry_metadata = metadata[entry_name]\n if (\n \"display\" not in entry_metadata\n and entry_display != entry_name\n ):\n if not metadata_dirty:\n metadata = self._copied_metadata(\n metadata, entry_name\n )\n metadata[entry_name][\"display\"] = entry_display\n entry_metadata[\"display\"] = entry_display\n metadata_dirty = True\n else:\n if not metadata_dirty:\n metadata = self._copied_metadata(metadata, entry_name)\n entry_metadata = self._add_basic_metadata(\n path,\n entry_name,\n display_name=entry_display,\n save=False,\n metadata=metadata,\n )\n metadata_dirty = True", " extended_entry_data = {}\n extended_entry_data.update(entry_metadata)\n extended_entry_data[\"name\"] = entry_name\n extended_entry_data[\"display\"] = entry_metadata.get(\n \"display\", entry_name\n )\n extended_entry_data[\"path\"] = path_in_location\n extended_entry_data[\"type\"] = file_type\n extended_entry_data[\"typePath\"] = type_path\n stat = entry_stat\n if stat:\n extended_entry_data[\"size\"] = stat.st_size\n extended_entry_data[\"date\"] = int(stat.st_mtime)", " result[entry_name] = extended_entry_data", " # folder recursion\n elif entry_is_dir:\n if entry_name in metadata and isinstance(\n metadata[entry_name], dict\n ):\n entry_metadata = metadata[entry_name]\n if (\n \"display\" not in entry_metadata\n and entry_display != entry_name\n ):\n if not metadata_dirty:\n metadata = self._copied_metadata(\n metadata, entry_name\n )\n metadata[entry_name][\"display\"] = entry_display\n entry_metadata[\"display\"] = entry_display\n metadata_dirty = True\n elif entry_name != entry_display:\n if not metadata_dirty:\n metadata = self._copied_metadata(metadata, entry_name)\n entry_metadata = self._add_basic_metadata(\n path,\n entry_name,\n display_name=entry_display,\n save=False,\n metadata=metadata,\n )\n metadata_dirty = True\n else:\n entry_metadata = {}", " entry_data = {\n \"name\": entry_name,\n \"display\": entry_metadata.get(\"display\", entry_name),\n \"path\": path_in_location,\n \"type\": \"folder\",\n \"typePath\": [\"folder\"],\n }", " result[entry_name] = entry_data\n except Exception:\n # So something went wrong somewhere while processing this file entry - log that and continue\n self._logger.exception(\n f\"Error while processing entry {entry_path}\"\n )\n continue", " self._filelist_cache[path] = (\n lm,\n result,\n )\n return enrich_folders(result)\n finally:\n # save metadata\n if metadata_dirty:\n self._save_metadata(path, metadata)", " def _add_basic_metadata(\n self,\n path,\n entry,\n display_name=None,\n additional_metadata=None,\n save=True,\n metadata=None,\n ):\n if additional_metadata is None:\n additional_metadata = {}", " if metadata is None:\n metadata = self._get_metadata(path)", " entry_path = os.path.join(path, entry)", " if os.path.isfile(entry_path):\n entry_data = {\n \"hash\": self._create_hash(os.path.join(path, entry)),\n \"links\": [],\n \"notes\": [],\n }\n if (\n path == self.basefolder\n and self._old_metadata is not None\n and entry in self._old_metadata\n and \"gcodeAnalysis\" in self._old_metadata[entry]\n ):\n # if there is still old metadata available and that contains an analysis for this file, use it!\n entry_data[\"analysis\"] = self._old_metadata[entry][\"gcodeAnalysis\"]", " elif os.path.isdir(entry_path):\n entry_data = {}", " else:\n return", " if display_name is not None and not display_name == entry:\n entry_data[\"display\"] = display_name", " entry_data.update(additional_metadata)", " metadata = copy.copy(metadata)\n metadata[entry] = entry_data", " if save:\n self._save_metadata(path, metadata)", " return entry_data", " def _create_hash(self, path):\n import hashlib", " blocksize = 65536\n hash = hashlib.sha1()\n with open(path, \"rb\") as f:\n buffer = f.read(blocksize)\n while len(buffer) > 0:\n hash.update(buffer)\n buffer = f.read(blocksize)", " return hash.hexdigest()", " def _get_metadata_entry(self, path, name, default=None):\n with self._get_metadata_lock(path):\n metadata = self._get_metadata(path)\n return metadata.get(name, default)", " def _remove_metadata_entry(self, path, name):\n with self._get_metadata_lock(path):\n metadata = self._get_metadata(path)\n if name not in metadata:\n return", " metadata = copy.copy(metadata)", " if \"hash\" in metadata[name]:\n hash = metadata[name][\"hash\"]\n for m in metadata.values():\n if \"links\" not in m:\n continue\n links_hash = (\n lambda link: \"hash\" in link\n and link[\"hash\"] == hash\n and \"rel\" in link\n and (link[\"rel\"] == \"model\" or link[\"rel\"] == \"machinecode\")\n )\n m[\"links\"] = [link for link in m[\"links\"] if not links_hash(link)]", " del metadata[name]\n self._save_metadata(path, metadata)", " def _update_metadata_entry(self, path, name, data):\n with self._get_metadata_lock(path):\n metadata = copy.copy(self._get_metadata(path))\n metadata[name] = data\n self._save_metadata(path, metadata)", " def _copy_metadata_entry(\n self,\n source_path,\n source_name,\n destination_path,\n destination_name,\n delete_source=False,\n updates=None,\n ):\n with self._get_metadata_lock(source_path):\n source_data = self._get_metadata_entry(source_path, source_name, default={})\n if not source_data:\n return", " if delete_source:\n self._remove_metadata_entry(source_path, source_name)", " if updates is not None:\n source_data.update(updates)", " with self._get_metadata_lock(destination_path):\n self._update_metadata_entry(destination_path, destination_name, source_data)", " def _get_metadata(self, path, force=False):\n import json", " if not force:\n metadata = self._metadata_cache.get(path)\n if metadata:\n return metadata", " self._migrate_metadata(path)", " metadata_path = os.path.join(path, \".metadata.json\")", " metadata = None\n with self._get_persisted_metadata_lock(path):\n if os.path.exists(metadata_path):\n with open(metadata_path, encoding=\"utf-8\") as f:\n try:\n metadata = json.load(f)\n except Exception:\n self._logger.exception(\n f\"Error while reading .metadata.json from {path}\"\n )", " def valid_json(value):\n try:\n json.dumps(value, allow_nan=False)\n return True\n except Exception:\n return False", " if isinstance(metadata, dict):\n old_size = len(metadata)\n metadata = {k: v for k, v in metadata.items() if valid_json(v)}\n metadata = {\n k: v for k, v in metadata.items() if os.path.exists(os.path.join(path, k))\n }\n new_size = len(metadata)\n if new_size != old_size:\n self._logger.info(\n \"Deleted {} stale or invalid entries from metadata for path {}\".format(\n old_size - new_size, path\n )\n )\n self._save_metadata(path, metadata)\n else:\n with self._get_metadata_lock(path):\n self._metadata_cache[path] = metadata\n return metadata\n else:\n return {}", " def _save_metadata(self, path, metadata):\n import json", " with self._get_metadata_lock(path):\n self._metadata_cache[path] = metadata", " with self._get_persisted_metadata_lock(path):\n metadata_path = os.path.join(path, \".metadata.json\")\n try:\n with atomic_write(metadata_path, mode=\"wb\") as f:\n f.write(\n to_bytes(json.dumps(metadata, indent=2, separators=(\",\", \": \")))\n )\n except Exception:\n self._logger.exception(f\"Error while writing .metadata.json to {path}\")", " def _delete_metadata(self, path):\n with self._get_metadata_lock(path):\n if path in self._metadata_cache:\n del self._metadata_cache[path]", " with self._get_persisted_metadata_lock(path):\n metadata_files = (\".metadata.json\", \".metadata.yaml\")\n for metadata_file in metadata_files:\n metadata_path = os.path.join(path, metadata_file)\n if os.path.exists(metadata_path):\n try:\n os.remove(metadata_path)\n except Exception:\n self._logger.exception(\n f\"Error while deleting {metadata_file} from {path}\"\n )", " @staticmethod\n def _copied_metadata(metadata, name):\n metadata = copy.copy(metadata)\n metadata[name] = copy.deepcopy(metadata.get(name, {}))\n return metadata", " def _migrate_metadata(self, path):\n # we switched to json in 1.3.9 - if we still have yaml here, migrate it now\n import json", " with self._get_persisted_metadata_lock(path):\n metadata_path_yaml = os.path.join(path, \".metadata.yaml\")\n metadata_path_json = os.path.join(path, \".metadata.json\")", " if not os.path.exists(metadata_path_yaml):\n # nothing to migrate\n return", " if os.path.exists(metadata_path_json):\n # already migrated\n try:\n os.remove(metadata_path_yaml)\n except Exception:\n self._logger.exception(\n f\"Error while removing .metadata.yaml from {path}\"\n )\n return", " try:\n metadata = yaml.load_from_file(path=metadata_path_yaml)\n except Exception:\n self._logger.exception(f\"Error while reading .metadata.yaml from {path}\")\n return", " if not isinstance(metadata, dict):\n # looks invalid, ignore it\n return", " with atomic_write(metadata_path_json, mode=\"wb\") as f:\n f.write(to_bytes(json.dumps(metadata, indent=2, separators=(\",\", \": \"))))", " try:\n os.remove(metadata_path_yaml)\n except Exception:\n self._logger.exception(f\"Error while removing .metadata.yaml from {path}\")", " @contextmanager\n def _get_metadata_lock(self, path):\n with self._metadata_lock_mutex:\n if path not in self._metadata_locks:\n import threading", " self._metadata_locks[path] = (0, threading.RLock())", " counter, lock = self._metadata_locks[path]\n counter += 1\n self._metadata_locks[path] = (counter, lock)", " yield lock", " with self._metadata_lock_mutex:\n counter = self._metadata_locks[path][0]\n counter -= 1\n if counter <= 0:\n del self._metadata_locks[path]\n else:\n self._metadata_locks[path] = (counter, lock)", " @contextmanager\n def _get_persisted_metadata_lock(self, path):\n with self._persisted_metadata_lock_mutex:\n if path not in self._persisted_metadata_locks:\n import threading", " self._persisted_metadata_locks[path] = (0, threading.RLock())", " counter, lock = self._persisted_metadata_locks[path]\n counter += 1\n self._persisted_metadata_locks[path] = (counter, lock)", " yield lock", " with self._persisted_metadata_lock_mutex:\n counter = self._persisted_metadata_locks[path][0]\n counter -= 1\n if counter <= 0:\n del self._persisted_metadata_locks[path]\n else:\n self._persisted_metadata_locks[path] = (counter, lock)" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [984, 842, 1177], "buggy_code_start_loc": [956, 42, 1141], "filenames": ["src/octoprint/filemanager/storage.py", "src/octoprint/server/__init__.py", "src/octoprint/server/api/files.py"], "fixing_code_end_loc": [997, 854, 1190], "fixing_code_start_loc": [957, 43, 1141], "message": "Unrestricted Upload of File with Dangerous Type in GitHub repository octoprint/octoprint prior to 1.8.3.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:octoprint:octoprint:*:*:*:*:*:*:*:*", "matchCriteriaId": "900F81F7-9FC4-44CE-ABD6-1E82DC120B4B", "versionEndExcluding": "1.8.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Unrestricted Upload of File with Dangerous Type in GitHub repository octoprint/octoprint prior to 1.8.3."}, {"lang": "es", "value": "Una Descarga sin Restricciones de Archivos de Tipo Peligroso en el repositorio GitHub octoprint/octoprint versiones anteriores a 1.8.3"}], "evaluatorComment": null, "id": "CVE-2022-2872", "lastModified": "2022-09-23T17:58:22.120", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:L/UI:R/S:U/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 1.2, "impactScore": 2.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-09-21T10:15:09.327", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/octoprint/octoprint/commit/3e3c11811e216fb371a33e28412df83f9701e5b0"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/b966c74d-6f3f-49fe-b40a-eaf25e362c56"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-434"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/octoprint/octoprint/commit/3e3c11811e216fb371a33e28412df83f9701e5b0"}, "type": "CWE-434"}
328
Determine whether the {function_name} code is vulnerable or not.
[ "__author__ = \"Gina Häußge <osd@foosel.net>\"\n__license__ = \"GNU Affero General Public License http://www.gnu.org/licenses/agpl.html\"\n__copyright__ = \"Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License\"", "import atexit\nimport base64\nimport functools\nimport logging\nimport logging.config\nimport mimetypes\nimport os\nimport re\nimport signal\nimport sys\nimport time\nimport uuid # noqa: F401\nfrom collections import OrderedDict, defaultdict", "from babel import Locale\nfrom flask import ( # noqa: F401\n Blueprint,\n Flask,\n Request,\n Response,\n current_app,\n g,\n make_response,\n request,\n session,\n)\nfrom flask_assets import Bundle, Environment\nfrom flask_babel import Babel, gettext, ngettext # noqa: F401\nfrom flask_login import ( # noqa: F401\n LoginManager,\n current_user,\n session_protected,\n user_logged_out,\n)\nfrom watchdog.observers import Observer\nfrom watchdog.observers.polling import PollingObserver\nfrom werkzeug.exceptions import HTTPException\n", "", "import octoprint.util\nimport octoprint.util.net\nfrom octoprint.server import util\nfrom octoprint.systemcommands import system_command_manager\nfrom octoprint.util.json import JsonEncoding\nfrom octoprint.vendor.flask_principal import ( # noqa: F401\n AnonymousIdentity,\n Identity,\n Permission,\n Principal,\n RoleNeed,\n UserNeed,\n identity_changed,\n identity_loaded,\n)\nfrom octoprint.vendor.sockjs.tornado import SockJSRouter", "try:\n import fcntl\nexcept ImportError:\n fcntl = None", "SUCCESS = {}\nNO_CONTENT = (\"\", 204, {\"Content-Type\": \"text/plain\"})\nNOT_MODIFIED = (\"Not Modified\", 304, {\"Content-Type\": \"text/plain\"})", "app = Flask(\"octoprint\")", "assets = None\nbabel = None\nlimiter = None\ndebug = False\nsafe_mode = False", "printer = None\nprinterProfileManager = None\nfileManager = None\nslicingManager = None\nanalysisQueue = None\nuserManager = None\npermissionManager = None\ngroupManager = None\neventManager = None\nloginManager = None\npluginManager = None\npluginLifecycleManager = None\npreemptiveCache = None\njsonEncoder = None\njsonDecoder = None\nconnectivityChecker = None\nenvironmentDetector = None", "principals = Principal(app)", "import octoprint.access.groups as groups # noqa: E402\nimport octoprint.access.permissions as permissions # noqa: E402", "# we set admin_permission to a GroupPermission with the default admin group\nadmin_permission = octoprint.util.variable_deprecated(\n \"admin_permission has been deprecated, \" \"please use individual Permissions instead\",\n since=\"1.4.0\",\n)(groups.GroupPermission(groups.ADMIN_GROUP))", "# we set user_permission to a GroupPermission with the default user group\nuser_permission = octoprint.util.variable_deprecated(\n \"user_permission has been deprecated, \" \"please use individual Permissions instead\",\n since=\"1.4.0\",\n)(groups.GroupPermission(groups.USER_GROUP))", "import octoprint._version # noqa: E402\nimport octoprint.access.groups as groups # noqa: E402\nimport octoprint.access.users as users # noqa: E402\nimport octoprint.events as events # noqa: E402\nimport octoprint.filemanager.analysis # noqa: E402\nimport octoprint.filemanager.storage # noqa: E402\nimport octoprint.plugin # noqa: E402\nimport octoprint.slicing # noqa: E402\nimport octoprint.timelapse # noqa: E402", "# only import further octoprint stuff down here, as it might depend on things defined above to be initialized already\nfrom octoprint import __branch__, __display_version__, __revision__, __version__\nfrom octoprint.printer.profile import PrinterProfileManager\nfrom octoprint.printer.standard import Printer\nfrom octoprint.server.util import (\n corsRequestHandler,\n corsResponseHandler,\n loginFromApiKeyRequestHandler,\n requireLoginRequestHandler,\n)\nfrom octoprint.server.util.flask import PreemptiveCache\nfrom octoprint.settings import settings", "VERSION = __version__\nBRANCH = __branch__\nDISPLAY_VERSION = __display_version__\nREVISION = __revision__", "LOCALES = []\nLANGUAGES = set()", "\n@identity_loaded.connect_via(app)\ndef on_identity_loaded(sender, identity):\n user = load_user(identity.id)\n if user is None:\n user = userManager.anonymous_user_factory()", " identity.provides.add(UserNeed(user.get_id()))\n for need in user.needs:\n identity.provides.add(need)", "\ndef _clear_identity(sender):\n # Remove session keys set by Flask-Principal\n for key in (\"identity.id\", \"identity.name\", \"identity.auth_type\"):\n session.pop(key, None)", " # switch to anonymous identity\n identity_changed.send(sender, identity=AnonymousIdentity())", "\n@session_protected.connect_via(app)\ndef on_session_protected(sender):\n # session was deleted by session protection, that means the user is no more and we need to clear our identity\n if session.get(\"remember\", None) == \"clear\":\n _clear_identity(sender)", "\n@user_logged_out.connect_via(app)\ndef on_user_logged_out(sender, user=None):\n # user was logged out, clear identity\n _clear_identity(sender)", "\ndef load_user(id):\n if id is None:\n return None", " if id == \"_api\":\n return userManager.api_user_factory()", " if session and \"usersession.id\" in session:\n sessionid = session[\"usersession.id\"]\n else:\n sessionid = None", " if sessionid:\n user = userManager.find_user(userid=id, session=sessionid)\n else:\n user = userManager.find_user(userid=id)", " if user and user.is_active:\n return user", " return None", "\ndef load_user_from_request(request):\n user = None", " if settings().getBoolean([\"accessControl\", \"trustBasicAuthentication\"]):\n # Basic Authentication?\n user = util.get_user_for_authorization_header(\n request.headers.get(\"Authorization\")\n )", " if settings().getBoolean([\"accessControl\", \"trustRemoteUser\"]):\n # Remote user header?\n user = util.get_user_for_remote_user_header(request)", " return user", "\ndef unauthorized_user():\n from flask import abort", " abort(403)", "\n# ~~ startup code", "\nclass Server:\n def __init__(\n self,\n settings=None,\n plugin_manager=None,\n connectivity_checker=None,\n environment_detector=None,\n event_manager=None,\n host=None,\n port=None,\n v6_only=False,\n debug=False,\n safe_mode=False,\n allow_root=False,\n octoprint_daemon=None,\n ):\n self._settings = settings\n self._plugin_manager = plugin_manager\n self._connectivity_checker = connectivity_checker\n self._environment_detector = environment_detector\n self._event_manager = event_manager\n self._host = host\n self._port = port\n self._v6_only = v6_only\n self._debug = debug\n self._safe_mode = safe_mode\n self._allow_root = allow_root\n self._octoprint_daemon = octoprint_daemon\n self._server = None", " self._logger = None", " self._lifecycle_callbacks = defaultdict(list)", " self._intermediary_server = None", " def run(self):\n if not self._allow_root:\n self._check_for_root()", " if self._settings is None:\n self._settings = settings()", " if not self._settings.getBoolean([\"server\", \"ignoreIncompleteStartup\"]):\n self._settings.setBoolean([\"server\", \"incompleteStartup\"], True)\n self._settings.save()", " if self._plugin_manager is None:\n self._plugin_manager = octoprint.plugin.plugin_manager()", " global app\n global babel", " global printer\n global printerProfileManager\n global fileManager\n global slicingManager\n global analysisQueue\n global userManager\n global permissionManager\n global groupManager\n global eventManager\n global loginManager\n global pluginManager\n global pluginLifecycleManager\n global preemptiveCache\n global jsonEncoder\n global jsonDecoder\n global connectivityChecker\n global environmentDetector\n global debug\n global safe_mode", " from tornado.ioloop import IOLoop\n from tornado.web import Application", " debug = self._debug\n safe_mode = self._safe_mode", " if safe_mode:\n self._log_safe_mode_start(safe_mode)", " if self._v6_only and not octoprint.util.net.HAS_V6:\n raise RuntimeError(\n \"IPv6 only mode configured but system doesn't support IPv6\"\n )", " if self._host is None:\n host = self._settings.get([\"server\", \"host\"])\n if host is None:\n if octoprint.util.net.HAS_V6:\n host = \"::\"\n else:\n host = \"0.0.0.0\"", " self._host = host", " if \":\" in self._host and not octoprint.util.net.HAS_V6:\n raise RuntimeError(\n \"IPv6 host address {!r} configured but system doesn't support IPv6\".format(\n self._host\n )\n )", " if self._port is None:\n self._port = self._settings.getInt([\"server\", \"port\"])\n if self._port is None:\n self._port = 5000", " self._logger = logging.getLogger(__name__)\n self._setup_heartbeat_logging()\n pluginManager = self._plugin_manager", " # monkey patch/fix some stuff\n util.tornado.fix_json_encode()\n util.tornado.fix_websocket_check_origin()\n util.tornado.enable_per_message_deflate_extension()\n util.flask.fix_flask_jsonify()", " self._setup_mimetypes()", " additional_translation_folders = []\n if not safe_mode:\n additional_translation_folders += [\n self._settings.getBaseFolder(\"translations\")\n ]\n util.flask.enable_additional_translations(\n additional_folders=additional_translation_folders\n )", " # setup app\n self._setup_app(app)", " # setup i18n\n self._setup_i18n(app)", " if self._settings.getBoolean([\"serial\", \"log\"]):\n # enable debug logging to serial.log\n logging.getLogger(\"SERIAL\").setLevel(logging.DEBUG)", " if self._settings.getBoolean([\"devel\", \"pluginTimings\"]):\n # enable plugin timings log\n logging.getLogger(\"PLUGIN_TIMINGS\").setLevel(logging.DEBUG)", " # start the intermediary server\n self._start_intermediary_server()", " ### IMPORTANT!\n ###\n ### Best do not start any subprocesses until the intermediary server shuts down again or they MIGHT inherit the\n ### open port and prevent us from firing up Tornado later.\n ###\n ### The intermediary server's socket should have the CLOSE_EXEC flag (or its equivalent) set where possible, but\n ### we can only do that if fcntl is available or we are on Windows, so better safe than sorry.\n ###\n ### See also issues #2035 and #2090", " systemCommandManager = system_command_manager()\n printerProfileManager = PrinterProfileManager()\n eventManager = self._event_manager", " analysis_queue_factories = {\n \"gcode\": octoprint.filemanager.analysis.GcodeAnalysisQueue\n }\n analysis_queue_hooks = pluginManager.get_hooks(\n \"octoprint.filemanager.analysis.factory\"\n )\n for name, hook in analysis_queue_hooks.items():\n try:\n additional_factories = hook()\n analysis_queue_factories.update(**additional_factories)\n except Exception:\n self._logger.exception(\n f\"Error while processing analysis queues from {name}\",\n extra={\"plugin\": name},\n )\n analysisQueue = octoprint.filemanager.analysis.AnalysisQueue(\n analysis_queue_factories\n )", " slicingManager = octoprint.slicing.SlicingManager(\n self._settings.getBaseFolder(\"slicingProfiles\"), printerProfileManager\n )", " storage_managers = {}\n storage_managers[\n octoprint.filemanager.FileDestinations.LOCAL\n ] = octoprint.filemanager.storage.LocalFileStorage(\n self._settings.getBaseFolder(\"uploads\"),\n really_universal=self._settings.getBoolean(\n [\"feature\", \"enforceReallyUniversalFilenames\"]\n ),\n )", " fileManager = octoprint.filemanager.FileManager(\n analysisQueue,\n slicingManager,\n printerProfileManager,\n initial_storage_managers=storage_managers,\n )\n pluginLifecycleManager = LifecycleManager(pluginManager)\n preemptiveCache = PreemptiveCache(\n os.path.join(\n self._settings.getBaseFolder(\"data\"), \"preemptive_cache_config.yaml\"\n )\n )", " JsonEncoding.add_encoder(users.User, lambda obj: obj.as_dict())\n JsonEncoding.add_encoder(groups.Group, lambda obj: obj.as_dict())\n JsonEncoding.add_encoder(\n permissions.OctoPrintPermission, lambda obj: obj.as_dict()\n )", " # start regular check if we are connected to the internet\n def on_connectivity_change(old_value, new_value):\n eventManager.fire(\n events.Events.CONNECTIVITY_CHANGED,\n payload={\"old\": old_value, \"new\": new_value},\n )", " connectivityChecker = self._connectivity_checker\n environmentDetector = self._environment_detector", " def on_settings_update(*args, **kwargs):\n # make sure our connectivity checker runs with the latest settings\n connectivityEnabled = self._settings.getBoolean(\n [\"server\", \"onlineCheck\", \"enabled\"]\n )\n connectivityInterval = self._settings.getInt(\n [\"server\", \"onlineCheck\", \"interval\"]\n )\n connectivityHost = self._settings.get([\"server\", \"onlineCheck\", \"host\"])\n connectivityPort = self._settings.getInt([\"server\", \"onlineCheck\", \"port\"])\n connectivityName = self._settings.get([\"server\", \"onlineCheck\", \"name\"])", " if (\n connectivityChecker.enabled != connectivityEnabled\n or connectivityChecker.interval != connectivityInterval\n or connectivityChecker.host != connectivityHost\n or connectivityChecker.port != connectivityPort\n or connectivityChecker.name != connectivityName\n ):\n connectivityChecker.enabled = connectivityEnabled\n connectivityChecker.interval = connectivityInterval\n connectivityChecker.host = connectivityHost\n connectivityChecker.port = connectivityPort\n connectivityChecker.name = connectivityName\n connectivityChecker.check_immediately()", " eventManager.subscribe(events.Events.SETTINGS_UPDATED, on_settings_update)", " components = {\n \"plugin_manager\": pluginManager,\n \"printer_profile_manager\": printerProfileManager,\n \"event_bus\": eventManager,\n \"analysis_queue\": analysisQueue,\n \"slicing_manager\": slicingManager,\n \"file_manager\": fileManager,\n \"plugin_lifecycle_manager\": pluginLifecycleManager,\n \"preemptive_cache\": preemptiveCache,\n \"json_encoder\": jsonEncoder,\n \"json_decoder\": jsonDecoder,\n \"connectivity_checker\": connectivityChecker,\n \"environment_detector\": self._environment_detector,\n \"system_commands\": systemCommandManager,\n }", " # ~~ setup access control", " # get additional permissions from plugins\n self._setup_plugin_permissions()", " # create group manager instance\n group_manager_factories = pluginManager.get_hooks(\n \"octoprint.access.groups.factory\"\n )\n for name, factory in group_manager_factories.items():\n try:\n groupManager = factory(components, self._settings)\n if groupManager is not None:\n self._logger.debug(\n f\"Created group manager instance from factory {name}\"\n )\n break\n except Exception:\n self._logger.exception(\n \"Error while creating group manager instance from factory {}\".format(\n name\n )\n )\n else:\n group_manager_name = self._settings.get([\"accessControl\", \"groupManager\"])\n try:\n clazz = octoprint.util.get_class(group_manager_name)\n groupManager = clazz()\n except AttributeError:\n self._logger.exception(\n \"Could not instantiate group manager {}, \"\n \"falling back to FilebasedGroupManager!\".format(group_manager_name)\n )\n groupManager = octoprint.access.groups.FilebasedGroupManager()\n components.update({\"group_manager\": groupManager})", " # create user manager instance\n user_manager_factories = pluginManager.get_hooks(\n \"octoprint.users.factory\"\n ) # legacy, set first so that new wins\n user_manager_factories.update(\n pluginManager.get_hooks(\"octoprint.access.users.factory\")\n )\n for name, factory in user_manager_factories.items():\n try:\n userManager = factory(components, self._settings)\n if userManager is not None:\n self._logger.debug(\n f\"Created user manager instance from factory {name}\"\n )\n break\n except Exception:\n self._logger.exception(\n \"Error while creating user manager instance from factory {}\".format(\n name\n ),\n extra={\"plugin\": name},\n )\n else:\n user_manager_name = self._settings.get([\"accessControl\", \"userManager\"])\n try:\n clazz = octoprint.util.get_class(user_manager_name)\n userManager = clazz(groupManager)\n except octoprint.access.users.CorruptUserStorage:\n raise\n except Exception:\n self._logger.exception(\n \"Could not instantiate user manager {}, \"\n \"falling back to FilebasedUserManager!\".format(user_manager_name)\n )\n userManager = octoprint.access.users.FilebasedUserManager(groupManager)\n components.update({\"user_manager\": userManager})", " # create printer instance\n printer_factories = pluginManager.get_hooks(\"octoprint.printer.factory\")\n for name, factory in printer_factories.items():\n try:\n printer = factory(components)\n if printer is not None:\n self._logger.debug(f\"Created printer instance from factory {name}\")\n break\n except Exception:\n self._logger.exception(\n f\"Error while creating printer instance from factory {name}\",\n extra={\"plugin\": name},\n )\n else:\n printer = Printer(fileManager, analysisQueue, printerProfileManager)\n components.update({\"printer\": printer})", " from octoprint import (\n init_custom_events,\n init_settings_plugin_config_migration_and_cleanup,\n )\n from octoprint import octoprint_plugin_inject_factory as opif\n from octoprint import settings_plugin_inject_factory as spif", " init_custom_events(pluginManager)", " octoprint_plugin_inject_factory = opif(self._settings, components)\n settings_plugin_inject_factory = spif(self._settings)", " pluginManager.implementation_inject_factories = [\n octoprint_plugin_inject_factory,\n settings_plugin_inject_factory,\n ]\n pluginManager.initialize_implementations()", " init_settings_plugin_config_migration_and_cleanup(pluginManager)", " pluginManager.log_all_plugins()", " # log environment data now\n self._environment_detector.log_detected_environment()", " # initialize file manager and register it for changes in the registered plugins\n fileManager.initialize()\n pluginLifecycleManager.add_callback(\n [\"enabled\", \"disabled\"], lambda name, plugin: fileManager.reload_plugins()\n )", " # initialize slicing manager and register it for changes in the registered plugins\n slicingManager.initialize()\n pluginLifecycleManager.add_callback(\n [\"enabled\", \"disabled\"], lambda name, plugin: slicingManager.reload_slicers()\n )", " # setup jinja2\n self._setup_jinja2()", " # setup assets\n self._setup_assets()", " # configure timelapse\n octoprint.timelapse.valid_timelapse(\"test\")\n octoprint.timelapse.configure_timelapse()", " # setup command triggers\n events.CommandTrigger(printer)\n if self._debug:\n events.DebugEventListener()", " # setup login manager\n self._setup_login_manager()", " # register API blueprint\n self._setup_blueprints()", " ## Tornado initialization starts here", " ioloop = IOLoop()\n ioloop.install()", " enable_cors = settings().getBoolean([\"api\", \"allowCrossOrigin\"])", " self._router = SockJSRouter(\n self._create_socket_connection,\n \"/sockjs\",\n session_kls=util.sockjs.ThreadSafeSession,\n user_settings={\n \"websocket_allow_origin\": \"*\" if enable_cors else \"\",\n \"jsessionid\": False,\n \"sockjs_url\": \"../../static/js/lib/sockjs.min.js\",\n },\n )", " upload_suffixes = {\n \"name\": self._settings.get([\"server\", \"uploads\", \"nameSuffix\"]),\n \"path\": self._settings.get([\"server\", \"uploads\", \"pathSuffix\"]),\n }", " def mime_type_guesser(path):\n from octoprint.filemanager import get_mime_type", " return get_mime_type(path)", " def download_name_generator(path):\n metadata = fileManager.get_metadata(\"local\", path)\n if metadata and \"display\" in metadata:\n return metadata[\"display\"]", " download_handler_kwargs = {\"as_attachment\": True, \"allow_client_caching\": False}", " additional_mime_types = {\"mime_type_guesser\": mime_type_guesser}", " ##~~ Permission validators", " access_validators_from_plugins = []\n for plugin, hook in pluginManager.get_hooks(\n \"octoprint.server.http.access_validator\"\n ).items():\n try:\n access_validators_from_plugins.append(\n util.tornado.access_validation_factory(app, hook)\n )\n except Exception:\n self._logger.exception(\n \"Error while adding tornado access validator from plugin {}\".format(\n plugin\n ),\n extra={\"plugin\": plugin},\n )", " timelapse_validators = [\n util.tornado.access_validation_factory(\n app,\n util.flask.permission_validator,\n permissions.Permissions.TIMELAPSE_LIST,\n ),\n ] + access_validators_from_plugins\n download_validators = [\n util.tornado.access_validation_factory(\n app,\n util.flask.permission_validator,\n permissions.Permissions.FILES_DOWNLOAD,\n ),\n ] + access_validators_from_plugins\n log_validators = [\n util.tornado.access_validation_factory(\n app,\n util.flask.permission_validator,\n permissions.Permissions.PLUGIN_LOGGING_MANAGE,\n ),\n ] + access_validators_from_plugins\n camera_validators = [\n util.tornado.access_validation_factory(\n app, util.flask.permission_validator, permissions.Permissions.WEBCAM\n ),\n ] + access_validators_from_plugins\n systeminfo_validators = [\n util.tornado.access_validation_factory(\n app, util.flask.permission_validator, permissions.Permissions.SYSTEM\n )\n ] + access_validators_from_plugins", " timelapse_permission_validator = {\n \"access_validation\": util.tornado.validation_chain(*timelapse_validators)\n }\n download_permission_validator = {\n \"access_validation\": util.tornado.validation_chain(*download_validators)\n }\n log_permission_validator = {\n \"access_validation\": util.tornado.validation_chain(*log_validators)\n }\n camera_permission_validator = {\n \"access_validation\": util.tornado.validation_chain(*camera_validators)\n }\n systeminfo_permission_validator = {\n \"access_validation\": util.tornado.validation_chain(*systeminfo_validators)\n }", " no_hidden_files_validator = {\n \"path_validation\": util.tornado.path_validation_factory(\n lambda path: not octoprint.util.is_hidden_path(path), status_code=404", "", " )\n }", " valid_timelapse = lambda path: not octoprint.util.is_hidden_path(path) and (\n octoprint.timelapse.valid_timelapse(path)\n or octoprint.timelapse.valid_timelapse_thumbnail(path)\n )\n timelapse_path_validator = {\n \"path_validation\": util.tornado.path_validation_factory(\n valid_timelapse,\n status_code=404,\n )\n }\n timelapses_path_validator = {\n \"path_validation\": util.tornado.path_validation_factory(\n lambda path: valid_timelapse(path)\n and os.path.realpath(os.path.abspath(path)).startswith(\n settings().getBaseFolder(\"timelapse\")\n ),\n status_code=400,\n )\n }", " valid_log = lambda path: not octoprint.util.is_hidden_path(\n path\n ) and path.endswith(\".log\")\n log_path_validator = {\n \"path_validation\": util.tornado.path_validation_factory(\n valid_log,\n status_code=404,\n )\n }\n logs_path_validator = {\n \"path_validation\": util.tornado.path_validation_factory(\n lambda path: valid_log(path)\n and os.path.realpath(os.path.abspath(path)).startswith(\n settings().getBaseFolder(\"logs\")\n ),\n status_code=400,\n )\n }", " def joined_dict(*dicts):\n if not len(dicts):\n return {}", " joined = {}\n for d in dicts:\n joined.update(d)\n return joined", " util.tornado.RequestlessExceptionLoggingMixin.LOG_REQUEST = debug\n util.tornado.CorsSupportMixin.ENABLE_CORS = enable_cors", " server_routes = self._router.urls + [\n # various downloads\n # .mpg and .mp4 timelapses:\n (\n r\"/downloads/timelapse/(.*)\",\n util.tornado.LargeResponseHandler,\n joined_dict(\n {\"path\": self._settings.getBaseFolder(\"timelapse\")},\n timelapse_permission_validator,\n download_handler_kwargs,\n timelapse_path_validator,\n ),\n ),\n # zipped timelapse bundles\n (\n r\"/downloads/timelapses\",\n util.tornado.DynamicZipBundleHandler,\n joined_dict(\n {\n \"as_attachment\": True,\n \"attachment_name\": \"octoprint-timelapses.zip\",\n \"path_processor\": lambda x: (\n x,\n os.path.join(self._settings.getBaseFolder(\"timelapse\"), x),\n ),\n },\n timelapse_permission_validator,\n timelapses_path_validator,\n ),\n ),\n # uploaded printables\n (\n r\"/downloads/files/local/(.*)\",\n util.tornado.LargeResponseHandler,\n joined_dict(\n {\n \"path\": self._settings.getBaseFolder(\"uploads\"),\n \"as_attachment\": True,\n \"name_generator\": download_name_generator,\n },\n download_permission_validator,\n download_handler_kwargs,\n no_hidden_files_validator,", "", " additional_mime_types,\n ),\n ),\n # log files\n (\n r\"/downloads/logs/([^/]*)\",\n util.tornado.LargeResponseHandler,\n joined_dict(\n {\n \"path\": self._settings.getBaseFolder(\"logs\"),\n \"mime_type_guesser\": lambda *args, **kwargs: \"text/plain\",\n \"stream_body\": True,\n },\n download_handler_kwargs,\n log_permission_validator,\n log_path_validator,\n ),\n ),\n # zipped log file bundles\n (\n r\"/downloads/logs\",\n util.tornado.DynamicZipBundleHandler,\n joined_dict(\n {\n \"as_attachment\": True,\n \"attachment_name\": \"octoprint-logs.zip\",\n \"path_processor\": lambda x: (\n x,\n os.path.join(self._settings.getBaseFolder(\"logs\"), x),\n ),\n },\n log_permission_validator,\n logs_path_validator,\n ),\n ),\n # system info bundle\n (\n r\"/downloads/systeminfo.zip\",\n util.tornado.SystemInfoBundleHandler,\n systeminfo_permission_validator,\n ),\n # camera snapshot\n (\n r\"/downloads/camera/current\",\n util.tornado.UrlProxyHandler,\n joined_dict(\n {\n \"url\": self._settings.get([\"webcam\", \"snapshot\"]),\n \"as_attachment\": True,\n },\n camera_permission_validator,\n ),\n ),\n # generated webassets\n (\n r\"/static/webassets/(.*)\",\n util.tornado.LargeResponseHandler,\n {\n \"path\": os.path.join(\n self._settings.getBaseFolder(\"generated\"), \"webassets\"\n ),\n \"is_pre_compressed\": True,\n },\n ),\n # online indicators - text file with \"online\" as content and a transparent gif\n (r\"/online.txt\", util.tornado.StaticDataHandler, {\"data\": \"online\\n\"}),\n (\n r\"/online.gif\",\n util.tornado.StaticDataHandler,\n {\n \"data\": bytes(\n base64.b64decode(\n \"R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7\"\n )\n ),\n \"content_type\": \"image/gif\",\n },\n ),\n # deprecated endpoints\n (\n r\"/api/logs\",\n util.tornado.DeprecatedEndpointHandler,\n {\"url\": \"/plugin/logging/logs\"},\n ),\n (\n r\"/api/logs/(.*)\",\n util.tornado.DeprecatedEndpointHandler,\n {\"url\": \"/plugin/logging/logs/{0}\"},\n ),\n ]", " # fetch additional routes from plugins\n for name, hook in pluginManager.get_hooks(\"octoprint.server.http.routes\").items():\n try:\n result = hook(list(server_routes))\n except Exception:\n self._logger.exception(\n f\"There was an error while retrieving additional \"\n f\"server routes from plugin hook {name}\",\n extra={\"plugin\": name},\n )\n else:\n if isinstance(result, (list, tuple)):\n for entry in result:\n if not isinstance(entry, tuple) or not len(entry) == 3:\n continue\n if not isinstance(entry[0], str):\n continue\n if not isinstance(entry[2], dict):\n continue", " route, handler, kwargs = entry\n route = r\"/plugin/{name}/{route}\".format(\n name=name,\n route=route if not route.startswith(\"/\") else route[1:],\n )", " self._logger.debug(\n f\"Adding additional route {route} handled by handler {handler} and with additional arguments {kwargs!r}\"\n )\n server_routes.append((route, handler, kwargs))", " headers = {\n \"X-Robots-Tag\": \"noindex, nofollow, noimageindex\",\n \"X-Content-Type-Options\": \"nosniff\",\n }\n if not settings().getBoolean([\"server\", \"allowFraming\"]):\n headers[\"X-Frame-Options\"] = \"sameorigin\"", " removed_headers = [\"Server\"]", " server_routes.append(\n (\n r\".*\",\n util.tornado.UploadStorageFallbackHandler,\n {\n \"fallback\": util.tornado.WsgiInputContainer(\n app.wsgi_app, headers=headers, removed_headers=removed_headers\n ),\n \"file_prefix\": \"octoprint-file-upload-\",\n \"file_suffix\": \".tmp\",\n \"suffixes\": upload_suffixes,\n },\n )\n )", " transforms = [\n util.tornado.GlobalHeaderTransform.for_headers(\n \"OctoPrintGlobalHeaderTransform\",\n headers=headers,\n removed_headers=removed_headers,\n )\n ]", " self._tornado_app = Application(handlers=server_routes, transforms=transforms)\n max_body_sizes = [\n (\n \"POST\",\n r\"/api/files/([^/]*)\",\n self._settings.getInt([\"server\", \"uploads\", \"maxSize\"]),\n ),\n (\"POST\", r\"/api/languages\", 5 * 1024 * 1024),\n ]", " # allow plugins to extend allowed maximum body sizes\n for name, hook in pluginManager.get_hooks(\n \"octoprint.server.http.bodysize\"\n ).items():\n try:\n result = hook(list(max_body_sizes))\n except Exception:\n self._logger.exception(\n f\"There was an error while retrieving additional \"\n f\"upload sizes from plugin hook {name}\",\n extra={\"plugin\": name},\n )\n else:\n if isinstance(result, (list, tuple)):\n for entry in result:\n if not isinstance(entry, tuple) or not len(entry) == 3:\n continue\n if (\n entry[0]\n not in util.tornado.UploadStorageFallbackHandler.BODY_METHODS\n ):\n continue\n if not isinstance(entry[2], int):\n continue", " method, route, size = entry\n route = r\"/plugin/{name}/{route}\".format(\n name=name,\n route=route if not route.startswith(\"/\") else route[1:],\n )", " self._logger.debug(\n f\"Adding maximum body size of {size}B for {method} requests to {route})\"\n )\n max_body_sizes.append((method, route, size))", " self._stop_intermediary_server()", " # initialize and bind the server\n trusted_downstream = self._settings.get(\n [\"server\", \"reverseProxy\", \"trustedDownstream\"]\n )\n if not isinstance(trusted_downstream, list):\n self._logger.warning(\n \"server.reverseProxy.trustedDownstream is not a list, skipping\"\n )\n trusted_downstream = []", " server_kwargs = {\n \"max_body_sizes\": max_body_sizes,\n \"default_max_body_size\": self._settings.getInt([\"server\", \"maxSize\"]),\n \"xheaders\": True,\n \"trusted_downstream\": trusted_downstream,\n }\n if sys.platform == \"win32\":\n # set 10min idle timeout under windows to hopefully make #2916 less likely\n server_kwargs.update({\"idle_connection_timeout\": 600})", " self._server = util.tornado.CustomHTTPServer(self._tornado_app, **server_kwargs)", " listening_address = self._host\n if self._host == \"::\" and not self._v6_only:\n # special case - tornado only listens on v4 _and_ v6 if we use None as address\n listening_address = None", " self._server.listen(self._port, address=listening_address)", " ### From now on it's ok to launch subprocesses again", " eventManager.fire(events.Events.STARTUP)", " # analysis backlog\n fileManager.process_backlog()", " # auto connect\n if self._settings.getBoolean([\"serial\", \"autoconnect\"]):\n self._logger.info(\n \"Autoconnect on startup is configured, trying to connect to the printer...\"\n )\n try:\n (port, baudrate) = (\n self._settings.get([\"serial\", \"port\"]),\n self._settings.getInt([\"serial\", \"baudrate\"]),\n )\n printer_profile = printerProfileManager.get_default()\n connectionOptions = printer.__class__.get_connection_options()\n if port in connectionOptions[\"ports\"] or port == \"AUTO\" or port is None:\n self._logger.info(\n f\"Trying to connect to configured serial port {port}\"\n )\n printer.connect(\n port=port,\n baudrate=baudrate,\n profile=printer_profile[\"id\"]\n if \"id\" in printer_profile\n else \"_default\",\n )\n else:\n self._logger.info(\n \"Could not find configured serial port {} in the system, cannot automatically connect to a non existing printer. Is it plugged in and booted up yet?\"\n )\n except Exception:\n self._logger.exception(\n \"Something went wrong while attempting to automatically connect to the printer\"\n )", " # start up watchdogs\n try:\n watched = self._settings.getBaseFolder(\"watched\")\n watchdog_handler = util.watchdog.GcodeWatchdogHandler(fileManager, printer)\n watchdog_handler.initial_scan(watched)", " if self._settings.getBoolean([\"feature\", \"pollWatched\"]):\n # use less performant polling observer if explicitly configured\n observer = PollingObserver()\n else:\n # use os default\n observer = Observer()", " observer.schedule(watchdog_handler, watched, recursive=True)\n observer.start()\n except Exception:\n self._logger.exception(\"Error starting watched folder observer\")", " # run our startup plugins\n octoprint.plugin.call_plugin(\n octoprint.plugin.StartupPlugin,\n \"on_startup\",\n args=(self._host, self._port),\n sorting_context=\"StartupPlugin.on_startup\",\n )", " def call_on_startup(name, plugin):\n implementation = plugin.get_implementation(octoprint.plugin.StartupPlugin)\n if implementation is None:\n return\n implementation.on_startup(self._host, self._port)", " pluginLifecycleManager.add_callback(\"enabled\", call_on_startup)", " # prepare our after startup function\n def on_after_startup():\n if self._host == \"::\":\n if self._v6_only:\n # only v6\n self._logger.info(f\"Listening on http://[::]:{self._port}\")\n else:\n # all v4 and v6\n self._logger.info(\n \"Listening on http://0.0.0.0:{port} and http://[::]:{port}\".format(\n port=self._port\n )\n )\n else:\n self._logger.info(\n \"Listening on http://{}:{}\".format(\n self._host if \":\" not in self._host else \"[\" + self._host + \"]\",\n self._port,\n )\n )", " if safe_mode and self._settings.getBoolean([\"server\", \"startOnceInSafeMode\"]):\n self._logger.info(\n \"Server started successfully in safe mode as requested from config, removing flag\"\n )\n self._settings.setBoolean([\"server\", \"startOnceInSafeMode\"], False)\n self._settings.save()", " # now this is somewhat ugly, but the issue is the following: startup plugins might want to do things for\n # which they need the server to be already alive (e.g. for being able to resolve urls, such as favicons\n # or service xmls or the like). While they are working though the ioloop would block. Therefore we'll\n # create a single use thread in which to perform our after-startup-tasks, start that and hand back\n # control to the ioloop\n def work():\n octoprint.plugin.call_plugin(\n octoprint.plugin.StartupPlugin,\n \"on_after_startup\",\n sorting_context=\"StartupPlugin.on_after_startup\",\n )", " def call_on_after_startup(name, plugin):\n implementation = plugin.get_implementation(\n octoprint.plugin.StartupPlugin\n )\n if implementation is None:\n return\n implementation.on_after_startup()", " pluginLifecycleManager.add_callback(\"enabled\", call_on_after_startup)", " # if there was a rogue plugin we wouldn't even have made it here, so remove startup triggered safe mode\n # flag again...\n self._settings.setBoolean([\"server\", \"incompleteStartup\"], False)\n self._settings.save()", " # make a backup of the current config\n self._settings.backup(ext=\"backup\")", " # when we are through with that we also run our preemptive cache\n if settings().getBoolean([\"devel\", \"cache\", \"preemptive\"]):\n self._execute_preemptive_flask_caching(preemptiveCache)", " import threading", " threading.Thread(target=work).start()", " ioloop.add_callback(on_after_startup)", " # prepare our shutdown function\n def on_shutdown():\n # will be called on clean system exit and shutdown the watchdog observer and call the on_shutdown methods\n # on all registered ShutdownPlugins\n self._logger.info(\"Shutting down...\")\n observer.stop()\n observer.join()\n eventManager.fire(events.Events.SHUTDOWN)", " self._logger.info(\"Calling on_shutdown on plugins\")\n octoprint.plugin.call_plugin(\n octoprint.plugin.ShutdownPlugin,\n \"on_shutdown\",\n sorting_context=\"ShutdownPlugin.on_shutdown\",\n )", " # wait for shutdown event to be processed, but maximally for 15s\n event_timeout = 15.0\n if eventManager.join(timeout=event_timeout):\n self._logger.warning(\n \"Event loop was still busy processing after {}s, shutting down anyhow\".format(\n event_timeout\n )\n )", " if self._octoprint_daemon is not None:\n self._logger.info(\"Cleaning up daemon pidfile\")\n self._octoprint_daemon.terminated()", " self._logger.info(\"Goodbye!\")", " atexit.register(on_shutdown)", " def sigterm_handler(*args, **kwargs):\n # will stop tornado on SIGTERM, making the program exit cleanly\n def shutdown_tornado():\n self._logger.debug(\"Shutting down tornado's IOLoop...\")\n ioloop.stop()", " self._logger.debug(\"SIGTERM received...\")\n ioloop.add_callback_from_signal(shutdown_tornado)", " signal.signal(signal.SIGTERM, sigterm_handler)", " try:\n # this is the main loop - as long as tornado is running, OctoPrint is running\n ioloop.start()\n self._logger.debug(\"Tornado's IOLoop stopped\")\n except (KeyboardInterrupt, SystemExit):\n pass\n except Exception:\n self._logger.fatal(\n \"Now that is embarrassing... Something really really went wrong here. Please report this including the stacktrace below in OctoPrint's bugtracker. Thanks!\"\n )\n self._logger.exception(\"Stacktrace follows:\")", " def _log_safe_mode_start(self, self_mode):\n self_mode_file = os.path.join(\n self._settings.getBaseFolder(\"data\"), \"last_safe_mode\"\n )\n try:\n with open(self_mode_file, \"w+\", encoding=\"utf-8\") as f:\n f.write(self_mode)\n except Exception as ex:\n self._logger.warn(f\"Could not write safe mode file {self_mode_file}: {ex}\")", " def _create_socket_connection(self, session):\n global printer, fileManager, analysisQueue, userManager, eventManager, connectivityChecker\n return util.sockjs.PrinterStateConnection(\n printer,\n fileManager,\n analysisQueue,\n userManager,\n groupManager,\n eventManager,\n pluginManager,\n connectivityChecker,\n session,\n )", " def _check_for_root(self):\n if \"geteuid\" in dir(os) and os.geteuid() == 0:\n exit(\"You should not run OctoPrint as root!\")", " def _get_locale(self):\n global LANGUAGES", " if \"l10n\" in request.values:\n return Locale.negotiate([request.values[\"l10n\"]], LANGUAGES)", " if \"X-Locale\" in request.headers:\n return Locale.negotiate([request.headers[\"X-Locale\"]], LANGUAGES)", " if hasattr(g, \"identity\") and g.identity:\n userid = g.identity.id\n try:\n user_language = userManager.get_user_setting(\n userid, (\"interface\", \"language\")\n )\n if user_language is not None and not user_language == \"_default\":\n return Locale.negotiate([user_language], LANGUAGES)\n except octoprint.access.users.UnknownUser:\n pass", " default_language = self._settings.get([\"appearance\", \"defaultLanguage\"])\n if (\n default_language is not None\n and not default_language == \"_default\"\n and default_language in LANGUAGES\n ):\n return Locale.negotiate([default_language], LANGUAGES)", " return Locale.parse(request.accept_languages.best_match(LANGUAGES))", " def _setup_heartbeat_logging(self):\n logger = logging.getLogger(__name__ + \".heartbeat\")", " def log_heartbeat():\n logger.info(\"Server heartbeat <3\")", " interval = settings().getFloat([\"server\", \"heartbeat\"])\n logger.info(f\"Starting server heartbeat, {interval}s interval\")", " timer = octoprint.util.RepeatedTimer(interval, log_heartbeat)\n timer.start()", " def _setup_app(self, app):\n global limiter", " from octoprint.server.util.flask import (\n OctoPrintFlaskRequest,\n OctoPrintFlaskResponse,\n OctoPrintJsonEncoder,\n OctoPrintSessionInterface,\n PrefixAwareJinjaEnvironment,\n ReverseProxiedEnvironment,\n )", " # we must set this here because setting app.debug will access app.jinja_env\n app.jinja_environment = PrefixAwareJinjaEnvironment", " app.config[\"TEMPLATES_AUTO_RELOAD\"] = True\n app.config[\"JSONIFY_PRETTYPRINT_REGULAR\"] = False\n app.config[\"REMEMBER_COOKIE_HTTPONLY\"] = True", " # we must not set this before TEMPLATES_AUTO_RELOAD is set to True or that won't take\n app.debug = self._debug", " # setup octoprint's flask json serialization/deserialization\n app.json_encoder = OctoPrintJsonEncoder", " s = settings()", " secret_key = s.get([\"server\", \"secretKey\"])\n if not secret_key:\n import string\n from random import choice", " chars = string.ascii_lowercase + string.ascii_uppercase + string.digits\n secret_key = \"\".join(choice(chars) for _ in range(32))\n s.set([\"server\", \"secretKey\"], secret_key)\n s.save()", " app.secret_key = secret_key", " reverse_proxied = ReverseProxiedEnvironment(\n header_prefix=s.get([\"server\", \"reverseProxy\", \"prefixHeader\"]),\n header_scheme=s.get([\"server\", \"reverseProxy\", \"schemeHeader\"]),\n header_host=s.get([\"server\", \"reverseProxy\", \"hostHeader\"]),\n header_server=s.get([\"server\", \"reverseProxy\", \"serverHeader\"]),\n header_port=s.get([\"server\", \"reverseProxy\", \"portHeader\"]),\n prefix=s.get([\"server\", \"reverseProxy\", \"prefixFallback\"]),\n scheme=s.get([\"server\", \"reverseProxy\", \"schemeFallback\"]),\n host=s.get([\"server\", \"reverseProxy\", \"hostFallback\"]),\n server=s.get([\"server\", \"reverseProxy\", \"serverFallback\"]),\n port=s.get([\"server\", \"reverseProxy\", \"portFallback\"]),\n )", " OctoPrintFlaskRequest.environment_wrapper = reverse_proxied\n app.request_class = OctoPrintFlaskRequest\n app.response_class = OctoPrintFlaskResponse\n app.session_interface = OctoPrintSessionInterface()", " @app.before_request\n def before_request():\n g.locale = self._get_locale()", " # used for performance measurement\n g.start_time = time.monotonic()", " if self._debug and \"perfprofile\" in request.args:\n try:\n from pyinstrument import Profiler", " g.perfprofiler = Profiler()\n g.perfprofiler.start()\n except ImportError:\n # profiler dependency not installed, ignore\n pass", " @app.after_request\n def after_request(response):\n # send no-cache headers with all POST responses\n if request.method == \"POST\":\n response.cache_control.no_cache = True", " response.headers.add(\"X-Clacks-Overhead\", \"GNU Terry Pratchett\")", " if hasattr(g, \"perfprofiler\"):\n g.perfprofiler.stop()\n output_html = g.perfprofiler.output_html()\n return make_response(output_html)", " if hasattr(g, \"start_time\"):\n end_time = time.monotonic()\n duration_ms = int((end_time - g.start_time) * 1000)\n response.headers.add(\"Server-Timing\", f\"app;dur={duration_ms}\")", " return response", " from octoprint.util.jinja import MarkdownFilter", " MarkdownFilter(app)", " from flask_limiter import Limiter\n from flask_limiter.util import get_remote_address", " app.config[\"RATELIMIT_STRATEGY\"] = \"fixed-window-elastic-expiry\"", " limiter = Limiter(app, key_func=get_remote_address)", " def _setup_i18n(self, app):\n global babel\n global LOCALES\n global LANGUAGES", " babel = Babel(app)", " def get_available_locale_identifiers(locales):\n result = set()", " # add available translations\n for locale in locales:\n result.add(locale.language)\n if locale.territory:\n # if a territory is specified, add that too\n result.add(f\"{locale.language}_{locale.territory}\")", " return result", " LOCALES = babel.list_translations()\n LANGUAGES = get_available_locale_identifiers(LOCALES)", " @babel.localeselector\n def get_locale():\n return self._get_locale()", " def _setup_jinja2(self):\n import re", " app.jinja_env.add_extension(\"jinja2.ext.do\")\n app.jinja_env.add_extension(\"octoprint.util.jinja.trycatch\")", " def regex_replace(s, find, replace):\n return re.sub(find, replace, s)", " html_header_regex = re.compile(\n r\"<h(?P<number>[1-6])>(?P<content>.*?)</h(?P=number)>\"\n )", " def offset_html_headers(s, offset):\n def repl(match):\n number = int(match.group(\"number\"))\n number += offset\n if number > 6:\n number = 6\n elif number < 1:\n number = 1\n return \"<h{number}>{content}</h{number}>\".format(\n number=number, content=match.group(\"content\")\n )", " return html_header_regex.sub(repl, s)", " markdown_header_regex = re.compile(\n r\"^(?P<hashs>#+)\\s+(?P<content>.*)$\", flags=re.MULTILINE\n )", " def offset_markdown_headers(s, offset):\n def repl(match):\n number = len(match.group(\"hashs\"))\n number += offset\n if number > 6:\n number = 6\n elif number < 1:\n number = 1\n return \"{hashs} {content}\".format(\n hashs=\"#\" * number, content=match.group(\"content\")\n )", " return markdown_header_regex.sub(repl, s)", " html_link_regex = re.compile(r\"<(?P<tag>a.*?)>(?P<content>.*?)</a>\")", " def externalize_links(text):\n def repl(match):\n tag = match.group(\"tag\")\n if \"href\" not in tag:\n return match.group(0)", " if \"target=\" not in tag and \"rel=\" not in tag:\n tag += ' target=\"_blank\" rel=\"noreferrer noopener\"'", " content = match.group(\"content\")\n return f\"<{tag}>{content}</a>\"", " return html_link_regex.sub(repl, text)", " single_quote_regex = re.compile(\"(?<!\\\\\\\\)'\")", " def escape_single_quote(text):\n return single_quote_regex.sub(\"\\\\'\", text)", " double_quote_regex = re.compile('(?<!\\\\\\\\)\"')", " def escape_double_quote(text):\n return double_quote_regex.sub('\\\\\"', text)", " app.jinja_env.filters[\"regex_replace\"] = regex_replace\n app.jinja_env.filters[\"offset_html_headers\"] = offset_html_headers\n app.jinja_env.filters[\"offset_markdown_headers\"] = offset_markdown_headers\n app.jinja_env.filters[\"externalize_links\"] = externalize_links\n app.jinja_env.filters[\"escape_single_quote\"] = app.jinja_env.filters[\n \"esq\"\n ] = escape_single_quote\n app.jinja_env.filters[\"escape_double_quote\"] = app.jinja_env.filters[\n \"edq\"\n ] = escape_double_quote", " # configure additional template folders for jinja2\n import jinja2", " import octoprint.util.jinja", " app.jinja_env.prefix_loader = jinja2.PrefixLoader({})", " loaders = [app.jinja_loader, app.jinja_env.prefix_loader]\n if octoprint.util.is_running_from_source():\n root = os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../..\"))\n allowed = [\"AUTHORS.md\", \"SUPPORTERS.md\", \"THIRDPARTYLICENSES.md\"]\n files = {\"_data/\" + name: os.path.join(root, name) for name in allowed}\n loaders.append(octoprint.util.jinja.SelectedFilesWithConversionLoader(files))", " # TODO: Remove this in 2.0.0\n warning_message = \"Loading plugin template '{template}' from '{filename}' without plugin prefix, this is deprecated and will soon no longer be supported.\"\n loaders.append(\n octoprint.util.jinja.WarningLoader(\n octoprint.util.jinja.PrefixChoiceLoader(app.jinja_env.prefix_loader),\n warning_message,\n )\n )", " app.jinja_loader = jinja2.ChoiceLoader(loaders)", " self._register_template_plugins()", " # make sure plugin lifecycle events relevant for jinja2 are taken care of\n def template_enabled(name, plugin):\n if plugin.implementation is None or not isinstance(\n plugin.implementation, octoprint.plugin.TemplatePlugin\n ):\n return\n self._register_additional_template_plugin(plugin.implementation)", " def template_disabled(name, plugin):\n if plugin.implementation is None or not isinstance(\n plugin.implementation, octoprint.plugin.TemplatePlugin\n ):\n return\n self._unregister_additional_template_plugin(plugin.implementation)", " pluginLifecycleManager.add_callback(\"enabled\", template_enabled)\n pluginLifecycleManager.add_callback(\"disabled\", template_disabled)", " def _execute_preemptive_flask_caching(self, preemptive_cache):\n import time", " from werkzeug.test import EnvironBuilder", " # we clean up entries from our preemptive cache settings that haven't been\n # accessed longer than server.preemptiveCache.until days\n preemptive_cache_timeout = settings().getInt(\n [\"server\", \"preemptiveCache\", \"until\"]\n )\n cutoff_timestamp = time.time() - preemptive_cache_timeout * 24 * 60 * 60", " def filter_current_entries(entry):\n \"\"\"Returns True for entries younger than the cutoff date\"\"\"\n return \"_timestamp\" in entry and entry[\"_timestamp\"] > cutoff_timestamp", " def filter_http_entries(entry):\n \"\"\"Returns True for entries targeting http or https.\"\"\"\n return (\n \"base_url\" in entry\n and entry[\"base_url\"]\n and (\n entry[\"base_url\"].startswith(\"http://\")\n or entry[\"base_url\"].startswith(\"https://\")\n )\n )", " def filter_entries(entry):\n \"\"\"Combined filter.\"\"\"\n filters = (filter_current_entries, filter_http_entries)\n return all([f(entry) for f in filters])", " # filter out all old and non-http entries\n cache_data = preemptive_cache.clean_all_data(\n lambda root, entries: list(filter(filter_entries, entries))\n )\n if not cache_data:\n return", " def execute_caching():\n logger = logging.getLogger(__name__ + \".preemptive_cache\")", " for route in sorted(cache_data.keys(), key=lambda x: (x.count(\"/\"), x)):\n entries = reversed(\n sorted(cache_data[route], key=lambda x: x.get(\"_count\", 0))\n )\n for kwargs in entries:\n plugin = kwargs.get(\"plugin\", None)\n if plugin:\n try:\n plugin_info = pluginManager.get_plugin_info(\n plugin, require_enabled=True\n )\n if plugin_info is None:\n logger.info(\n \"About to preemptively cache plugin {} but it is not installed or enabled, preemptive caching makes no sense\".format(\n plugin\n )\n )\n continue", " implementation = plugin_info.implementation\n if implementation is None or not isinstance(\n implementation, octoprint.plugin.UiPlugin\n ):\n logger.info(\n \"About to preemptively cache plugin {} but it is not a UiPlugin, preemptive caching makes no sense\".format(\n plugin\n )\n )\n continue\n if not implementation.get_ui_preemptive_caching_enabled():\n logger.info(\n \"About to preemptively cache plugin {} but it has disabled preemptive caching\".format(\n plugin\n )\n )\n continue\n except Exception:\n logger.exception(\n \"Error while trying to check if plugin {} has preemptive caching enabled, skipping entry\"\n )\n continue", " additional_request_data = kwargs.get(\"_additional_request_data\", {})\n kwargs = {\n k: v\n for k, v in kwargs.items()\n if not k.startswith(\"_\") and not k == \"plugin\"\n }\n kwargs.update(additional_request_data)", " try:\n start = time.monotonic()\n if plugin:\n logger.info(\n \"Preemptively caching {} (ui {}) for {!r}\".format(\n route, plugin, kwargs\n )\n )\n else:\n logger.info(\n \"Preemptively caching {} (ui _default) for {!r}\".format(\n route, kwargs\n )\n )", " headers = kwargs.get(\"headers\", {})\n headers[\"X-Force-View\"] = plugin if plugin else \"_default\"\n headers[\"X-Preemptive-Recording\"] = \"yes\"\n kwargs[\"headers\"] = headers", " builder = EnvironBuilder(**kwargs)\n app(builder.get_environ(), lambda *a, **kw: None)", " logger.info(f\"... done in {time.monotonic() - start:.2f}s\")\n except Exception:\n logger.exception(\n \"Error while trying to preemptively cache {} for {!r}\".format(\n route, kwargs\n )\n )", " # asynchronous caching\n import threading", " cache_thread = threading.Thread(\n target=execute_caching, name=\"Preemptive Cache Worker\"\n )\n cache_thread.daemon = True\n cache_thread.start()", " def _register_template_plugins(self):\n template_plugins = pluginManager.get_implementations(\n octoprint.plugin.TemplatePlugin\n )\n for plugin in template_plugins:\n try:\n self._register_additional_template_plugin(plugin)\n except Exception:\n self._logger.exception(\n \"Error while trying to register templates of plugin {}, ignoring it\".format(\n plugin._identifier\n )\n )", " def _register_additional_template_plugin(self, plugin):\n import octoprint.util.jinja", " folder = plugin.get_template_folder()\n if (\n folder is not None\n and plugin.template_folder_key not in app.jinja_env.prefix_loader.mapping\n ):\n loader = octoprint.util.jinja.FilteredFileSystemLoader(\n [plugin.get_template_folder()],\n path_filter=lambda x: not octoprint.util.is_hidden_path(x),\n )", " app.jinja_env.prefix_loader.mapping[plugin.template_folder_key] = loader", " def _unregister_additional_template_plugin(self, plugin):\n folder = plugin.get_template_folder()\n if (\n folder is not None\n and plugin.template_folder_key in app.jinja_env.prefix_loader.mapping\n ):\n del app.jinja_env.prefix_loader.mapping[plugin.template_folder_key]", " def _setup_blueprints(self):\n # do not remove or the index view won't be found\n import octoprint.server.views # noqa: F401\n from octoprint.server.api import api\n from octoprint.server.util.flask import make_api_error", " blueprints = [api]\n api_endpoints = [\"/api\"]\n registrators = [functools.partial(app.register_blueprint, api, url_prefix=\"/api\")]", " # also register any blueprints defined in BlueprintPlugins\n (\n blueprints_from_plugins,\n api_endpoints_from_plugins,\n registrators_from_plugins,\n ) = self._prepare_blueprint_plugins()\n blueprints += blueprints_from_plugins\n api_endpoints += api_endpoints_from_plugins\n registrators += registrators_from_plugins", " # and register a blueprint for serving the static files of asset plugins which are not blueprint plugins themselves\n (blueprints_from_assets, registrators_from_assets) = self._prepare_asset_plugins()\n blueprints += blueprints_from_assets\n registrators += registrators_from_assets", " # make sure all before/after_request hook results are attached as well\n self._add_plugin_request_handlers_to_blueprints(*blueprints)", " # register everything with the system\n for registrator in registrators:\n registrator()", " @app.errorhandler(HTTPException)\n def _handle_api_error(ex):\n if any(map(lambda x: request.path.startswith(x), api_endpoints)):\n return make_api_error(ex.description, ex.code)\n else:\n return ex", " def _prepare_blueprint_plugins(self):\n def register_plugin_blueprint(plugin, blueprint, url_prefix):\n try:\n app.register_blueprint(\n blueprint, url_prefix=url_prefix, name_prefix=\"plugin\"\n )\n self._logger.debug(\n f\"Registered API of plugin {plugin} under URL prefix {url_prefix}\"\n )\n except Exception:\n self._logger.exception(\n f\"Error while registering blueprint of plugin {plugin}, ignoring it\",\n extra={\"plugin\": plugin},\n )", " blueprints = []\n api_endpoints = []\n registrators = []", " blueprint_plugins = octoprint.plugin.plugin_manager().get_implementations(\n octoprint.plugin.BlueprintPlugin\n )\n for plugin in blueprint_plugins:\n blueprint, prefix = self._prepare_blueprint_plugin(plugin)", " blueprints.append(blueprint)\n api_endpoints += map(\n lambda x: prefix + x, plugin.get_blueprint_api_prefixes()\n )\n registrators.append(\n functools.partial(\n register_plugin_blueprint, plugin._identifier, blueprint, prefix\n )\n )", " return blueprints, api_endpoints, registrators", " def _prepare_asset_plugins(self):\n def register_asset_blueprint(plugin, blueprint, url_prefix):\n try:\n app.register_blueprint(\n blueprint, url_prefix=url_prefix, name_prefix=\"plugin\"\n )\n self._logger.debug(\n f\"Registered assets of plugin {plugin} under URL prefix {url_prefix}\"\n )\n except Exception:\n self._logger.exception(\n f\"Error while registering blueprint of plugin {plugin}, ignoring it\",\n extra={\"plugin\": plugin},\n )", " blueprints = []\n registrators = []", " asset_plugins = octoprint.plugin.plugin_manager().get_implementations(\n octoprint.plugin.AssetPlugin\n )\n for plugin in asset_plugins:\n if isinstance(plugin, octoprint.plugin.BlueprintPlugin):\n continue\n blueprint, prefix = self._prepare_asset_plugin(plugin)", " blueprints.append(blueprint)\n registrators.append(\n functools.partial(\n register_asset_blueprint, plugin._identifier, blueprint, prefix\n )\n )", " return blueprints, registrators", " def _prepare_blueprint_plugin(self, plugin):\n name = plugin._identifier\n blueprint = plugin.get_blueprint()\n if blueprint is None:\n return", " blueprint.before_request(corsRequestHandler)\n blueprint.before_request(loginFromApiKeyRequestHandler)\n blueprint.after_request(corsResponseHandler)", " if plugin.is_blueprint_protected():\n blueprint.before_request(requireLoginRequestHandler)", " url_prefix = f\"/plugin/{name}\"\n return blueprint, url_prefix", " def _prepare_asset_plugin(self, plugin):\n name = plugin._identifier", " url_prefix = f\"/plugin/{name}\"\n blueprint = Blueprint(name, name, static_folder=plugin.get_asset_folder())\n return blueprint, url_prefix", " def _add_plugin_request_handlers_to_blueprints(self, *blueprints):\n before_hooks = octoprint.plugin.plugin_manager().get_hooks(\n \"octoprint.server.api.before_request\"\n )\n after_hooks = octoprint.plugin.plugin_manager().get_hooks(\n \"octoprint.server.api.after_request\"\n )", " for name, hook in before_hooks.items():\n plugin = octoprint.plugin.plugin_manager().get_plugin(name)\n for blueprint in blueprints:\n try:\n result = hook(plugin=plugin)\n if isinstance(result, (list, tuple)):\n for h in result:\n blueprint.before_request(h)\n except Exception:\n self._logger.exception(\n \"Error processing before_request hooks from plugin {}\".format(\n plugin\n ),\n extra={\"plugin\": name},\n )", " for name, hook in after_hooks.items():\n plugin = octoprint.plugin.plugin_manager().get_plugin(name)\n for blueprint in blueprints:\n try:\n result = hook(plugin=plugin)\n if isinstance(result, (list, tuple)):\n for h in result:\n blueprint.after_request(h)\n except Exception:\n self._logger.exception(\n \"Error processing after_request hooks from plugin {}\".format(\n plugin\n ),\n extra={\"plugin\": name},\n )", " def _setup_mimetypes(self):\n # Safety measures for Windows... apparently the mimetypes module takes its translation from the windows\n # registry, and if for some weird reason that gets borked the reported MIME types can be all over the place.\n # Since at least in Chrome that can cause hilarious issues with JS files (refusal to run them and thus a\n # borked UI) we make sure that .js always maps to the correct application/javascript, and also throw in a\n # .css -> text/css for good measure.\n #\n # See #3367\n mimetypes.add_type(\"application/javascript\", \".js\")\n mimetypes.add_type(\"text/css\", \".css\")", " def _setup_assets(self):\n global app\n global assets\n global pluginManager", " from octoprint.server.util.webassets import MemoryManifest # noqa: F401", " util.flask.fix_webassets_filtertool()", " base_folder = self._settings.getBaseFolder(\"generated\")", " # clean the folder\n if self._settings.getBoolean([\"devel\", \"webassets\", \"clean_on_startup\"]):\n import errno\n import shutil", " for entry, recreate in (\n (\"webassets\", True),\n # no longer used, but clean up just in case\n (\".webassets-cache\", False),\n (\".webassets-manifest.json\", False),\n ):\n path = os.path.join(base_folder, entry)", " # delete path if it exists\n if os.path.exists(path):\n try:\n self._logger.debug(f\"Deleting {path}...\")\n if os.path.isdir(path):\n shutil.rmtree(path)\n else:\n os.remove(path)\n except Exception:\n self._logger.exception(\n f\"Error while trying to delete {path}, \" f\"leaving it alone\"\n )\n continue", " # re-create path if necessary\n if recreate:\n self._logger.debug(f\"Creating {path}...\")\n error_text = (\n f\"Error while trying to re-create {path}, that might cause \"\n f\"errors with the webassets cache\"\n )\n try:\n os.makedirs(path)\n except OSError as e:\n if e.errno == errno.EACCES:\n # that might be caused by the user still having the folder open somewhere, let's try again after\n # waiting a bit\n import time", " for n in range(3):\n time.sleep(0.5)\n self._logger.debug(\n \"Creating {path}: Retry #{retry} after {time}s\".format(\n path=path, retry=n + 1, time=(n + 1) * 0.5\n )\n )\n try:\n os.makedirs(path)\n break\n except Exception:\n if self._logger.isEnabledFor(logging.DEBUG):\n self._logger.exception(\n f\"Ignored error while creating \"\n f\"directory {path}\"\n )\n pass\n else:\n # this will only get executed if we never did\n # successfully execute makedirs above\n self._logger.exception(error_text)\n continue\n else:\n # not an access error, so something we don't understand\n # went wrong -> log an error and stop\n self._logger.exception(error_text)\n continue\n except Exception:\n # not an OSError, so something we don't understand\n # went wrong -> log an error and stop\n self._logger.exception(error_text)\n continue", " self._logger.info(f\"Reset webasset folder {path}...\")", " AdjustedEnvironment = type(Environment)(\n Environment.__name__,\n (Environment,),\n {\"resolver_class\": util.flask.PluginAssetResolver},\n )", " class CustomDirectoryEnvironment(AdjustedEnvironment):\n @property\n def directory(self):\n return base_folder", " assets = CustomDirectoryEnvironment(app)\n assets.debug = not self._settings.getBoolean([\"devel\", \"webassets\", \"bundle\"])", " # we should rarely if ever regenerate the webassets in production and can wait a\n # few seconds for regeneration in development, if it means we can get rid of\n # a whole monkey patch and in internal use of pickle with non-tamperproof files\n assets.cache = False\n assets.manifest = \"memory\"", " UpdaterType = type(util.flask.SettingsCheckUpdater)(\n util.flask.SettingsCheckUpdater.__name__,\n (util.flask.SettingsCheckUpdater,),\n {\"updater\": assets.updater},\n )\n assets.updater = UpdaterType", " preferred_stylesheet = self._settings.get([\"devel\", \"stylesheet\"])", " dynamic_core_assets = util.flask.collect_core_assets()\n dynamic_plugin_assets = util.flask.collect_plugin_assets(\n preferred_stylesheet=preferred_stylesheet\n )", " js_libs = [\n \"js/lib/babel-polyfill.min.js\",\n \"js/lib/jquery/jquery.min.js\",\n \"js/lib/modernizr.custom.js\",\n \"js/lib/lodash.min.js\",\n \"js/lib/sprintf.min.js\",\n \"js/lib/knockout.js\",\n \"js/lib/knockout.mapping-latest.js\",\n \"js/lib/babel.js\",\n \"js/lib/bootstrap/bootstrap.js\",\n \"js/lib/bootstrap/bootstrap-modalmanager.js\",\n \"js/lib/bootstrap/bootstrap-modal.js\",\n \"js/lib/bootstrap/bootstrap-slider.js\",\n \"js/lib/bootstrap/bootstrap-tabdrop.js\",\n \"js/lib/jquery/jquery-ui.js\",\n \"js/lib/jquery/jquery.flot.js\",\n \"js/lib/jquery/jquery.flot.time.js\",\n \"js/lib/jquery/jquery.flot.crosshair.js\",\n \"js/lib/jquery/jquery.flot.resize.js\",\n \"js/lib/jquery/jquery.iframe-transport.js\",\n \"js/lib/jquery/jquery.fileupload.js\",\n \"js/lib/jquery/jquery.slimscroll.min.js\",\n \"js/lib/jquery/jquery.qrcode.min.js\",\n \"js/lib/jquery/jquery.bootstrap.wizard.js\",\n \"js/lib/pnotify/pnotify.core.min.js\",\n \"js/lib/pnotify/pnotify.buttons.min.js\",\n \"js/lib/pnotify/pnotify.callbacks.min.js\",\n \"js/lib/pnotify/pnotify.confirm.min.js\",\n \"js/lib/pnotify/pnotify.desktop.min.js\",\n \"js/lib/pnotify/pnotify.history.min.js\",\n \"js/lib/pnotify/pnotify.mobile.min.js\",\n \"js/lib/pnotify/pnotify.nonblock.min.js\",\n \"js/lib/pnotify/pnotify.reference.min.js\",\n \"js/lib/pnotify/pnotify.tooltip.min.js\",\n \"js/lib/pnotify/pnotify.maxheight.js\",\n \"js/lib/moment-with-locales.min.js\",\n \"js/lib/pusher.color.min.js\",\n \"js/lib/detectmobilebrowser.js\",\n \"js/lib/ua-parser.min.js\",\n \"js/lib/md5.min.js\",\n \"js/lib/bootstrap-slider-knockout-binding.js\",\n \"js/lib/loglevel.min.js\",\n \"js/lib/sockjs.min.js\",\n \"js/lib/hls.js\",\n \"js/lib/less.js\",\n ]", " css_libs = [\n \"css/bootstrap.min.css\",\n \"css/bootstrap-modal.css\",\n \"css/bootstrap-slider.css\",\n \"css/bootstrap-tabdrop.css\",\n \"vendor/font-awesome-3.2.1/css/font-awesome.min.css\",\n \"vendor/font-awesome-5.15.1/css/all.min.css\",\n \"vendor/font-awesome-5.15.1/css/v4-shims.min.css\",\n \"css/jquery.fileupload-ui.css\",\n \"css/pnotify.core.min.css\",\n \"css/pnotify.buttons.min.css\",\n \"css/pnotify.history.min.css\",\n ]", " # a couple of custom filters\n from webassets.filter import register_filter", " from octoprint.server.util.webassets import (\n GzipFile,\n JsDelimiterBundler,\n JsPluginBundle,\n LessImportRewrite,\n RJSMinExtended,\n SourceMapRemove,\n SourceMapRewrite,\n )", " register_filter(LessImportRewrite)\n register_filter(SourceMapRewrite)\n register_filter(SourceMapRemove)\n register_filter(JsDelimiterBundler)\n register_filter(GzipFile)\n register_filter(RJSMinExtended)", " def all_assets_for_plugins(collection):\n \"\"\"Gets all plugin assets for a dict of plugin->assets\"\"\"\n result = []\n for assets in collection.values():\n result += assets\n return result", " # -- JS --------------------------------------------------------------------------------------------------------", " filters = [\"sourcemap_remove\"]\n if self._settings.getBoolean([\"devel\", \"webassets\", \"minify\"]):\n filters += [\"rjsmin_extended\"]\n filters += [\"js_delimiter_bundler\", \"gzip\"]", " js_filters = filters\n if self._settings.getBoolean([\"devel\", \"webassets\", \"minify_plugins\"]):\n js_plugin_filters = js_filters\n else:\n js_plugin_filters = [x for x in js_filters if x not in (\"rjsmin_extended\",)]", " def js_bundles_for_plugins(collection, filters=None):\n \"\"\"Produces JsPluginBundle instances that output IIFE wrapped assets\"\"\"\n result = OrderedDict()\n for plugin, assets in collection.items():\n if len(assets):\n result[plugin] = JsPluginBundle(plugin, *assets, filters=filters)\n return result", " js_core = (\n dynamic_core_assets[\"js\"]\n + all_assets_for_plugins(dynamic_plugin_assets[\"bundled\"][\"js\"])\n + [\"js/app/dataupdater.js\", \"js/app/helpers.js\", \"js/app/main.js\"]\n )\n js_plugins = js_bundles_for_plugins(\n dynamic_plugin_assets[\"external\"][\"js\"], filters=\"js_delimiter_bundler\"\n )", " clientjs_core = dynamic_core_assets[\"clientjs\"] + all_assets_for_plugins(\n dynamic_plugin_assets[\"bundled\"][\"clientjs\"]\n )\n clientjs_plugins = js_bundles_for_plugins(\n dynamic_plugin_assets[\"external\"][\"clientjs\"], filters=\"js_delimiter_bundler\"\n )", " js_libs_bundle = Bundle(\n *js_libs, output=\"webassets/packed_libs.js\", filters=\",\".join(js_filters)\n )", " js_core_bundle = Bundle(\n *js_core, output=\"webassets/packed_core.js\", filters=\",\".join(js_filters)\n )", " if len(js_plugins) == 0:\n js_plugins_bundle = Bundle(*[])\n else:\n js_plugins_bundle = Bundle(\n *js_plugins.values(),\n output=\"webassets/packed_plugins.js\",\n filters=\",\".join(js_plugin_filters),\n )", " js_app_bundle = Bundle(\n js_plugins_bundle,\n js_core_bundle,\n output=\"webassets/packed_app.js\",\n filters=\",\".join(js_plugin_filters),\n )", " js_client_core_bundle = Bundle(\n *clientjs_core,\n output=\"webassets/packed_client_core.js\",\n filters=\",\".join(js_filters),\n )", " if len(clientjs_plugins) == 0:\n js_client_plugins_bundle = Bundle(*[])\n else:\n js_client_plugins_bundle = Bundle(\n *clientjs_plugins.values(),\n output=\"webassets/packed_client_plugins.js\",\n filters=\",\".join(js_plugin_filters),\n )", " js_client_bundle = Bundle(\n js_client_core_bundle,\n js_client_plugins_bundle,\n output=\"webassets/packed_client.js\",\n filters=\",\".join(js_plugin_filters),\n )", " # -- CSS -------------------------------------------------------------------------------------------------------", " css_filters = [\"cssrewrite\", \"gzip\"]", " css_core = list(dynamic_core_assets[\"css\"]) + all_assets_for_plugins(\n dynamic_plugin_assets[\"bundled\"][\"css\"]\n )\n css_plugins = list(\n all_assets_for_plugins(dynamic_plugin_assets[\"external\"][\"css\"])\n )", " css_libs_bundle = Bundle(\n *css_libs, output=\"webassets/packed_libs.css\", filters=\",\".join(css_filters)\n )", " if len(css_core) == 0:\n css_core_bundle = Bundle(*[])\n else:\n css_core_bundle = Bundle(\n *css_core,\n output=\"webassets/packed_core.css\",\n filters=\",\".join(css_filters),\n )", " if len(css_plugins) == 0:\n css_plugins_bundle = Bundle(*[])\n else:\n css_plugins_bundle = Bundle(\n *css_plugins,\n output=\"webassets/packed_plugins.css\",\n filters=\",\".join(css_filters),\n )", " css_app_bundle = Bundle(\n css_core,\n css_plugins,\n output=\"webassets/packed_app.css\",\n filters=\",\".join(css_filters),\n )", " # -- LESS ------------------------------------------------------------------------------------------------------", " less_filters = [\"cssrewrite\", \"less_importrewrite\", \"gzip\"]", " less_core = list(dynamic_core_assets[\"less\"]) + all_assets_for_plugins(\n dynamic_plugin_assets[\"bundled\"][\"less\"]\n )\n less_plugins = all_assets_for_plugins(dynamic_plugin_assets[\"external\"][\"less\"])", " if len(less_core) == 0:\n less_core_bundle = Bundle(*[])\n else:\n less_core_bundle = Bundle(\n *less_core,\n output=\"webassets/packed_core.less\",\n filters=\",\".join(less_filters),\n )", " if len(less_plugins) == 0:\n less_plugins_bundle = Bundle(*[])\n else:\n less_plugins_bundle = Bundle(\n *less_plugins,\n output=\"webassets/packed_plugins.less\",\n filters=\",\".join(less_filters),\n )", " less_app_bundle = Bundle(\n less_core,\n less_plugins,\n output=\"webassets/packed_app.less\",\n filters=\",\".join(less_filters),\n )", " # -- asset registration ----------------------------------------------------------------------------------------", " assets.register(\"js_libs\", js_libs_bundle)\n assets.register(\"js_client_core\", js_client_core_bundle)\n for plugin, bundle in clientjs_plugins.items():\n # register our collected clientjs plugin bundles so that they are bound to the environment\n assets.register(f\"js_client_plugin_{plugin}\", bundle)\n assets.register(\"js_client_plugins\", js_client_plugins_bundle)\n assets.register(\"js_client\", js_client_bundle)\n assets.register(\"js_core\", js_core_bundle)\n for plugin, bundle in js_plugins.items():\n # register our collected plugin bundles so that they are bound to the environment\n assets.register(f\"js_plugin_{plugin}\", bundle)\n assets.register(\"js_plugins\", js_plugins_bundle)\n assets.register(\"js_app\", js_app_bundle)\n assets.register(\"css_libs\", css_libs_bundle)\n assets.register(\"css_core\", css_core_bundle)\n assets.register(\"css_plugins\", css_plugins_bundle)\n assets.register(\"css_app\", css_app_bundle)\n assets.register(\"less_core\", less_core_bundle)\n assets.register(\"less_plugins\", less_plugins_bundle)\n assets.register(\"less_app\", less_app_bundle)", " def _setup_login_manager(self):\n global loginManager", " loginManager = LoginManager()", " # \"strong\" is incompatible to remember me, see maxcountryman/flask-login#156. It also causes issues with\n # clients toggling between IPv4 and IPv6 client addresses due to names being resolved one way or the other as\n # at least observed on a Win10 client targeting \"localhost\", resolved as both \"127.0.0.1\" and \"::1\"\n loginManager.session_protection = \"basic\"", " loginManager.user_loader(load_user)\n loginManager.unauthorized_handler(unauthorized_user)\n loginManager.anonymous_user = userManager.anonymous_user_factory\n loginManager.request_loader(load_user_from_request)", " loginManager.init_app(app, add_context_processor=False)", " def _start_intermediary_server(self):\n import socket\n import threading\n from http.server import BaseHTTPRequestHandler, HTTPServer", " host = self._host\n port = self._port", " class IntermediaryServerHandler(BaseHTTPRequestHandler):\n def __init__(self, rules=None, *args, **kwargs):\n if rules is None:\n rules = []\n self.rules = rules\n BaseHTTPRequestHandler.__init__(self, *args, **kwargs)", " def do_GET(self):\n request_path = self.path\n if \"?\" in request_path:\n request_path = request_path[0 : request_path.find(\"?\")]", " for rule in self.rules:\n path, data, content_type = rule\n if request_path == path:\n self.send_response(200)\n if content_type:\n self.send_header(\"Content-Type\", content_type)\n self.end_headers()\n if isinstance(data, str):\n data = data.encode(\"utf-8\")\n self.wfile.write(data)\n break\n else:\n self.send_response(404)\n self.wfile.write(b\"Not found\")", " base_path = os.path.realpath(\n os.path.join(os.path.dirname(__file__), \"..\", \"static\")\n )\n rules = [\n (\n \"/\",\n [\n \"intermediary.html\",\n ],\n \"text/html\",\n ),\n (\"/favicon.ico\", [\"img\", \"tentacle-20x20.png\"], \"image/png\"),\n (\n \"/intermediary.gif\",\n bytes(\n base64.b64decode(\n \"R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7\"\n )\n ),\n \"image/gif\",\n ),\n ]", " def contents(args):\n path = os.path.join(base_path, *args)\n if not os.path.isfile(path):\n return \"\"", " with open(path, \"rb\") as f:\n data = f.read()\n return data", " def process(rule):\n if len(rule) == 2:\n path, data = rule\n content_type = None\n else:\n path, data, content_type = rule", " if isinstance(data, (list, tuple)):\n data = contents(data)", " return path, data, content_type", " rules = list(\n map(process, filter(lambda rule: len(rule) == 2 or len(rule) == 3, rules))\n )", " HTTPServerV4 = HTTPServer", " class HTTPServerV6(HTTPServer):\n address_family = socket.AF_INET6", " class HTTPServerV6SingleStack(HTTPServerV6):\n def __init__(self, *args, **kwargs):\n HTTPServerV6.__init__(self, *args, **kwargs)", " # explicitly set V6ONLY flag - seems to be the default, but just to make sure...\n self.socket.setsockopt(\n octoprint.util.net.IPPROTO_IPV6, octoprint.util.net.IPV6_V6ONLY, 1\n )", " class HTTPServerV6DualStack(HTTPServerV6):\n def __init__(self, *args, **kwargs):\n HTTPServerV6.__init__(self, *args, **kwargs)", " # explicitly unset V6ONLY flag\n self.socket.setsockopt(\n octoprint.util.net.IPPROTO_IPV6, octoprint.util.net.IPV6_V6ONLY, 0\n )", " if \":\" in host:\n # v6\n if host == \"::\" and not self._v6_only:\n ServerClass = HTTPServerV6DualStack\n else:\n ServerClass = HTTPServerV6SingleStack\n else:\n # v4\n ServerClass = HTTPServerV4", " if host == \"::\":\n if self._v6_only:\n self._logger.debug(f\"Starting intermediary server on http://[::]:{port}\")\n else:\n self._logger.debug(\n \"Starting intermediary server on http://0.0.0.0:{port} and http://[::]:{port}\".format(\n port=port\n )\n )\n else:\n self._logger.debug(\n \"Starting intermediary server on http://{}:{}\".format(\n host if \":\" not in host else \"[\" + host + \"]\", port\n )\n )", " self._intermediary_server = ServerClass(\n (host, port),\n lambda *args, **kwargs: IntermediaryServerHandler(rules, *args, **kwargs),\n bind_and_activate=False,\n )", " # if possible, make sure our socket's port descriptor isn't handed over to subprocesses\n from octoprint.util.platform import set_close_exec", " try:\n set_close_exec(self._intermediary_server.fileno())\n except Exception:\n self._logger.exception(\n \"Error while attempting to set_close_exec on intermediary server socket\"\n )", " # then bind the server and have it serve our handler until stopped\n try:\n self._intermediary_server.server_bind()\n self._intermediary_server.server_activate()\n except Exception as exc:\n self._intermediary_server.server_close()", " if isinstance(exc, UnicodeDecodeError) and sys.platform == \"win32\":\n # we end up here if the hostname contains non-ASCII characters due to\n # https://bugs.python.org/issue26227 - tell the user they need\n # to either change their hostname or read up other options in\n # https://github.com/OctoPrint/OctoPrint/issues/3963\n raise CannotStartServerException(\n \"OctoPrint cannot start due to a Python bug \"\n \"(https://bugs.python.org/issue26227). Your \"\n \"computer's host name contains non-ASCII characters. \"\n \"Please either change your computer's host name to \"\n \"contain only ASCII characters, or take a look at \"\n \"https://github.com/OctoPrint/OctoPrint/issues/3963 for \"\n \"other options.\"\n )\n else:\n raise", " def serve():\n try:\n self._intermediary_server.serve_forever()\n except Exception:\n self._logger.exception(\"Error in intermediary server\")", " thread = threading.Thread(target=serve)\n thread.daemon = True\n thread.start()", " self._logger.info(\"Intermediary server started\")", " def _stop_intermediary_server(self):\n if self._intermediary_server is None:\n return\n self._logger.info(\"Shutting down intermediary server...\")\n self._intermediary_server.shutdown()\n self._intermediary_server.server_close()\n self._logger.info(\"Intermediary server shut down\")", " def _setup_plugin_permissions(self):\n global pluginManager", " from octoprint.access.permissions import PluginOctoPrintPermission", " key_whitelist = re.compile(r\"[A-Za-z0-9_]*\")", " def permission_key(plugin, definition):\n return \"PLUGIN_{}_{}\".format(plugin.upper(), definition[\"key\"].upper())", " def permission_name(plugin, definition):\n return \"{}: {}\".format(plugin, definition[\"name\"])", " def permission_role(plugin, role):\n return f\"plugin_{plugin}_{role}\"", " def process_regular_permission(plugin_info, definition):\n permissions = []\n for key in definition.get(\"permissions\", []):\n permission = octoprint.access.permissions.Permissions.find(key)", " if permission is None:\n # if there is still no permission found, postpone this - maybe it is a permission from\n # another plugin that hasn't been loaded yet\n return False", " permissions.append(permission)", " roles = definition.get(\"roles\", [])\n description = definition.get(\"description\", \"\")\n dangerous = definition.get(\"dangerous\", False)\n default_groups = definition.get(\"default_groups\", [])", " roles_and_permissions = [\n permission_role(plugin_info.key, role) for role in roles\n ] + permissions", " key = permission_key(plugin_info.key, definition)\n permission = PluginOctoPrintPermission(\n permission_name(plugin_info.name, definition),\n description,\n plugin=plugin_info.key,\n dangerous=dangerous,\n default_groups=default_groups,\n *roles_and_permissions,\n )\n setattr(\n octoprint.access.permissions.Permissions,\n key,\n PluginOctoPrintPermission(\n permission_name(plugin_info.name, definition),\n description,\n plugin=plugin_info.key,\n dangerous=dangerous,\n default_groups=default_groups,\n *roles_and_permissions,\n ),\n )", " self._logger.info(\n \"Added new permission from plugin {}: {} (needs: {!r})\".format(\n plugin_info.key, key, \", \".join(map(repr, permission.needs))\n )\n )\n return True", " postponed = []", " hooks = pluginManager.get_hooks(\"octoprint.access.permissions\")\n for name, factory in hooks.items():\n try:\n if isinstance(factory, (tuple, list)):\n additional_permissions = list(factory)\n elif callable(factory):\n additional_permissions = factory()\n else:\n raise ValueError(\"factory must be either a callable, tuple or list\")", " if not isinstance(additional_permissions, (tuple, list)):\n raise ValueError(\n \"factory result must be either a tuple or a list of permission definition dicts\"\n )", " plugin_info = pluginManager.get_plugin_info(name)\n for p in additional_permissions:\n if not isinstance(p, dict):\n continue", " if \"key\" not in p or \"name\" not in p:\n continue", " if not key_whitelist.match(p[\"key\"]):\n self._logger.warning(\n \"Got permission with invalid key from plugin {}: {}\".format(\n name, p[\"key\"]\n )\n )\n continue", " if not process_regular_permission(plugin_info, p):\n postponed.append((plugin_info, p))\n except Exception:\n self._logger.exception(\n f\"Error while creating permission instance/s from {name}\"\n )", " # final resolution passes\n pass_number = 1\n still_postponed = []\n while len(postponed):\n start_length = len(postponed)\n self._logger.debug(\n \"Plugin permission resolution pass #{}, \"\n \"{} unresolved permissions...\".format(pass_number, start_length)\n )", " for plugin_info, definition in postponed:\n if not process_regular_permission(plugin_info, definition):\n still_postponed.append((plugin_info, definition))", " self._logger.debug(\n \"... pass #{} done, {} permissions left to resolve\".format(\n pass_number, len(still_postponed)\n )\n )", " if len(still_postponed) == start_length:\n # no change, looks like some stuff is unresolvable - let's bail\n for plugin_info, definition in still_postponed:\n self._logger.warning(\n \"Unable to resolve permission from {}: {!r}\".format(\n plugin_info.key, definition\n )\n )\n break", " postponed = still_postponed\n still_postponed = []\n pass_number += 1", "\nclass LifecycleManager:\n def __init__(self, plugin_manager):\n self._plugin_manager = plugin_manager", " self._plugin_lifecycle_callbacks = defaultdict(list)\n self._logger = logging.getLogger(__name__)", " def wrap_plugin_event(lifecycle_event, new_handler):\n orig_handler = getattr(self._plugin_manager, \"on_plugin_\" + lifecycle_event)", " def handler(*args, **kwargs):\n if callable(orig_handler):\n orig_handler(*args, **kwargs)\n if callable(new_handler):\n new_handler(*args, **kwargs)", " return handler", " def on_plugin_event_factory(lifecycle_event):\n def on_plugin_event(name, plugin):\n self.on_plugin_event(lifecycle_event, name, plugin)", " return on_plugin_event", " for event in (\"loaded\", \"unloaded\", \"enabled\", \"disabled\"):\n wrap_plugin_event(event, on_plugin_event_factory(event))", " def on_plugin_event(self, event, name, plugin):\n for lifecycle_callback in self._plugin_lifecycle_callbacks[event]:\n lifecycle_callback(name, plugin)", " def add_callback(self, events, callback):\n if isinstance(events, str):\n events = [events]", " for event in events:\n self._plugin_lifecycle_callbacks[event].append(callback)", " def remove_callback(self, callback, events=None):\n if events is None:\n for event in self._plugin_lifecycle_callbacks:\n if callback in self._plugin_lifecycle_callbacks[event]:\n self._plugin_lifecycle_callbacks[event].remove(callback)\n else:\n if isinstance(events, str):\n events = [events]", " for event in events:\n if callback in self._plugin_lifecycle_callbacks[event]:\n self._plugin_lifecycle_callbacks[event].remove(callback)", "\nclass CannotStartServerException(Exception):\n pass" ]
[ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [984, 842, 1177], "buggy_code_start_loc": [956, 42, 1141], "filenames": ["src/octoprint/filemanager/storage.py", "src/octoprint/server/__init__.py", "src/octoprint/server/api/files.py"], "fixing_code_end_loc": [997, 854, 1190], "fixing_code_start_loc": [957, 43, 1141], "message": "Unrestricted Upload of File with Dangerous Type in GitHub repository octoprint/octoprint prior to 1.8.3.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:octoprint:octoprint:*:*:*:*:*:*:*:*", "matchCriteriaId": "900F81F7-9FC4-44CE-ABD6-1E82DC120B4B", "versionEndExcluding": "1.8.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Unrestricted Upload of File with Dangerous Type in GitHub repository octoprint/octoprint prior to 1.8.3."}, {"lang": "es", "value": "Una Descarga sin Restricciones de Archivos de Tipo Peligroso en el repositorio GitHub octoprint/octoprint versiones anteriores a 1.8.3"}], "evaluatorComment": null, "id": "CVE-2022-2872", "lastModified": "2022-09-23T17:58:22.120", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:L/UI:R/S:U/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 1.2, "impactScore": 2.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-09-21T10:15:09.327", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/octoprint/octoprint/commit/3e3c11811e216fb371a33e28412df83f9701e5b0"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/b966c74d-6f3f-49fe-b40a-eaf25e362c56"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-434"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/octoprint/octoprint/commit/3e3c11811e216fb371a33e28412df83f9701e5b0"}, "type": "CWE-434"}
328
Determine whether the {function_name} code is vulnerable or not.
[ "__author__ = \"Gina Häußge <osd@foosel.net>\"\n__license__ = \"GNU Affero General Public License http://www.gnu.org/licenses/agpl.html\"\n__copyright__ = \"Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License\"", "import atexit\nimport base64\nimport functools\nimport logging\nimport logging.config\nimport mimetypes\nimport os\nimport re\nimport signal\nimport sys\nimport time\nimport uuid # noqa: F401\nfrom collections import OrderedDict, defaultdict", "from babel import Locale\nfrom flask import ( # noqa: F401\n Blueprint,\n Flask,\n Request,\n Response,\n current_app,\n g,\n make_response,\n request,\n session,\n)\nfrom flask_assets import Bundle, Environment\nfrom flask_babel import Babel, gettext, ngettext # noqa: F401\nfrom flask_login import ( # noqa: F401\n LoginManager,\n current_user,\n session_protected,\n user_logged_out,\n)\nfrom watchdog.observers import Observer\nfrom watchdog.observers.polling import PollingObserver\nfrom werkzeug.exceptions import HTTPException\n", "import octoprint.filemanager", "import octoprint.util\nimport octoprint.util.net\nfrom octoprint.server import util\nfrom octoprint.systemcommands import system_command_manager\nfrom octoprint.util.json import JsonEncoding\nfrom octoprint.vendor.flask_principal import ( # noqa: F401\n AnonymousIdentity,\n Identity,\n Permission,\n Principal,\n RoleNeed,\n UserNeed,\n identity_changed,\n identity_loaded,\n)\nfrom octoprint.vendor.sockjs.tornado import SockJSRouter", "try:\n import fcntl\nexcept ImportError:\n fcntl = None", "SUCCESS = {}\nNO_CONTENT = (\"\", 204, {\"Content-Type\": \"text/plain\"})\nNOT_MODIFIED = (\"Not Modified\", 304, {\"Content-Type\": \"text/plain\"})", "app = Flask(\"octoprint\")", "assets = None\nbabel = None\nlimiter = None\ndebug = False\nsafe_mode = False", "printer = None\nprinterProfileManager = None\nfileManager = None\nslicingManager = None\nanalysisQueue = None\nuserManager = None\npermissionManager = None\ngroupManager = None\neventManager = None\nloginManager = None\npluginManager = None\npluginLifecycleManager = None\npreemptiveCache = None\njsonEncoder = None\njsonDecoder = None\nconnectivityChecker = None\nenvironmentDetector = None", "principals = Principal(app)", "import octoprint.access.groups as groups # noqa: E402\nimport octoprint.access.permissions as permissions # noqa: E402", "# we set admin_permission to a GroupPermission with the default admin group\nadmin_permission = octoprint.util.variable_deprecated(\n \"admin_permission has been deprecated, \" \"please use individual Permissions instead\",\n since=\"1.4.0\",\n)(groups.GroupPermission(groups.ADMIN_GROUP))", "# we set user_permission to a GroupPermission with the default user group\nuser_permission = octoprint.util.variable_deprecated(\n \"user_permission has been deprecated, \" \"please use individual Permissions instead\",\n since=\"1.4.0\",\n)(groups.GroupPermission(groups.USER_GROUP))", "import octoprint._version # noqa: E402\nimport octoprint.access.groups as groups # noqa: E402\nimport octoprint.access.users as users # noqa: E402\nimport octoprint.events as events # noqa: E402\nimport octoprint.filemanager.analysis # noqa: E402\nimport octoprint.filemanager.storage # noqa: E402\nimport octoprint.plugin # noqa: E402\nimport octoprint.slicing # noqa: E402\nimport octoprint.timelapse # noqa: E402", "# only import further octoprint stuff down here, as it might depend on things defined above to be initialized already\nfrom octoprint import __branch__, __display_version__, __revision__, __version__\nfrom octoprint.printer.profile import PrinterProfileManager\nfrom octoprint.printer.standard import Printer\nfrom octoprint.server.util import (\n corsRequestHandler,\n corsResponseHandler,\n loginFromApiKeyRequestHandler,\n requireLoginRequestHandler,\n)\nfrom octoprint.server.util.flask import PreemptiveCache\nfrom octoprint.settings import settings", "VERSION = __version__\nBRANCH = __branch__\nDISPLAY_VERSION = __display_version__\nREVISION = __revision__", "LOCALES = []\nLANGUAGES = set()", "\n@identity_loaded.connect_via(app)\ndef on_identity_loaded(sender, identity):\n user = load_user(identity.id)\n if user is None:\n user = userManager.anonymous_user_factory()", " identity.provides.add(UserNeed(user.get_id()))\n for need in user.needs:\n identity.provides.add(need)", "\ndef _clear_identity(sender):\n # Remove session keys set by Flask-Principal\n for key in (\"identity.id\", \"identity.name\", \"identity.auth_type\"):\n session.pop(key, None)", " # switch to anonymous identity\n identity_changed.send(sender, identity=AnonymousIdentity())", "\n@session_protected.connect_via(app)\ndef on_session_protected(sender):\n # session was deleted by session protection, that means the user is no more and we need to clear our identity\n if session.get(\"remember\", None) == \"clear\":\n _clear_identity(sender)", "\n@user_logged_out.connect_via(app)\ndef on_user_logged_out(sender, user=None):\n # user was logged out, clear identity\n _clear_identity(sender)", "\ndef load_user(id):\n if id is None:\n return None", " if id == \"_api\":\n return userManager.api_user_factory()", " if session and \"usersession.id\" in session:\n sessionid = session[\"usersession.id\"]\n else:\n sessionid = None", " if sessionid:\n user = userManager.find_user(userid=id, session=sessionid)\n else:\n user = userManager.find_user(userid=id)", " if user and user.is_active:\n return user", " return None", "\ndef load_user_from_request(request):\n user = None", " if settings().getBoolean([\"accessControl\", \"trustBasicAuthentication\"]):\n # Basic Authentication?\n user = util.get_user_for_authorization_header(\n request.headers.get(\"Authorization\")\n )", " if settings().getBoolean([\"accessControl\", \"trustRemoteUser\"]):\n # Remote user header?\n user = util.get_user_for_remote_user_header(request)", " return user", "\ndef unauthorized_user():\n from flask import abort", " abort(403)", "\n# ~~ startup code", "\nclass Server:\n def __init__(\n self,\n settings=None,\n plugin_manager=None,\n connectivity_checker=None,\n environment_detector=None,\n event_manager=None,\n host=None,\n port=None,\n v6_only=False,\n debug=False,\n safe_mode=False,\n allow_root=False,\n octoprint_daemon=None,\n ):\n self._settings = settings\n self._plugin_manager = plugin_manager\n self._connectivity_checker = connectivity_checker\n self._environment_detector = environment_detector\n self._event_manager = event_manager\n self._host = host\n self._port = port\n self._v6_only = v6_only\n self._debug = debug\n self._safe_mode = safe_mode\n self._allow_root = allow_root\n self._octoprint_daemon = octoprint_daemon\n self._server = None", " self._logger = None", " self._lifecycle_callbacks = defaultdict(list)", " self._intermediary_server = None", " def run(self):\n if not self._allow_root:\n self._check_for_root()", " if self._settings is None:\n self._settings = settings()", " if not self._settings.getBoolean([\"server\", \"ignoreIncompleteStartup\"]):\n self._settings.setBoolean([\"server\", \"incompleteStartup\"], True)\n self._settings.save()", " if self._plugin_manager is None:\n self._plugin_manager = octoprint.plugin.plugin_manager()", " global app\n global babel", " global printer\n global printerProfileManager\n global fileManager\n global slicingManager\n global analysisQueue\n global userManager\n global permissionManager\n global groupManager\n global eventManager\n global loginManager\n global pluginManager\n global pluginLifecycleManager\n global preemptiveCache\n global jsonEncoder\n global jsonDecoder\n global connectivityChecker\n global environmentDetector\n global debug\n global safe_mode", " from tornado.ioloop import IOLoop\n from tornado.web import Application", " debug = self._debug\n safe_mode = self._safe_mode", " if safe_mode:\n self._log_safe_mode_start(safe_mode)", " if self._v6_only and not octoprint.util.net.HAS_V6:\n raise RuntimeError(\n \"IPv6 only mode configured but system doesn't support IPv6\"\n )", " if self._host is None:\n host = self._settings.get([\"server\", \"host\"])\n if host is None:\n if octoprint.util.net.HAS_V6:\n host = \"::\"\n else:\n host = \"0.0.0.0\"", " self._host = host", " if \":\" in self._host and not octoprint.util.net.HAS_V6:\n raise RuntimeError(\n \"IPv6 host address {!r} configured but system doesn't support IPv6\".format(\n self._host\n )\n )", " if self._port is None:\n self._port = self._settings.getInt([\"server\", \"port\"])\n if self._port is None:\n self._port = 5000", " self._logger = logging.getLogger(__name__)\n self._setup_heartbeat_logging()\n pluginManager = self._plugin_manager", " # monkey patch/fix some stuff\n util.tornado.fix_json_encode()\n util.tornado.fix_websocket_check_origin()\n util.tornado.enable_per_message_deflate_extension()\n util.flask.fix_flask_jsonify()", " self._setup_mimetypes()", " additional_translation_folders = []\n if not safe_mode:\n additional_translation_folders += [\n self._settings.getBaseFolder(\"translations\")\n ]\n util.flask.enable_additional_translations(\n additional_folders=additional_translation_folders\n )", " # setup app\n self._setup_app(app)", " # setup i18n\n self._setup_i18n(app)", " if self._settings.getBoolean([\"serial\", \"log\"]):\n # enable debug logging to serial.log\n logging.getLogger(\"SERIAL\").setLevel(logging.DEBUG)", " if self._settings.getBoolean([\"devel\", \"pluginTimings\"]):\n # enable plugin timings log\n logging.getLogger(\"PLUGIN_TIMINGS\").setLevel(logging.DEBUG)", " # start the intermediary server\n self._start_intermediary_server()", " ### IMPORTANT!\n ###\n ### Best do not start any subprocesses until the intermediary server shuts down again or they MIGHT inherit the\n ### open port and prevent us from firing up Tornado later.\n ###\n ### The intermediary server's socket should have the CLOSE_EXEC flag (or its equivalent) set where possible, but\n ### we can only do that if fcntl is available or we are on Windows, so better safe than sorry.\n ###\n ### See also issues #2035 and #2090", " systemCommandManager = system_command_manager()\n printerProfileManager = PrinterProfileManager()\n eventManager = self._event_manager", " analysis_queue_factories = {\n \"gcode\": octoprint.filemanager.analysis.GcodeAnalysisQueue\n }\n analysis_queue_hooks = pluginManager.get_hooks(\n \"octoprint.filemanager.analysis.factory\"\n )\n for name, hook in analysis_queue_hooks.items():\n try:\n additional_factories = hook()\n analysis_queue_factories.update(**additional_factories)\n except Exception:\n self._logger.exception(\n f\"Error while processing analysis queues from {name}\",\n extra={\"plugin\": name},\n )\n analysisQueue = octoprint.filemanager.analysis.AnalysisQueue(\n analysis_queue_factories\n )", " slicingManager = octoprint.slicing.SlicingManager(\n self._settings.getBaseFolder(\"slicingProfiles\"), printerProfileManager\n )", " storage_managers = {}\n storage_managers[\n octoprint.filemanager.FileDestinations.LOCAL\n ] = octoprint.filemanager.storage.LocalFileStorage(\n self._settings.getBaseFolder(\"uploads\"),\n really_universal=self._settings.getBoolean(\n [\"feature\", \"enforceReallyUniversalFilenames\"]\n ),\n )", " fileManager = octoprint.filemanager.FileManager(\n analysisQueue,\n slicingManager,\n printerProfileManager,\n initial_storage_managers=storage_managers,\n )\n pluginLifecycleManager = LifecycleManager(pluginManager)\n preemptiveCache = PreemptiveCache(\n os.path.join(\n self._settings.getBaseFolder(\"data\"), \"preemptive_cache_config.yaml\"\n )\n )", " JsonEncoding.add_encoder(users.User, lambda obj: obj.as_dict())\n JsonEncoding.add_encoder(groups.Group, lambda obj: obj.as_dict())\n JsonEncoding.add_encoder(\n permissions.OctoPrintPermission, lambda obj: obj.as_dict()\n )", " # start regular check if we are connected to the internet\n def on_connectivity_change(old_value, new_value):\n eventManager.fire(\n events.Events.CONNECTIVITY_CHANGED,\n payload={\"old\": old_value, \"new\": new_value},\n )", " connectivityChecker = self._connectivity_checker\n environmentDetector = self._environment_detector", " def on_settings_update(*args, **kwargs):\n # make sure our connectivity checker runs with the latest settings\n connectivityEnabled = self._settings.getBoolean(\n [\"server\", \"onlineCheck\", \"enabled\"]\n )\n connectivityInterval = self._settings.getInt(\n [\"server\", \"onlineCheck\", \"interval\"]\n )\n connectivityHost = self._settings.get([\"server\", \"onlineCheck\", \"host\"])\n connectivityPort = self._settings.getInt([\"server\", \"onlineCheck\", \"port\"])\n connectivityName = self._settings.get([\"server\", \"onlineCheck\", \"name\"])", " if (\n connectivityChecker.enabled != connectivityEnabled\n or connectivityChecker.interval != connectivityInterval\n or connectivityChecker.host != connectivityHost\n or connectivityChecker.port != connectivityPort\n or connectivityChecker.name != connectivityName\n ):\n connectivityChecker.enabled = connectivityEnabled\n connectivityChecker.interval = connectivityInterval\n connectivityChecker.host = connectivityHost\n connectivityChecker.port = connectivityPort\n connectivityChecker.name = connectivityName\n connectivityChecker.check_immediately()", " eventManager.subscribe(events.Events.SETTINGS_UPDATED, on_settings_update)", " components = {\n \"plugin_manager\": pluginManager,\n \"printer_profile_manager\": printerProfileManager,\n \"event_bus\": eventManager,\n \"analysis_queue\": analysisQueue,\n \"slicing_manager\": slicingManager,\n \"file_manager\": fileManager,\n \"plugin_lifecycle_manager\": pluginLifecycleManager,\n \"preemptive_cache\": preemptiveCache,\n \"json_encoder\": jsonEncoder,\n \"json_decoder\": jsonDecoder,\n \"connectivity_checker\": connectivityChecker,\n \"environment_detector\": self._environment_detector,\n \"system_commands\": systemCommandManager,\n }", " # ~~ setup access control", " # get additional permissions from plugins\n self._setup_plugin_permissions()", " # create group manager instance\n group_manager_factories = pluginManager.get_hooks(\n \"octoprint.access.groups.factory\"\n )\n for name, factory in group_manager_factories.items():\n try:\n groupManager = factory(components, self._settings)\n if groupManager is not None:\n self._logger.debug(\n f\"Created group manager instance from factory {name}\"\n )\n break\n except Exception:\n self._logger.exception(\n \"Error while creating group manager instance from factory {}\".format(\n name\n )\n )\n else:\n group_manager_name = self._settings.get([\"accessControl\", \"groupManager\"])\n try:\n clazz = octoprint.util.get_class(group_manager_name)\n groupManager = clazz()\n except AttributeError:\n self._logger.exception(\n \"Could not instantiate group manager {}, \"\n \"falling back to FilebasedGroupManager!\".format(group_manager_name)\n )\n groupManager = octoprint.access.groups.FilebasedGroupManager()\n components.update({\"group_manager\": groupManager})", " # create user manager instance\n user_manager_factories = pluginManager.get_hooks(\n \"octoprint.users.factory\"\n ) # legacy, set first so that new wins\n user_manager_factories.update(\n pluginManager.get_hooks(\"octoprint.access.users.factory\")\n )\n for name, factory in user_manager_factories.items():\n try:\n userManager = factory(components, self._settings)\n if userManager is not None:\n self._logger.debug(\n f\"Created user manager instance from factory {name}\"\n )\n break\n except Exception:\n self._logger.exception(\n \"Error while creating user manager instance from factory {}\".format(\n name\n ),\n extra={\"plugin\": name},\n )\n else:\n user_manager_name = self._settings.get([\"accessControl\", \"userManager\"])\n try:\n clazz = octoprint.util.get_class(user_manager_name)\n userManager = clazz(groupManager)\n except octoprint.access.users.CorruptUserStorage:\n raise\n except Exception:\n self._logger.exception(\n \"Could not instantiate user manager {}, \"\n \"falling back to FilebasedUserManager!\".format(user_manager_name)\n )\n userManager = octoprint.access.users.FilebasedUserManager(groupManager)\n components.update({\"user_manager\": userManager})", " # create printer instance\n printer_factories = pluginManager.get_hooks(\"octoprint.printer.factory\")\n for name, factory in printer_factories.items():\n try:\n printer = factory(components)\n if printer is not None:\n self._logger.debug(f\"Created printer instance from factory {name}\")\n break\n except Exception:\n self._logger.exception(\n f\"Error while creating printer instance from factory {name}\",\n extra={\"plugin\": name},\n )\n else:\n printer = Printer(fileManager, analysisQueue, printerProfileManager)\n components.update({\"printer\": printer})", " from octoprint import (\n init_custom_events,\n init_settings_plugin_config_migration_and_cleanup,\n )\n from octoprint import octoprint_plugin_inject_factory as opif\n from octoprint import settings_plugin_inject_factory as spif", " init_custom_events(pluginManager)", " octoprint_plugin_inject_factory = opif(self._settings, components)\n settings_plugin_inject_factory = spif(self._settings)", " pluginManager.implementation_inject_factories = [\n octoprint_plugin_inject_factory,\n settings_plugin_inject_factory,\n ]\n pluginManager.initialize_implementations()", " init_settings_plugin_config_migration_and_cleanup(pluginManager)", " pluginManager.log_all_plugins()", " # log environment data now\n self._environment_detector.log_detected_environment()", " # initialize file manager and register it for changes in the registered plugins\n fileManager.initialize()\n pluginLifecycleManager.add_callback(\n [\"enabled\", \"disabled\"], lambda name, plugin: fileManager.reload_plugins()\n )", " # initialize slicing manager and register it for changes in the registered plugins\n slicingManager.initialize()\n pluginLifecycleManager.add_callback(\n [\"enabled\", \"disabled\"], lambda name, plugin: slicingManager.reload_slicers()\n )", " # setup jinja2\n self._setup_jinja2()", " # setup assets\n self._setup_assets()", " # configure timelapse\n octoprint.timelapse.valid_timelapse(\"test\")\n octoprint.timelapse.configure_timelapse()", " # setup command triggers\n events.CommandTrigger(printer)\n if self._debug:\n events.DebugEventListener()", " # setup login manager\n self._setup_login_manager()", " # register API blueprint\n self._setup_blueprints()", " ## Tornado initialization starts here", " ioloop = IOLoop()\n ioloop.install()", " enable_cors = settings().getBoolean([\"api\", \"allowCrossOrigin\"])", " self._router = SockJSRouter(\n self._create_socket_connection,\n \"/sockjs\",\n session_kls=util.sockjs.ThreadSafeSession,\n user_settings={\n \"websocket_allow_origin\": \"*\" if enable_cors else \"\",\n \"jsessionid\": False,\n \"sockjs_url\": \"../../static/js/lib/sockjs.min.js\",\n },\n )", " upload_suffixes = {\n \"name\": self._settings.get([\"server\", \"uploads\", \"nameSuffix\"]),\n \"path\": self._settings.get([\"server\", \"uploads\", \"pathSuffix\"]),\n }", " def mime_type_guesser(path):\n from octoprint.filemanager import get_mime_type", " return get_mime_type(path)", " def download_name_generator(path):\n metadata = fileManager.get_metadata(\"local\", path)\n if metadata and \"display\" in metadata:\n return metadata[\"display\"]", " download_handler_kwargs = {\"as_attachment\": True, \"allow_client_caching\": False}", " additional_mime_types = {\"mime_type_guesser\": mime_type_guesser}", " ##~~ Permission validators", " access_validators_from_plugins = []\n for plugin, hook in pluginManager.get_hooks(\n \"octoprint.server.http.access_validator\"\n ).items():\n try:\n access_validators_from_plugins.append(\n util.tornado.access_validation_factory(app, hook)\n )\n except Exception:\n self._logger.exception(\n \"Error while adding tornado access validator from plugin {}\".format(\n plugin\n ),\n extra={\"plugin\": plugin},\n )", " timelapse_validators = [\n util.tornado.access_validation_factory(\n app,\n util.flask.permission_validator,\n permissions.Permissions.TIMELAPSE_LIST,\n ),\n ] + access_validators_from_plugins\n download_validators = [\n util.tornado.access_validation_factory(\n app,\n util.flask.permission_validator,\n permissions.Permissions.FILES_DOWNLOAD,\n ),\n ] + access_validators_from_plugins\n log_validators = [\n util.tornado.access_validation_factory(\n app,\n util.flask.permission_validator,\n permissions.Permissions.PLUGIN_LOGGING_MANAGE,\n ),\n ] + access_validators_from_plugins\n camera_validators = [\n util.tornado.access_validation_factory(\n app, util.flask.permission_validator, permissions.Permissions.WEBCAM\n ),\n ] + access_validators_from_plugins\n systeminfo_validators = [\n util.tornado.access_validation_factory(\n app, util.flask.permission_validator, permissions.Permissions.SYSTEM\n )\n ] + access_validators_from_plugins", " timelapse_permission_validator = {\n \"access_validation\": util.tornado.validation_chain(*timelapse_validators)\n }\n download_permission_validator = {\n \"access_validation\": util.tornado.validation_chain(*download_validators)\n }\n log_permission_validator = {\n \"access_validation\": util.tornado.validation_chain(*log_validators)\n }\n camera_permission_validator = {\n \"access_validation\": util.tornado.validation_chain(*camera_validators)\n }\n systeminfo_permission_validator = {\n \"access_validation\": util.tornado.validation_chain(*systeminfo_validators)\n }", " no_hidden_files_validator = {\n \"path_validation\": util.tornado.path_validation_factory(\n lambda path: not octoprint.util.is_hidden_path(path), status_code=404", " )\n }", " only_known_types_validator = {\n \"path_validation\": util.tornado.path_validation_factory(\n lambda path: octoprint.filemanager.valid_file_type(\n os.path.basename(path)\n ),\n status_code=404,", " )\n }", " valid_timelapse = lambda path: not octoprint.util.is_hidden_path(path) and (\n octoprint.timelapse.valid_timelapse(path)\n or octoprint.timelapse.valid_timelapse_thumbnail(path)\n )\n timelapse_path_validator = {\n \"path_validation\": util.tornado.path_validation_factory(\n valid_timelapse,\n status_code=404,\n )\n }\n timelapses_path_validator = {\n \"path_validation\": util.tornado.path_validation_factory(\n lambda path: valid_timelapse(path)\n and os.path.realpath(os.path.abspath(path)).startswith(\n settings().getBaseFolder(\"timelapse\")\n ),\n status_code=400,\n )\n }", " valid_log = lambda path: not octoprint.util.is_hidden_path(\n path\n ) and path.endswith(\".log\")\n log_path_validator = {\n \"path_validation\": util.tornado.path_validation_factory(\n valid_log,\n status_code=404,\n )\n }\n logs_path_validator = {\n \"path_validation\": util.tornado.path_validation_factory(\n lambda path: valid_log(path)\n and os.path.realpath(os.path.abspath(path)).startswith(\n settings().getBaseFolder(\"logs\")\n ),\n status_code=400,\n )\n }", " def joined_dict(*dicts):\n if not len(dicts):\n return {}", " joined = {}\n for d in dicts:\n joined.update(d)\n return joined", " util.tornado.RequestlessExceptionLoggingMixin.LOG_REQUEST = debug\n util.tornado.CorsSupportMixin.ENABLE_CORS = enable_cors", " server_routes = self._router.urls + [\n # various downloads\n # .mpg and .mp4 timelapses:\n (\n r\"/downloads/timelapse/(.*)\",\n util.tornado.LargeResponseHandler,\n joined_dict(\n {\"path\": self._settings.getBaseFolder(\"timelapse\")},\n timelapse_permission_validator,\n download_handler_kwargs,\n timelapse_path_validator,\n ),\n ),\n # zipped timelapse bundles\n (\n r\"/downloads/timelapses\",\n util.tornado.DynamicZipBundleHandler,\n joined_dict(\n {\n \"as_attachment\": True,\n \"attachment_name\": \"octoprint-timelapses.zip\",\n \"path_processor\": lambda x: (\n x,\n os.path.join(self._settings.getBaseFolder(\"timelapse\"), x),\n ),\n },\n timelapse_permission_validator,\n timelapses_path_validator,\n ),\n ),\n # uploaded printables\n (\n r\"/downloads/files/local/(.*)\",\n util.tornado.LargeResponseHandler,\n joined_dict(\n {\n \"path\": self._settings.getBaseFolder(\"uploads\"),\n \"as_attachment\": True,\n \"name_generator\": download_name_generator,\n },\n download_permission_validator,\n download_handler_kwargs,\n no_hidden_files_validator,", " only_known_types_validator,", " additional_mime_types,\n ),\n ),\n # log files\n (\n r\"/downloads/logs/([^/]*)\",\n util.tornado.LargeResponseHandler,\n joined_dict(\n {\n \"path\": self._settings.getBaseFolder(\"logs\"),\n \"mime_type_guesser\": lambda *args, **kwargs: \"text/plain\",\n \"stream_body\": True,\n },\n download_handler_kwargs,\n log_permission_validator,\n log_path_validator,\n ),\n ),\n # zipped log file bundles\n (\n r\"/downloads/logs\",\n util.tornado.DynamicZipBundleHandler,\n joined_dict(\n {\n \"as_attachment\": True,\n \"attachment_name\": \"octoprint-logs.zip\",\n \"path_processor\": lambda x: (\n x,\n os.path.join(self._settings.getBaseFolder(\"logs\"), x),\n ),\n },\n log_permission_validator,\n logs_path_validator,\n ),\n ),\n # system info bundle\n (\n r\"/downloads/systeminfo.zip\",\n util.tornado.SystemInfoBundleHandler,\n systeminfo_permission_validator,\n ),\n # camera snapshot\n (\n r\"/downloads/camera/current\",\n util.tornado.UrlProxyHandler,\n joined_dict(\n {\n \"url\": self._settings.get([\"webcam\", \"snapshot\"]),\n \"as_attachment\": True,\n },\n camera_permission_validator,\n ),\n ),\n # generated webassets\n (\n r\"/static/webassets/(.*)\",\n util.tornado.LargeResponseHandler,\n {\n \"path\": os.path.join(\n self._settings.getBaseFolder(\"generated\"), \"webassets\"\n ),\n \"is_pre_compressed\": True,\n },\n ),\n # online indicators - text file with \"online\" as content and a transparent gif\n (r\"/online.txt\", util.tornado.StaticDataHandler, {\"data\": \"online\\n\"}),\n (\n r\"/online.gif\",\n util.tornado.StaticDataHandler,\n {\n \"data\": bytes(\n base64.b64decode(\n \"R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7\"\n )\n ),\n \"content_type\": \"image/gif\",\n },\n ),\n # deprecated endpoints\n (\n r\"/api/logs\",\n util.tornado.DeprecatedEndpointHandler,\n {\"url\": \"/plugin/logging/logs\"},\n ),\n (\n r\"/api/logs/(.*)\",\n util.tornado.DeprecatedEndpointHandler,\n {\"url\": \"/plugin/logging/logs/{0}\"},\n ),\n ]", " # fetch additional routes from plugins\n for name, hook in pluginManager.get_hooks(\"octoprint.server.http.routes\").items():\n try:\n result = hook(list(server_routes))\n except Exception:\n self._logger.exception(\n f\"There was an error while retrieving additional \"\n f\"server routes from plugin hook {name}\",\n extra={\"plugin\": name},\n )\n else:\n if isinstance(result, (list, tuple)):\n for entry in result:\n if not isinstance(entry, tuple) or not len(entry) == 3:\n continue\n if not isinstance(entry[0], str):\n continue\n if not isinstance(entry[2], dict):\n continue", " route, handler, kwargs = entry\n route = r\"/plugin/{name}/{route}\".format(\n name=name,\n route=route if not route.startswith(\"/\") else route[1:],\n )", " self._logger.debug(\n f\"Adding additional route {route} handled by handler {handler} and with additional arguments {kwargs!r}\"\n )\n server_routes.append((route, handler, kwargs))", " headers = {\n \"X-Robots-Tag\": \"noindex, nofollow, noimageindex\",\n \"X-Content-Type-Options\": \"nosniff\",\n }\n if not settings().getBoolean([\"server\", \"allowFraming\"]):\n headers[\"X-Frame-Options\"] = \"sameorigin\"", " removed_headers = [\"Server\"]", " server_routes.append(\n (\n r\".*\",\n util.tornado.UploadStorageFallbackHandler,\n {\n \"fallback\": util.tornado.WsgiInputContainer(\n app.wsgi_app, headers=headers, removed_headers=removed_headers\n ),\n \"file_prefix\": \"octoprint-file-upload-\",\n \"file_suffix\": \".tmp\",\n \"suffixes\": upload_suffixes,\n },\n )\n )", " transforms = [\n util.tornado.GlobalHeaderTransform.for_headers(\n \"OctoPrintGlobalHeaderTransform\",\n headers=headers,\n removed_headers=removed_headers,\n )\n ]", " self._tornado_app = Application(handlers=server_routes, transforms=transforms)\n max_body_sizes = [\n (\n \"POST\",\n r\"/api/files/([^/]*)\",\n self._settings.getInt([\"server\", \"uploads\", \"maxSize\"]),\n ),\n (\"POST\", r\"/api/languages\", 5 * 1024 * 1024),\n ]", " # allow plugins to extend allowed maximum body sizes\n for name, hook in pluginManager.get_hooks(\n \"octoprint.server.http.bodysize\"\n ).items():\n try:\n result = hook(list(max_body_sizes))\n except Exception:\n self._logger.exception(\n f\"There was an error while retrieving additional \"\n f\"upload sizes from plugin hook {name}\",\n extra={\"plugin\": name},\n )\n else:\n if isinstance(result, (list, tuple)):\n for entry in result:\n if not isinstance(entry, tuple) or not len(entry) == 3:\n continue\n if (\n entry[0]\n not in util.tornado.UploadStorageFallbackHandler.BODY_METHODS\n ):\n continue\n if not isinstance(entry[2], int):\n continue", " method, route, size = entry\n route = r\"/plugin/{name}/{route}\".format(\n name=name,\n route=route if not route.startswith(\"/\") else route[1:],\n )", " self._logger.debug(\n f\"Adding maximum body size of {size}B for {method} requests to {route})\"\n )\n max_body_sizes.append((method, route, size))", " self._stop_intermediary_server()", " # initialize and bind the server\n trusted_downstream = self._settings.get(\n [\"server\", \"reverseProxy\", \"trustedDownstream\"]\n )\n if not isinstance(trusted_downstream, list):\n self._logger.warning(\n \"server.reverseProxy.trustedDownstream is not a list, skipping\"\n )\n trusted_downstream = []", " server_kwargs = {\n \"max_body_sizes\": max_body_sizes,\n \"default_max_body_size\": self._settings.getInt([\"server\", \"maxSize\"]),\n \"xheaders\": True,\n \"trusted_downstream\": trusted_downstream,\n }\n if sys.platform == \"win32\":\n # set 10min idle timeout under windows to hopefully make #2916 less likely\n server_kwargs.update({\"idle_connection_timeout\": 600})", " self._server = util.tornado.CustomHTTPServer(self._tornado_app, **server_kwargs)", " listening_address = self._host\n if self._host == \"::\" and not self._v6_only:\n # special case - tornado only listens on v4 _and_ v6 if we use None as address\n listening_address = None", " self._server.listen(self._port, address=listening_address)", " ### From now on it's ok to launch subprocesses again", " eventManager.fire(events.Events.STARTUP)", " # analysis backlog\n fileManager.process_backlog()", " # auto connect\n if self._settings.getBoolean([\"serial\", \"autoconnect\"]):\n self._logger.info(\n \"Autoconnect on startup is configured, trying to connect to the printer...\"\n )\n try:\n (port, baudrate) = (\n self._settings.get([\"serial\", \"port\"]),\n self._settings.getInt([\"serial\", \"baudrate\"]),\n )\n printer_profile = printerProfileManager.get_default()\n connectionOptions = printer.__class__.get_connection_options()\n if port in connectionOptions[\"ports\"] or port == \"AUTO\" or port is None:\n self._logger.info(\n f\"Trying to connect to configured serial port {port}\"\n )\n printer.connect(\n port=port,\n baudrate=baudrate,\n profile=printer_profile[\"id\"]\n if \"id\" in printer_profile\n else \"_default\",\n )\n else:\n self._logger.info(\n \"Could not find configured serial port {} in the system, cannot automatically connect to a non existing printer. Is it plugged in and booted up yet?\"\n )\n except Exception:\n self._logger.exception(\n \"Something went wrong while attempting to automatically connect to the printer\"\n )", " # start up watchdogs\n try:\n watched = self._settings.getBaseFolder(\"watched\")\n watchdog_handler = util.watchdog.GcodeWatchdogHandler(fileManager, printer)\n watchdog_handler.initial_scan(watched)", " if self._settings.getBoolean([\"feature\", \"pollWatched\"]):\n # use less performant polling observer if explicitly configured\n observer = PollingObserver()\n else:\n # use os default\n observer = Observer()", " observer.schedule(watchdog_handler, watched, recursive=True)\n observer.start()\n except Exception:\n self._logger.exception(\"Error starting watched folder observer\")", " # run our startup plugins\n octoprint.plugin.call_plugin(\n octoprint.plugin.StartupPlugin,\n \"on_startup\",\n args=(self._host, self._port),\n sorting_context=\"StartupPlugin.on_startup\",\n )", " def call_on_startup(name, plugin):\n implementation = plugin.get_implementation(octoprint.plugin.StartupPlugin)\n if implementation is None:\n return\n implementation.on_startup(self._host, self._port)", " pluginLifecycleManager.add_callback(\"enabled\", call_on_startup)", " # prepare our after startup function\n def on_after_startup():\n if self._host == \"::\":\n if self._v6_only:\n # only v6\n self._logger.info(f\"Listening on http://[::]:{self._port}\")\n else:\n # all v4 and v6\n self._logger.info(\n \"Listening on http://0.0.0.0:{port} and http://[::]:{port}\".format(\n port=self._port\n )\n )\n else:\n self._logger.info(\n \"Listening on http://{}:{}\".format(\n self._host if \":\" not in self._host else \"[\" + self._host + \"]\",\n self._port,\n )\n )", " if safe_mode and self._settings.getBoolean([\"server\", \"startOnceInSafeMode\"]):\n self._logger.info(\n \"Server started successfully in safe mode as requested from config, removing flag\"\n )\n self._settings.setBoolean([\"server\", \"startOnceInSafeMode\"], False)\n self._settings.save()", " # now this is somewhat ugly, but the issue is the following: startup plugins might want to do things for\n # which they need the server to be already alive (e.g. for being able to resolve urls, such as favicons\n # or service xmls or the like). While they are working though the ioloop would block. Therefore we'll\n # create a single use thread in which to perform our after-startup-tasks, start that and hand back\n # control to the ioloop\n def work():\n octoprint.plugin.call_plugin(\n octoprint.plugin.StartupPlugin,\n \"on_after_startup\",\n sorting_context=\"StartupPlugin.on_after_startup\",\n )", " def call_on_after_startup(name, plugin):\n implementation = plugin.get_implementation(\n octoprint.plugin.StartupPlugin\n )\n if implementation is None:\n return\n implementation.on_after_startup()", " pluginLifecycleManager.add_callback(\"enabled\", call_on_after_startup)", " # if there was a rogue plugin we wouldn't even have made it here, so remove startup triggered safe mode\n # flag again...\n self._settings.setBoolean([\"server\", \"incompleteStartup\"], False)\n self._settings.save()", " # make a backup of the current config\n self._settings.backup(ext=\"backup\")", " # when we are through with that we also run our preemptive cache\n if settings().getBoolean([\"devel\", \"cache\", \"preemptive\"]):\n self._execute_preemptive_flask_caching(preemptiveCache)", " import threading", " threading.Thread(target=work).start()", " ioloop.add_callback(on_after_startup)", " # prepare our shutdown function\n def on_shutdown():\n # will be called on clean system exit and shutdown the watchdog observer and call the on_shutdown methods\n # on all registered ShutdownPlugins\n self._logger.info(\"Shutting down...\")\n observer.stop()\n observer.join()\n eventManager.fire(events.Events.SHUTDOWN)", " self._logger.info(\"Calling on_shutdown on plugins\")\n octoprint.plugin.call_plugin(\n octoprint.plugin.ShutdownPlugin,\n \"on_shutdown\",\n sorting_context=\"ShutdownPlugin.on_shutdown\",\n )", " # wait for shutdown event to be processed, but maximally for 15s\n event_timeout = 15.0\n if eventManager.join(timeout=event_timeout):\n self._logger.warning(\n \"Event loop was still busy processing after {}s, shutting down anyhow\".format(\n event_timeout\n )\n )", " if self._octoprint_daemon is not None:\n self._logger.info(\"Cleaning up daemon pidfile\")\n self._octoprint_daemon.terminated()", " self._logger.info(\"Goodbye!\")", " atexit.register(on_shutdown)", " def sigterm_handler(*args, **kwargs):\n # will stop tornado on SIGTERM, making the program exit cleanly\n def shutdown_tornado():\n self._logger.debug(\"Shutting down tornado's IOLoop...\")\n ioloop.stop()", " self._logger.debug(\"SIGTERM received...\")\n ioloop.add_callback_from_signal(shutdown_tornado)", " signal.signal(signal.SIGTERM, sigterm_handler)", " try:\n # this is the main loop - as long as tornado is running, OctoPrint is running\n ioloop.start()\n self._logger.debug(\"Tornado's IOLoop stopped\")\n except (KeyboardInterrupt, SystemExit):\n pass\n except Exception:\n self._logger.fatal(\n \"Now that is embarrassing... Something really really went wrong here. Please report this including the stacktrace below in OctoPrint's bugtracker. Thanks!\"\n )\n self._logger.exception(\"Stacktrace follows:\")", " def _log_safe_mode_start(self, self_mode):\n self_mode_file = os.path.join(\n self._settings.getBaseFolder(\"data\"), \"last_safe_mode\"\n )\n try:\n with open(self_mode_file, \"w+\", encoding=\"utf-8\") as f:\n f.write(self_mode)\n except Exception as ex:\n self._logger.warn(f\"Could not write safe mode file {self_mode_file}: {ex}\")", " def _create_socket_connection(self, session):\n global printer, fileManager, analysisQueue, userManager, eventManager, connectivityChecker\n return util.sockjs.PrinterStateConnection(\n printer,\n fileManager,\n analysisQueue,\n userManager,\n groupManager,\n eventManager,\n pluginManager,\n connectivityChecker,\n session,\n )", " def _check_for_root(self):\n if \"geteuid\" in dir(os) and os.geteuid() == 0:\n exit(\"You should not run OctoPrint as root!\")", " def _get_locale(self):\n global LANGUAGES", " if \"l10n\" in request.values:\n return Locale.negotiate([request.values[\"l10n\"]], LANGUAGES)", " if \"X-Locale\" in request.headers:\n return Locale.negotiate([request.headers[\"X-Locale\"]], LANGUAGES)", " if hasattr(g, \"identity\") and g.identity:\n userid = g.identity.id\n try:\n user_language = userManager.get_user_setting(\n userid, (\"interface\", \"language\")\n )\n if user_language is not None and not user_language == \"_default\":\n return Locale.negotiate([user_language], LANGUAGES)\n except octoprint.access.users.UnknownUser:\n pass", " default_language = self._settings.get([\"appearance\", \"defaultLanguage\"])\n if (\n default_language is not None\n and not default_language == \"_default\"\n and default_language in LANGUAGES\n ):\n return Locale.negotiate([default_language], LANGUAGES)", " return Locale.parse(request.accept_languages.best_match(LANGUAGES))", " def _setup_heartbeat_logging(self):\n logger = logging.getLogger(__name__ + \".heartbeat\")", " def log_heartbeat():\n logger.info(\"Server heartbeat <3\")", " interval = settings().getFloat([\"server\", \"heartbeat\"])\n logger.info(f\"Starting server heartbeat, {interval}s interval\")", " timer = octoprint.util.RepeatedTimer(interval, log_heartbeat)\n timer.start()", " def _setup_app(self, app):\n global limiter", " from octoprint.server.util.flask import (\n OctoPrintFlaskRequest,\n OctoPrintFlaskResponse,\n OctoPrintJsonEncoder,\n OctoPrintSessionInterface,\n PrefixAwareJinjaEnvironment,\n ReverseProxiedEnvironment,\n )", " # we must set this here because setting app.debug will access app.jinja_env\n app.jinja_environment = PrefixAwareJinjaEnvironment", " app.config[\"TEMPLATES_AUTO_RELOAD\"] = True\n app.config[\"JSONIFY_PRETTYPRINT_REGULAR\"] = False\n app.config[\"REMEMBER_COOKIE_HTTPONLY\"] = True", " # we must not set this before TEMPLATES_AUTO_RELOAD is set to True or that won't take\n app.debug = self._debug", " # setup octoprint's flask json serialization/deserialization\n app.json_encoder = OctoPrintJsonEncoder", " s = settings()", " secret_key = s.get([\"server\", \"secretKey\"])\n if not secret_key:\n import string\n from random import choice", " chars = string.ascii_lowercase + string.ascii_uppercase + string.digits\n secret_key = \"\".join(choice(chars) for _ in range(32))\n s.set([\"server\", \"secretKey\"], secret_key)\n s.save()", " app.secret_key = secret_key", " reverse_proxied = ReverseProxiedEnvironment(\n header_prefix=s.get([\"server\", \"reverseProxy\", \"prefixHeader\"]),\n header_scheme=s.get([\"server\", \"reverseProxy\", \"schemeHeader\"]),\n header_host=s.get([\"server\", \"reverseProxy\", \"hostHeader\"]),\n header_server=s.get([\"server\", \"reverseProxy\", \"serverHeader\"]),\n header_port=s.get([\"server\", \"reverseProxy\", \"portHeader\"]),\n prefix=s.get([\"server\", \"reverseProxy\", \"prefixFallback\"]),\n scheme=s.get([\"server\", \"reverseProxy\", \"schemeFallback\"]),\n host=s.get([\"server\", \"reverseProxy\", \"hostFallback\"]),\n server=s.get([\"server\", \"reverseProxy\", \"serverFallback\"]),\n port=s.get([\"server\", \"reverseProxy\", \"portFallback\"]),\n )", " OctoPrintFlaskRequest.environment_wrapper = reverse_proxied\n app.request_class = OctoPrintFlaskRequest\n app.response_class = OctoPrintFlaskResponse\n app.session_interface = OctoPrintSessionInterface()", " @app.before_request\n def before_request():\n g.locale = self._get_locale()", " # used for performance measurement\n g.start_time = time.monotonic()", " if self._debug and \"perfprofile\" in request.args:\n try:\n from pyinstrument import Profiler", " g.perfprofiler = Profiler()\n g.perfprofiler.start()\n except ImportError:\n # profiler dependency not installed, ignore\n pass", " @app.after_request\n def after_request(response):\n # send no-cache headers with all POST responses\n if request.method == \"POST\":\n response.cache_control.no_cache = True", " response.headers.add(\"X-Clacks-Overhead\", \"GNU Terry Pratchett\")", " if hasattr(g, \"perfprofiler\"):\n g.perfprofiler.stop()\n output_html = g.perfprofiler.output_html()\n return make_response(output_html)", " if hasattr(g, \"start_time\"):\n end_time = time.monotonic()\n duration_ms = int((end_time - g.start_time) * 1000)\n response.headers.add(\"Server-Timing\", f\"app;dur={duration_ms}\")", " return response", " from octoprint.util.jinja import MarkdownFilter", " MarkdownFilter(app)", " from flask_limiter import Limiter\n from flask_limiter.util import get_remote_address", " app.config[\"RATELIMIT_STRATEGY\"] = \"fixed-window-elastic-expiry\"", " limiter = Limiter(app, key_func=get_remote_address)", " def _setup_i18n(self, app):\n global babel\n global LOCALES\n global LANGUAGES", " babel = Babel(app)", " def get_available_locale_identifiers(locales):\n result = set()", " # add available translations\n for locale in locales:\n result.add(locale.language)\n if locale.territory:\n # if a territory is specified, add that too\n result.add(f\"{locale.language}_{locale.territory}\")", " return result", " LOCALES = babel.list_translations()\n LANGUAGES = get_available_locale_identifiers(LOCALES)", " @babel.localeselector\n def get_locale():\n return self._get_locale()", " def _setup_jinja2(self):\n import re", " app.jinja_env.add_extension(\"jinja2.ext.do\")\n app.jinja_env.add_extension(\"octoprint.util.jinja.trycatch\")", " def regex_replace(s, find, replace):\n return re.sub(find, replace, s)", " html_header_regex = re.compile(\n r\"<h(?P<number>[1-6])>(?P<content>.*?)</h(?P=number)>\"\n )", " def offset_html_headers(s, offset):\n def repl(match):\n number = int(match.group(\"number\"))\n number += offset\n if number > 6:\n number = 6\n elif number < 1:\n number = 1\n return \"<h{number}>{content}</h{number}>\".format(\n number=number, content=match.group(\"content\")\n )", " return html_header_regex.sub(repl, s)", " markdown_header_regex = re.compile(\n r\"^(?P<hashs>#+)\\s+(?P<content>.*)$\", flags=re.MULTILINE\n )", " def offset_markdown_headers(s, offset):\n def repl(match):\n number = len(match.group(\"hashs\"))\n number += offset\n if number > 6:\n number = 6\n elif number < 1:\n number = 1\n return \"{hashs} {content}\".format(\n hashs=\"#\" * number, content=match.group(\"content\")\n )", " return markdown_header_regex.sub(repl, s)", " html_link_regex = re.compile(r\"<(?P<tag>a.*?)>(?P<content>.*?)</a>\")", " def externalize_links(text):\n def repl(match):\n tag = match.group(\"tag\")\n if \"href\" not in tag:\n return match.group(0)", " if \"target=\" not in tag and \"rel=\" not in tag:\n tag += ' target=\"_blank\" rel=\"noreferrer noopener\"'", " content = match.group(\"content\")\n return f\"<{tag}>{content}</a>\"", " return html_link_regex.sub(repl, text)", " single_quote_regex = re.compile(\"(?<!\\\\\\\\)'\")", " def escape_single_quote(text):\n return single_quote_regex.sub(\"\\\\'\", text)", " double_quote_regex = re.compile('(?<!\\\\\\\\)\"')", " def escape_double_quote(text):\n return double_quote_regex.sub('\\\\\"', text)", " app.jinja_env.filters[\"regex_replace\"] = regex_replace\n app.jinja_env.filters[\"offset_html_headers\"] = offset_html_headers\n app.jinja_env.filters[\"offset_markdown_headers\"] = offset_markdown_headers\n app.jinja_env.filters[\"externalize_links\"] = externalize_links\n app.jinja_env.filters[\"escape_single_quote\"] = app.jinja_env.filters[\n \"esq\"\n ] = escape_single_quote\n app.jinja_env.filters[\"escape_double_quote\"] = app.jinja_env.filters[\n \"edq\"\n ] = escape_double_quote", " # configure additional template folders for jinja2\n import jinja2", " import octoprint.util.jinja", " app.jinja_env.prefix_loader = jinja2.PrefixLoader({})", " loaders = [app.jinja_loader, app.jinja_env.prefix_loader]\n if octoprint.util.is_running_from_source():\n root = os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../..\"))\n allowed = [\"AUTHORS.md\", \"SUPPORTERS.md\", \"THIRDPARTYLICENSES.md\"]\n files = {\"_data/\" + name: os.path.join(root, name) for name in allowed}\n loaders.append(octoprint.util.jinja.SelectedFilesWithConversionLoader(files))", " # TODO: Remove this in 2.0.0\n warning_message = \"Loading plugin template '{template}' from '{filename}' without plugin prefix, this is deprecated and will soon no longer be supported.\"\n loaders.append(\n octoprint.util.jinja.WarningLoader(\n octoprint.util.jinja.PrefixChoiceLoader(app.jinja_env.prefix_loader),\n warning_message,\n )\n )", " app.jinja_loader = jinja2.ChoiceLoader(loaders)", " self._register_template_plugins()", " # make sure plugin lifecycle events relevant for jinja2 are taken care of\n def template_enabled(name, plugin):\n if plugin.implementation is None or not isinstance(\n plugin.implementation, octoprint.plugin.TemplatePlugin\n ):\n return\n self._register_additional_template_plugin(plugin.implementation)", " def template_disabled(name, plugin):\n if plugin.implementation is None or not isinstance(\n plugin.implementation, octoprint.plugin.TemplatePlugin\n ):\n return\n self._unregister_additional_template_plugin(plugin.implementation)", " pluginLifecycleManager.add_callback(\"enabled\", template_enabled)\n pluginLifecycleManager.add_callback(\"disabled\", template_disabled)", " def _execute_preemptive_flask_caching(self, preemptive_cache):\n import time", " from werkzeug.test import EnvironBuilder", " # we clean up entries from our preemptive cache settings that haven't been\n # accessed longer than server.preemptiveCache.until days\n preemptive_cache_timeout = settings().getInt(\n [\"server\", \"preemptiveCache\", \"until\"]\n )\n cutoff_timestamp = time.time() - preemptive_cache_timeout * 24 * 60 * 60", " def filter_current_entries(entry):\n \"\"\"Returns True for entries younger than the cutoff date\"\"\"\n return \"_timestamp\" in entry and entry[\"_timestamp\"] > cutoff_timestamp", " def filter_http_entries(entry):\n \"\"\"Returns True for entries targeting http or https.\"\"\"\n return (\n \"base_url\" in entry\n and entry[\"base_url\"]\n and (\n entry[\"base_url\"].startswith(\"http://\")\n or entry[\"base_url\"].startswith(\"https://\")\n )\n )", " def filter_entries(entry):\n \"\"\"Combined filter.\"\"\"\n filters = (filter_current_entries, filter_http_entries)\n return all([f(entry) for f in filters])", " # filter out all old and non-http entries\n cache_data = preemptive_cache.clean_all_data(\n lambda root, entries: list(filter(filter_entries, entries))\n )\n if not cache_data:\n return", " def execute_caching():\n logger = logging.getLogger(__name__ + \".preemptive_cache\")", " for route in sorted(cache_data.keys(), key=lambda x: (x.count(\"/\"), x)):\n entries = reversed(\n sorted(cache_data[route], key=lambda x: x.get(\"_count\", 0))\n )\n for kwargs in entries:\n plugin = kwargs.get(\"plugin\", None)\n if plugin:\n try:\n plugin_info = pluginManager.get_plugin_info(\n plugin, require_enabled=True\n )\n if plugin_info is None:\n logger.info(\n \"About to preemptively cache plugin {} but it is not installed or enabled, preemptive caching makes no sense\".format(\n plugin\n )\n )\n continue", " implementation = plugin_info.implementation\n if implementation is None or not isinstance(\n implementation, octoprint.plugin.UiPlugin\n ):\n logger.info(\n \"About to preemptively cache plugin {} but it is not a UiPlugin, preemptive caching makes no sense\".format(\n plugin\n )\n )\n continue\n if not implementation.get_ui_preemptive_caching_enabled():\n logger.info(\n \"About to preemptively cache plugin {} but it has disabled preemptive caching\".format(\n plugin\n )\n )\n continue\n except Exception:\n logger.exception(\n \"Error while trying to check if plugin {} has preemptive caching enabled, skipping entry\"\n )\n continue", " additional_request_data = kwargs.get(\"_additional_request_data\", {})\n kwargs = {\n k: v\n for k, v in kwargs.items()\n if not k.startswith(\"_\") and not k == \"plugin\"\n }\n kwargs.update(additional_request_data)", " try:\n start = time.monotonic()\n if plugin:\n logger.info(\n \"Preemptively caching {} (ui {}) for {!r}\".format(\n route, plugin, kwargs\n )\n )\n else:\n logger.info(\n \"Preemptively caching {} (ui _default) for {!r}\".format(\n route, kwargs\n )\n )", " headers = kwargs.get(\"headers\", {})\n headers[\"X-Force-View\"] = plugin if plugin else \"_default\"\n headers[\"X-Preemptive-Recording\"] = \"yes\"\n kwargs[\"headers\"] = headers", " builder = EnvironBuilder(**kwargs)\n app(builder.get_environ(), lambda *a, **kw: None)", " logger.info(f\"... done in {time.monotonic() - start:.2f}s\")\n except Exception:\n logger.exception(\n \"Error while trying to preemptively cache {} for {!r}\".format(\n route, kwargs\n )\n )", " # asynchronous caching\n import threading", " cache_thread = threading.Thread(\n target=execute_caching, name=\"Preemptive Cache Worker\"\n )\n cache_thread.daemon = True\n cache_thread.start()", " def _register_template_plugins(self):\n template_plugins = pluginManager.get_implementations(\n octoprint.plugin.TemplatePlugin\n )\n for plugin in template_plugins:\n try:\n self._register_additional_template_plugin(plugin)\n except Exception:\n self._logger.exception(\n \"Error while trying to register templates of plugin {}, ignoring it\".format(\n plugin._identifier\n )\n )", " def _register_additional_template_plugin(self, plugin):\n import octoprint.util.jinja", " folder = plugin.get_template_folder()\n if (\n folder is not None\n and plugin.template_folder_key not in app.jinja_env.prefix_loader.mapping\n ):\n loader = octoprint.util.jinja.FilteredFileSystemLoader(\n [plugin.get_template_folder()],\n path_filter=lambda x: not octoprint.util.is_hidden_path(x),\n )", " app.jinja_env.prefix_loader.mapping[plugin.template_folder_key] = loader", " def _unregister_additional_template_plugin(self, plugin):\n folder = plugin.get_template_folder()\n if (\n folder is not None\n and plugin.template_folder_key in app.jinja_env.prefix_loader.mapping\n ):\n del app.jinja_env.prefix_loader.mapping[plugin.template_folder_key]", " def _setup_blueprints(self):\n # do not remove or the index view won't be found\n import octoprint.server.views # noqa: F401\n from octoprint.server.api import api\n from octoprint.server.util.flask import make_api_error", " blueprints = [api]\n api_endpoints = [\"/api\"]\n registrators = [functools.partial(app.register_blueprint, api, url_prefix=\"/api\")]", " # also register any blueprints defined in BlueprintPlugins\n (\n blueprints_from_plugins,\n api_endpoints_from_plugins,\n registrators_from_plugins,\n ) = self._prepare_blueprint_plugins()\n blueprints += blueprints_from_plugins\n api_endpoints += api_endpoints_from_plugins\n registrators += registrators_from_plugins", " # and register a blueprint for serving the static files of asset plugins which are not blueprint plugins themselves\n (blueprints_from_assets, registrators_from_assets) = self._prepare_asset_plugins()\n blueprints += blueprints_from_assets\n registrators += registrators_from_assets", " # make sure all before/after_request hook results are attached as well\n self._add_plugin_request_handlers_to_blueprints(*blueprints)", " # register everything with the system\n for registrator in registrators:\n registrator()", " @app.errorhandler(HTTPException)\n def _handle_api_error(ex):\n if any(map(lambda x: request.path.startswith(x), api_endpoints)):\n return make_api_error(ex.description, ex.code)\n else:\n return ex", " def _prepare_blueprint_plugins(self):\n def register_plugin_blueprint(plugin, blueprint, url_prefix):\n try:\n app.register_blueprint(\n blueprint, url_prefix=url_prefix, name_prefix=\"plugin\"\n )\n self._logger.debug(\n f\"Registered API of plugin {plugin} under URL prefix {url_prefix}\"\n )\n except Exception:\n self._logger.exception(\n f\"Error while registering blueprint of plugin {plugin}, ignoring it\",\n extra={\"plugin\": plugin},\n )", " blueprints = []\n api_endpoints = []\n registrators = []", " blueprint_plugins = octoprint.plugin.plugin_manager().get_implementations(\n octoprint.plugin.BlueprintPlugin\n )\n for plugin in blueprint_plugins:\n blueprint, prefix = self._prepare_blueprint_plugin(plugin)", " blueprints.append(blueprint)\n api_endpoints += map(\n lambda x: prefix + x, plugin.get_blueprint_api_prefixes()\n )\n registrators.append(\n functools.partial(\n register_plugin_blueprint, plugin._identifier, blueprint, prefix\n )\n )", " return blueprints, api_endpoints, registrators", " def _prepare_asset_plugins(self):\n def register_asset_blueprint(plugin, blueprint, url_prefix):\n try:\n app.register_blueprint(\n blueprint, url_prefix=url_prefix, name_prefix=\"plugin\"\n )\n self._logger.debug(\n f\"Registered assets of plugin {plugin} under URL prefix {url_prefix}\"\n )\n except Exception:\n self._logger.exception(\n f\"Error while registering blueprint of plugin {plugin}, ignoring it\",\n extra={\"plugin\": plugin},\n )", " blueprints = []\n registrators = []", " asset_plugins = octoprint.plugin.plugin_manager().get_implementations(\n octoprint.plugin.AssetPlugin\n )\n for plugin in asset_plugins:\n if isinstance(plugin, octoprint.plugin.BlueprintPlugin):\n continue\n blueprint, prefix = self._prepare_asset_plugin(plugin)", " blueprints.append(blueprint)\n registrators.append(\n functools.partial(\n register_asset_blueprint, plugin._identifier, blueprint, prefix\n )\n )", " return blueprints, registrators", " def _prepare_blueprint_plugin(self, plugin):\n name = plugin._identifier\n blueprint = plugin.get_blueprint()\n if blueprint is None:\n return", " blueprint.before_request(corsRequestHandler)\n blueprint.before_request(loginFromApiKeyRequestHandler)\n blueprint.after_request(corsResponseHandler)", " if plugin.is_blueprint_protected():\n blueprint.before_request(requireLoginRequestHandler)", " url_prefix = f\"/plugin/{name}\"\n return blueprint, url_prefix", " def _prepare_asset_plugin(self, plugin):\n name = plugin._identifier", " url_prefix = f\"/plugin/{name}\"\n blueprint = Blueprint(name, name, static_folder=plugin.get_asset_folder())\n return blueprint, url_prefix", " def _add_plugin_request_handlers_to_blueprints(self, *blueprints):\n before_hooks = octoprint.plugin.plugin_manager().get_hooks(\n \"octoprint.server.api.before_request\"\n )\n after_hooks = octoprint.plugin.plugin_manager().get_hooks(\n \"octoprint.server.api.after_request\"\n )", " for name, hook in before_hooks.items():\n plugin = octoprint.plugin.plugin_manager().get_plugin(name)\n for blueprint in blueprints:\n try:\n result = hook(plugin=plugin)\n if isinstance(result, (list, tuple)):\n for h in result:\n blueprint.before_request(h)\n except Exception:\n self._logger.exception(\n \"Error processing before_request hooks from plugin {}\".format(\n plugin\n ),\n extra={\"plugin\": name},\n )", " for name, hook in after_hooks.items():\n plugin = octoprint.plugin.plugin_manager().get_plugin(name)\n for blueprint in blueprints:\n try:\n result = hook(plugin=plugin)\n if isinstance(result, (list, tuple)):\n for h in result:\n blueprint.after_request(h)\n except Exception:\n self._logger.exception(\n \"Error processing after_request hooks from plugin {}\".format(\n plugin\n ),\n extra={\"plugin\": name},\n )", " def _setup_mimetypes(self):\n # Safety measures for Windows... apparently the mimetypes module takes its translation from the windows\n # registry, and if for some weird reason that gets borked the reported MIME types can be all over the place.\n # Since at least in Chrome that can cause hilarious issues with JS files (refusal to run them and thus a\n # borked UI) we make sure that .js always maps to the correct application/javascript, and also throw in a\n # .css -> text/css for good measure.\n #\n # See #3367\n mimetypes.add_type(\"application/javascript\", \".js\")\n mimetypes.add_type(\"text/css\", \".css\")", " def _setup_assets(self):\n global app\n global assets\n global pluginManager", " from octoprint.server.util.webassets import MemoryManifest # noqa: F401", " util.flask.fix_webassets_filtertool()", " base_folder = self._settings.getBaseFolder(\"generated\")", " # clean the folder\n if self._settings.getBoolean([\"devel\", \"webassets\", \"clean_on_startup\"]):\n import errno\n import shutil", " for entry, recreate in (\n (\"webassets\", True),\n # no longer used, but clean up just in case\n (\".webassets-cache\", False),\n (\".webassets-manifest.json\", False),\n ):\n path = os.path.join(base_folder, entry)", " # delete path if it exists\n if os.path.exists(path):\n try:\n self._logger.debug(f\"Deleting {path}...\")\n if os.path.isdir(path):\n shutil.rmtree(path)\n else:\n os.remove(path)\n except Exception:\n self._logger.exception(\n f\"Error while trying to delete {path}, \" f\"leaving it alone\"\n )\n continue", " # re-create path if necessary\n if recreate:\n self._logger.debug(f\"Creating {path}...\")\n error_text = (\n f\"Error while trying to re-create {path}, that might cause \"\n f\"errors with the webassets cache\"\n )\n try:\n os.makedirs(path)\n except OSError as e:\n if e.errno == errno.EACCES:\n # that might be caused by the user still having the folder open somewhere, let's try again after\n # waiting a bit\n import time", " for n in range(3):\n time.sleep(0.5)\n self._logger.debug(\n \"Creating {path}: Retry #{retry} after {time}s\".format(\n path=path, retry=n + 1, time=(n + 1) * 0.5\n )\n )\n try:\n os.makedirs(path)\n break\n except Exception:\n if self._logger.isEnabledFor(logging.DEBUG):\n self._logger.exception(\n f\"Ignored error while creating \"\n f\"directory {path}\"\n )\n pass\n else:\n # this will only get executed if we never did\n # successfully execute makedirs above\n self._logger.exception(error_text)\n continue\n else:\n # not an access error, so something we don't understand\n # went wrong -> log an error and stop\n self._logger.exception(error_text)\n continue\n except Exception:\n # not an OSError, so something we don't understand\n # went wrong -> log an error and stop\n self._logger.exception(error_text)\n continue", " self._logger.info(f\"Reset webasset folder {path}...\")", " AdjustedEnvironment = type(Environment)(\n Environment.__name__,\n (Environment,),\n {\"resolver_class\": util.flask.PluginAssetResolver},\n )", " class CustomDirectoryEnvironment(AdjustedEnvironment):\n @property\n def directory(self):\n return base_folder", " assets = CustomDirectoryEnvironment(app)\n assets.debug = not self._settings.getBoolean([\"devel\", \"webassets\", \"bundle\"])", " # we should rarely if ever regenerate the webassets in production and can wait a\n # few seconds for regeneration in development, if it means we can get rid of\n # a whole monkey patch and in internal use of pickle with non-tamperproof files\n assets.cache = False\n assets.manifest = \"memory\"", " UpdaterType = type(util.flask.SettingsCheckUpdater)(\n util.flask.SettingsCheckUpdater.__name__,\n (util.flask.SettingsCheckUpdater,),\n {\"updater\": assets.updater},\n )\n assets.updater = UpdaterType", " preferred_stylesheet = self._settings.get([\"devel\", \"stylesheet\"])", " dynamic_core_assets = util.flask.collect_core_assets()\n dynamic_plugin_assets = util.flask.collect_plugin_assets(\n preferred_stylesheet=preferred_stylesheet\n )", " js_libs = [\n \"js/lib/babel-polyfill.min.js\",\n \"js/lib/jquery/jquery.min.js\",\n \"js/lib/modernizr.custom.js\",\n \"js/lib/lodash.min.js\",\n \"js/lib/sprintf.min.js\",\n \"js/lib/knockout.js\",\n \"js/lib/knockout.mapping-latest.js\",\n \"js/lib/babel.js\",\n \"js/lib/bootstrap/bootstrap.js\",\n \"js/lib/bootstrap/bootstrap-modalmanager.js\",\n \"js/lib/bootstrap/bootstrap-modal.js\",\n \"js/lib/bootstrap/bootstrap-slider.js\",\n \"js/lib/bootstrap/bootstrap-tabdrop.js\",\n \"js/lib/jquery/jquery-ui.js\",\n \"js/lib/jquery/jquery.flot.js\",\n \"js/lib/jquery/jquery.flot.time.js\",\n \"js/lib/jquery/jquery.flot.crosshair.js\",\n \"js/lib/jquery/jquery.flot.resize.js\",\n \"js/lib/jquery/jquery.iframe-transport.js\",\n \"js/lib/jquery/jquery.fileupload.js\",\n \"js/lib/jquery/jquery.slimscroll.min.js\",\n \"js/lib/jquery/jquery.qrcode.min.js\",\n \"js/lib/jquery/jquery.bootstrap.wizard.js\",\n \"js/lib/pnotify/pnotify.core.min.js\",\n \"js/lib/pnotify/pnotify.buttons.min.js\",\n \"js/lib/pnotify/pnotify.callbacks.min.js\",\n \"js/lib/pnotify/pnotify.confirm.min.js\",\n \"js/lib/pnotify/pnotify.desktop.min.js\",\n \"js/lib/pnotify/pnotify.history.min.js\",\n \"js/lib/pnotify/pnotify.mobile.min.js\",\n \"js/lib/pnotify/pnotify.nonblock.min.js\",\n \"js/lib/pnotify/pnotify.reference.min.js\",\n \"js/lib/pnotify/pnotify.tooltip.min.js\",\n \"js/lib/pnotify/pnotify.maxheight.js\",\n \"js/lib/moment-with-locales.min.js\",\n \"js/lib/pusher.color.min.js\",\n \"js/lib/detectmobilebrowser.js\",\n \"js/lib/ua-parser.min.js\",\n \"js/lib/md5.min.js\",\n \"js/lib/bootstrap-slider-knockout-binding.js\",\n \"js/lib/loglevel.min.js\",\n \"js/lib/sockjs.min.js\",\n \"js/lib/hls.js\",\n \"js/lib/less.js\",\n ]", " css_libs = [\n \"css/bootstrap.min.css\",\n \"css/bootstrap-modal.css\",\n \"css/bootstrap-slider.css\",\n \"css/bootstrap-tabdrop.css\",\n \"vendor/font-awesome-3.2.1/css/font-awesome.min.css\",\n \"vendor/font-awesome-5.15.1/css/all.min.css\",\n \"vendor/font-awesome-5.15.1/css/v4-shims.min.css\",\n \"css/jquery.fileupload-ui.css\",\n \"css/pnotify.core.min.css\",\n \"css/pnotify.buttons.min.css\",\n \"css/pnotify.history.min.css\",\n ]", " # a couple of custom filters\n from webassets.filter import register_filter", " from octoprint.server.util.webassets import (\n GzipFile,\n JsDelimiterBundler,\n JsPluginBundle,\n LessImportRewrite,\n RJSMinExtended,\n SourceMapRemove,\n SourceMapRewrite,\n )", " register_filter(LessImportRewrite)\n register_filter(SourceMapRewrite)\n register_filter(SourceMapRemove)\n register_filter(JsDelimiterBundler)\n register_filter(GzipFile)\n register_filter(RJSMinExtended)", " def all_assets_for_plugins(collection):\n \"\"\"Gets all plugin assets for a dict of plugin->assets\"\"\"\n result = []\n for assets in collection.values():\n result += assets\n return result", " # -- JS --------------------------------------------------------------------------------------------------------", " filters = [\"sourcemap_remove\"]\n if self._settings.getBoolean([\"devel\", \"webassets\", \"minify\"]):\n filters += [\"rjsmin_extended\"]\n filters += [\"js_delimiter_bundler\", \"gzip\"]", " js_filters = filters\n if self._settings.getBoolean([\"devel\", \"webassets\", \"minify_plugins\"]):\n js_plugin_filters = js_filters\n else:\n js_plugin_filters = [x for x in js_filters if x not in (\"rjsmin_extended\",)]", " def js_bundles_for_plugins(collection, filters=None):\n \"\"\"Produces JsPluginBundle instances that output IIFE wrapped assets\"\"\"\n result = OrderedDict()\n for plugin, assets in collection.items():\n if len(assets):\n result[plugin] = JsPluginBundle(plugin, *assets, filters=filters)\n return result", " js_core = (\n dynamic_core_assets[\"js\"]\n + all_assets_for_plugins(dynamic_plugin_assets[\"bundled\"][\"js\"])\n + [\"js/app/dataupdater.js\", \"js/app/helpers.js\", \"js/app/main.js\"]\n )\n js_plugins = js_bundles_for_plugins(\n dynamic_plugin_assets[\"external\"][\"js\"], filters=\"js_delimiter_bundler\"\n )", " clientjs_core = dynamic_core_assets[\"clientjs\"] + all_assets_for_plugins(\n dynamic_plugin_assets[\"bundled\"][\"clientjs\"]\n )\n clientjs_plugins = js_bundles_for_plugins(\n dynamic_plugin_assets[\"external\"][\"clientjs\"], filters=\"js_delimiter_bundler\"\n )", " js_libs_bundle = Bundle(\n *js_libs, output=\"webassets/packed_libs.js\", filters=\",\".join(js_filters)\n )", " js_core_bundle = Bundle(\n *js_core, output=\"webassets/packed_core.js\", filters=\",\".join(js_filters)\n )", " if len(js_plugins) == 0:\n js_plugins_bundle = Bundle(*[])\n else:\n js_plugins_bundle = Bundle(\n *js_plugins.values(),\n output=\"webassets/packed_plugins.js\",\n filters=\",\".join(js_plugin_filters),\n )", " js_app_bundle = Bundle(\n js_plugins_bundle,\n js_core_bundle,\n output=\"webassets/packed_app.js\",\n filters=\",\".join(js_plugin_filters),\n )", " js_client_core_bundle = Bundle(\n *clientjs_core,\n output=\"webassets/packed_client_core.js\",\n filters=\",\".join(js_filters),\n )", " if len(clientjs_plugins) == 0:\n js_client_plugins_bundle = Bundle(*[])\n else:\n js_client_plugins_bundle = Bundle(\n *clientjs_plugins.values(),\n output=\"webassets/packed_client_plugins.js\",\n filters=\",\".join(js_plugin_filters),\n )", " js_client_bundle = Bundle(\n js_client_core_bundle,\n js_client_plugins_bundle,\n output=\"webassets/packed_client.js\",\n filters=\",\".join(js_plugin_filters),\n )", " # -- CSS -------------------------------------------------------------------------------------------------------", " css_filters = [\"cssrewrite\", \"gzip\"]", " css_core = list(dynamic_core_assets[\"css\"]) + all_assets_for_plugins(\n dynamic_plugin_assets[\"bundled\"][\"css\"]\n )\n css_plugins = list(\n all_assets_for_plugins(dynamic_plugin_assets[\"external\"][\"css\"])\n )", " css_libs_bundle = Bundle(\n *css_libs, output=\"webassets/packed_libs.css\", filters=\",\".join(css_filters)\n )", " if len(css_core) == 0:\n css_core_bundle = Bundle(*[])\n else:\n css_core_bundle = Bundle(\n *css_core,\n output=\"webassets/packed_core.css\",\n filters=\",\".join(css_filters),\n )", " if len(css_plugins) == 0:\n css_plugins_bundle = Bundle(*[])\n else:\n css_plugins_bundle = Bundle(\n *css_plugins,\n output=\"webassets/packed_plugins.css\",\n filters=\",\".join(css_filters),\n )", " css_app_bundle = Bundle(\n css_core,\n css_plugins,\n output=\"webassets/packed_app.css\",\n filters=\",\".join(css_filters),\n )", " # -- LESS ------------------------------------------------------------------------------------------------------", " less_filters = [\"cssrewrite\", \"less_importrewrite\", \"gzip\"]", " less_core = list(dynamic_core_assets[\"less\"]) + all_assets_for_plugins(\n dynamic_plugin_assets[\"bundled\"][\"less\"]\n )\n less_plugins = all_assets_for_plugins(dynamic_plugin_assets[\"external\"][\"less\"])", " if len(less_core) == 0:\n less_core_bundle = Bundle(*[])\n else:\n less_core_bundle = Bundle(\n *less_core,\n output=\"webassets/packed_core.less\",\n filters=\",\".join(less_filters),\n )", " if len(less_plugins) == 0:\n less_plugins_bundle = Bundle(*[])\n else:\n less_plugins_bundle = Bundle(\n *less_plugins,\n output=\"webassets/packed_plugins.less\",\n filters=\",\".join(less_filters),\n )", " less_app_bundle = Bundle(\n less_core,\n less_plugins,\n output=\"webassets/packed_app.less\",\n filters=\",\".join(less_filters),\n )", " # -- asset registration ----------------------------------------------------------------------------------------", " assets.register(\"js_libs\", js_libs_bundle)\n assets.register(\"js_client_core\", js_client_core_bundle)\n for plugin, bundle in clientjs_plugins.items():\n # register our collected clientjs plugin bundles so that they are bound to the environment\n assets.register(f\"js_client_plugin_{plugin}\", bundle)\n assets.register(\"js_client_plugins\", js_client_plugins_bundle)\n assets.register(\"js_client\", js_client_bundle)\n assets.register(\"js_core\", js_core_bundle)\n for plugin, bundle in js_plugins.items():\n # register our collected plugin bundles so that they are bound to the environment\n assets.register(f\"js_plugin_{plugin}\", bundle)\n assets.register(\"js_plugins\", js_plugins_bundle)\n assets.register(\"js_app\", js_app_bundle)\n assets.register(\"css_libs\", css_libs_bundle)\n assets.register(\"css_core\", css_core_bundle)\n assets.register(\"css_plugins\", css_plugins_bundle)\n assets.register(\"css_app\", css_app_bundle)\n assets.register(\"less_core\", less_core_bundle)\n assets.register(\"less_plugins\", less_plugins_bundle)\n assets.register(\"less_app\", less_app_bundle)", " def _setup_login_manager(self):\n global loginManager", " loginManager = LoginManager()", " # \"strong\" is incompatible to remember me, see maxcountryman/flask-login#156. It also causes issues with\n # clients toggling between IPv4 and IPv6 client addresses due to names being resolved one way or the other as\n # at least observed on a Win10 client targeting \"localhost\", resolved as both \"127.0.0.1\" and \"::1\"\n loginManager.session_protection = \"basic\"", " loginManager.user_loader(load_user)\n loginManager.unauthorized_handler(unauthorized_user)\n loginManager.anonymous_user = userManager.anonymous_user_factory\n loginManager.request_loader(load_user_from_request)", " loginManager.init_app(app, add_context_processor=False)", " def _start_intermediary_server(self):\n import socket\n import threading\n from http.server import BaseHTTPRequestHandler, HTTPServer", " host = self._host\n port = self._port", " class IntermediaryServerHandler(BaseHTTPRequestHandler):\n def __init__(self, rules=None, *args, **kwargs):\n if rules is None:\n rules = []\n self.rules = rules\n BaseHTTPRequestHandler.__init__(self, *args, **kwargs)", " def do_GET(self):\n request_path = self.path\n if \"?\" in request_path:\n request_path = request_path[0 : request_path.find(\"?\")]", " for rule in self.rules:\n path, data, content_type = rule\n if request_path == path:\n self.send_response(200)\n if content_type:\n self.send_header(\"Content-Type\", content_type)\n self.end_headers()\n if isinstance(data, str):\n data = data.encode(\"utf-8\")\n self.wfile.write(data)\n break\n else:\n self.send_response(404)\n self.wfile.write(b\"Not found\")", " base_path = os.path.realpath(\n os.path.join(os.path.dirname(__file__), \"..\", \"static\")\n )\n rules = [\n (\n \"/\",\n [\n \"intermediary.html\",\n ],\n \"text/html\",\n ),\n (\"/favicon.ico\", [\"img\", \"tentacle-20x20.png\"], \"image/png\"),\n (\n \"/intermediary.gif\",\n bytes(\n base64.b64decode(\n \"R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7\"\n )\n ),\n \"image/gif\",\n ),\n ]", " def contents(args):\n path = os.path.join(base_path, *args)\n if not os.path.isfile(path):\n return \"\"", " with open(path, \"rb\") as f:\n data = f.read()\n return data", " def process(rule):\n if len(rule) == 2:\n path, data = rule\n content_type = None\n else:\n path, data, content_type = rule", " if isinstance(data, (list, tuple)):\n data = contents(data)", " return path, data, content_type", " rules = list(\n map(process, filter(lambda rule: len(rule) == 2 or len(rule) == 3, rules))\n )", " HTTPServerV4 = HTTPServer", " class HTTPServerV6(HTTPServer):\n address_family = socket.AF_INET6", " class HTTPServerV6SingleStack(HTTPServerV6):\n def __init__(self, *args, **kwargs):\n HTTPServerV6.__init__(self, *args, **kwargs)", " # explicitly set V6ONLY flag - seems to be the default, but just to make sure...\n self.socket.setsockopt(\n octoprint.util.net.IPPROTO_IPV6, octoprint.util.net.IPV6_V6ONLY, 1\n )", " class HTTPServerV6DualStack(HTTPServerV6):\n def __init__(self, *args, **kwargs):\n HTTPServerV6.__init__(self, *args, **kwargs)", " # explicitly unset V6ONLY flag\n self.socket.setsockopt(\n octoprint.util.net.IPPROTO_IPV6, octoprint.util.net.IPV6_V6ONLY, 0\n )", " if \":\" in host:\n # v6\n if host == \"::\" and not self._v6_only:\n ServerClass = HTTPServerV6DualStack\n else:\n ServerClass = HTTPServerV6SingleStack\n else:\n # v4\n ServerClass = HTTPServerV4", " if host == \"::\":\n if self._v6_only:\n self._logger.debug(f\"Starting intermediary server on http://[::]:{port}\")\n else:\n self._logger.debug(\n \"Starting intermediary server on http://0.0.0.0:{port} and http://[::]:{port}\".format(\n port=port\n )\n )\n else:\n self._logger.debug(\n \"Starting intermediary server on http://{}:{}\".format(\n host if \":\" not in host else \"[\" + host + \"]\", port\n )\n )", " self._intermediary_server = ServerClass(\n (host, port),\n lambda *args, **kwargs: IntermediaryServerHandler(rules, *args, **kwargs),\n bind_and_activate=False,\n )", " # if possible, make sure our socket's port descriptor isn't handed over to subprocesses\n from octoprint.util.platform import set_close_exec", " try:\n set_close_exec(self._intermediary_server.fileno())\n except Exception:\n self._logger.exception(\n \"Error while attempting to set_close_exec on intermediary server socket\"\n )", " # then bind the server and have it serve our handler until stopped\n try:\n self._intermediary_server.server_bind()\n self._intermediary_server.server_activate()\n except Exception as exc:\n self._intermediary_server.server_close()", " if isinstance(exc, UnicodeDecodeError) and sys.platform == \"win32\":\n # we end up here if the hostname contains non-ASCII characters due to\n # https://bugs.python.org/issue26227 - tell the user they need\n # to either change their hostname or read up other options in\n # https://github.com/OctoPrint/OctoPrint/issues/3963\n raise CannotStartServerException(\n \"OctoPrint cannot start due to a Python bug \"\n \"(https://bugs.python.org/issue26227). Your \"\n \"computer's host name contains non-ASCII characters. \"\n \"Please either change your computer's host name to \"\n \"contain only ASCII characters, or take a look at \"\n \"https://github.com/OctoPrint/OctoPrint/issues/3963 for \"\n \"other options.\"\n )\n else:\n raise", " def serve():\n try:\n self._intermediary_server.serve_forever()\n except Exception:\n self._logger.exception(\"Error in intermediary server\")", " thread = threading.Thread(target=serve)\n thread.daemon = True\n thread.start()", " self._logger.info(\"Intermediary server started\")", " def _stop_intermediary_server(self):\n if self._intermediary_server is None:\n return\n self._logger.info(\"Shutting down intermediary server...\")\n self._intermediary_server.shutdown()\n self._intermediary_server.server_close()\n self._logger.info(\"Intermediary server shut down\")", " def _setup_plugin_permissions(self):\n global pluginManager", " from octoprint.access.permissions import PluginOctoPrintPermission", " key_whitelist = re.compile(r\"[A-Za-z0-9_]*\")", " def permission_key(plugin, definition):\n return \"PLUGIN_{}_{}\".format(plugin.upper(), definition[\"key\"].upper())", " def permission_name(plugin, definition):\n return \"{}: {}\".format(plugin, definition[\"name\"])", " def permission_role(plugin, role):\n return f\"plugin_{plugin}_{role}\"", " def process_regular_permission(plugin_info, definition):\n permissions = []\n for key in definition.get(\"permissions\", []):\n permission = octoprint.access.permissions.Permissions.find(key)", " if permission is None:\n # if there is still no permission found, postpone this - maybe it is a permission from\n # another plugin that hasn't been loaded yet\n return False", " permissions.append(permission)", " roles = definition.get(\"roles\", [])\n description = definition.get(\"description\", \"\")\n dangerous = definition.get(\"dangerous\", False)\n default_groups = definition.get(\"default_groups\", [])", " roles_and_permissions = [\n permission_role(plugin_info.key, role) for role in roles\n ] + permissions", " key = permission_key(plugin_info.key, definition)\n permission = PluginOctoPrintPermission(\n permission_name(plugin_info.name, definition),\n description,\n plugin=plugin_info.key,\n dangerous=dangerous,\n default_groups=default_groups,\n *roles_and_permissions,\n )\n setattr(\n octoprint.access.permissions.Permissions,\n key,\n PluginOctoPrintPermission(\n permission_name(plugin_info.name, definition),\n description,\n plugin=plugin_info.key,\n dangerous=dangerous,\n default_groups=default_groups,\n *roles_and_permissions,\n ),\n )", " self._logger.info(\n \"Added new permission from plugin {}: {} (needs: {!r})\".format(\n plugin_info.key, key, \", \".join(map(repr, permission.needs))\n )\n )\n return True", " postponed = []", " hooks = pluginManager.get_hooks(\"octoprint.access.permissions\")\n for name, factory in hooks.items():\n try:\n if isinstance(factory, (tuple, list)):\n additional_permissions = list(factory)\n elif callable(factory):\n additional_permissions = factory()\n else:\n raise ValueError(\"factory must be either a callable, tuple or list\")", " if not isinstance(additional_permissions, (tuple, list)):\n raise ValueError(\n \"factory result must be either a tuple or a list of permission definition dicts\"\n )", " plugin_info = pluginManager.get_plugin_info(name)\n for p in additional_permissions:\n if not isinstance(p, dict):\n continue", " if \"key\" not in p or \"name\" not in p:\n continue", " if not key_whitelist.match(p[\"key\"]):\n self._logger.warning(\n \"Got permission with invalid key from plugin {}: {}\".format(\n name, p[\"key\"]\n )\n )\n continue", " if not process_regular_permission(plugin_info, p):\n postponed.append((plugin_info, p))\n except Exception:\n self._logger.exception(\n f\"Error while creating permission instance/s from {name}\"\n )", " # final resolution passes\n pass_number = 1\n still_postponed = []\n while len(postponed):\n start_length = len(postponed)\n self._logger.debug(\n \"Plugin permission resolution pass #{}, \"\n \"{} unresolved permissions...\".format(pass_number, start_length)\n )", " for plugin_info, definition in postponed:\n if not process_regular_permission(plugin_info, definition):\n still_postponed.append((plugin_info, definition))", " self._logger.debug(\n \"... pass #{} done, {} permissions left to resolve\".format(\n pass_number, len(still_postponed)\n )\n )", " if len(still_postponed) == start_length:\n # no change, looks like some stuff is unresolvable - let's bail\n for plugin_info, definition in still_postponed:\n self._logger.warning(\n \"Unable to resolve permission from {}: {!r}\".format(\n plugin_info.key, definition\n )\n )\n break", " postponed = still_postponed\n still_postponed = []\n pass_number += 1", "\nclass LifecycleManager:\n def __init__(self, plugin_manager):\n self._plugin_manager = plugin_manager", " self._plugin_lifecycle_callbacks = defaultdict(list)\n self._logger = logging.getLogger(__name__)", " def wrap_plugin_event(lifecycle_event, new_handler):\n orig_handler = getattr(self._plugin_manager, \"on_plugin_\" + lifecycle_event)", " def handler(*args, **kwargs):\n if callable(orig_handler):\n orig_handler(*args, **kwargs)\n if callable(new_handler):\n new_handler(*args, **kwargs)", " return handler", " def on_plugin_event_factory(lifecycle_event):\n def on_plugin_event(name, plugin):\n self.on_plugin_event(lifecycle_event, name, plugin)", " return on_plugin_event", " for event in (\"loaded\", \"unloaded\", \"enabled\", \"disabled\"):\n wrap_plugin_event(event, on_plugin_event_factory(event))", " def on_plugin_event(self, event, name, plugin):\n for lifecycle_callback in self._plugin_lifecycle_callbacks[event]:\n lifecycle_callback(name, plugin)", " def add_callback(self, events, callback):\n if isinstance(events, str):\n events = [events]", " for event in events:\n self._plugin_lifecycle_callbacks[event].append(callback)", " def remove_callback(self, callback, events=None):\n if events is None:\n for event in self._plugin_lifecycle_callbacks:\n if callback in self._plugin_lifecycle_callbacks[event]:\n self._plugin_lifecycle_callbacks[event].remove(callback)\n else:\n if isinstance(events, str):\n events = [events]", " for event in events:\n if callback in self._plugin_lifecycle_callbacks[event]:\n self._plugin_lifecycle_callbacks[event].remove(callback)", "\nclass CannotStartServerException(Exception):\n pass" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [984, 842, 1177], "buggy_code_start_loc": [956, 42, 1141], "filenames": ["src/octoprint/filemanager/storage.py", "src/octoprint/server/__init__.py", "src/octoprint/server/api/files.py"], "fixing_code_end_loc": [997, 854, 1190], "fixing_code_start_loc": [957, 43, 1141], "message": "Unrestricted Upload of File with Dangerous Type in GitHub repository octoprint/octoprint prior to 1.8.3.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:octoprint:octoprint:*:*:*:*:*:*:*:*", "matchCriteriaId": "900F81F7-9FC4-44CE-ABD6-1E82DC120B4B", "versionEndExcluding": "1.8.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Unrestricted Upload of File with Dangerous Type in GitHub repository octoprint/octoprint prior to 1.8.3."}, {"lang": "es", "value": "Una Descarga sin Restricciones de Archivos de Tipo Peligroso en el repositorio GitHub octoprint/octoprint versiones anteriores a 1.8.3"}], "evaluatorComment": null, "id": "CVE-2022-2872", "lastModified": "2022-09-23T17:58:22.120", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:L/UI:R/S:U/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 1.2, "impactScore": 2.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-09-21T10:15:09.327", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/octoprint/octoprint/commit/3e3c11811e216fb371a33e28412df83f9701e5b0"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/b966c74d-6f3f-49fe-b40a-eaf25e362c56"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-434"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/octoprint/octoprint/commit/3e3c11811e216fb371a33e28412df83f9701e5b0"}, "type": "CWE-434"}
328
Determine whether the {function_name} code is vulnerable or not.
[ "__author__ = \"Gina Häußge <osd@foosel.net>\"\n__license__ = \"GNU Affero General Public License http://www.gnu.org/licenses/agpl.html\"\n__copyright__ = \"Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License\"", "import hashlib\nimport logging\nimport os\nimport threading\nfrom urllib.parse import quote as urlquote", "import psutil\nfrom flask import abort, jsonify, make_response, request, url_for", "import octoprint.filemanager\nimport octoprint.filemanager.storage\nimport octoprint.filemanager.util\nimport octoprint.slicing\nfrom octoprint.access.permissions import Permissions\nfrom octoprint.events import Events\nfrom octoprint.filemanager.destinations import FileDestinations\nfrom octoprint.server import (\n NO_CONTENT,\n current_user,\n eventManager,\n fileManager,\n printer,\n slicingManager,\n)\nfrom octoprint.server.api import api\nfrom octoprint.server.util.flask import (\n get_json_command_from_request,\n no_firstrun_access,\n with_revalidation_checking,\n)\nfrom octoprint.settings import settings, valid_boolean_trues\nfrom octoprint.util import sv, time_this", "# ~~ GCODE file handling", "_file_cache = {}\n_file_cache_mutex = threading.RLock()", "_DATA_FORMAT_VERSION = \"v2\"", "\ndef _clear_file_cache():\n with _file_cache_mutex:\n _file_cache.clear()", "\ndef _create_lastmodified(path, recursive):\n path = path[len(\"/api/files\") :]\n if path.startswith(\"/\"):\n path = path[1:]", " if path == \"\":\n # all storages involved\n lms = [0]\n for storage in fileManager.registered_storages:\n try:\n lms.append(fileManager.last_modified(storage, recursive=recursive))\n except Exception:\n logging.getLogger(__name__).exception(\n \"There was an error retrieving the last modified data from storage {}\".format(\n storage\n )\n )\n lms.append(None)", " if any(filter(lambda x: x is None, lms)):\n # we return None if ANY of the involved storages returned None\n return None", " # if we reach this point, we return the maximum of all dates\n return max(lms)", " else:\n if \"/\" in path:\n storage, path_in_storage = path.split(\"/\", 1)\n else:\n storage = path\n path_in_storage = None", " try:\n return fileManager.last_modified(\n storage, path=path_in_storage, recursive=recursive\n )\n except Exception:\n logging.getLogger(__name__).exception(\n \"There was an error retrieving the last modified data from storage {} and path {}\".format(\n storage, path_in_storage\n )\n )\n return None", "\ndef _create_etag(path, filter, recursive, lm=None):\n if lm is None:\n lm = _create_lastmodified(path, recursive)", " if lm is None:\n return None", " hash = hashlib.sha1()", " def hash_update(value):\n value = value.encode(\"utf-8\")\n hash.update(value)", " hash_update(str(lm))\n hash_update(str(filter))\n hash_update(str(recursive))", " path = path[len(\"/api/files\") :]\n if path.startswith(\"/\"):\n path = path[1:]", " if \"/\" in path:\n storage, _ = path.split(\"/\", 1)\n else:\n storage = path", " if path == \"\" or storage == FileDestinations.SDCARD:\n # include sd data in etag\n hash_update(repr(sorted(printer.get_sd_files(), key=lambda x: sv(x[\"name\"]))))", " hash_update(_DATA_FORMAT_VERSION) # increment version if we change the API format", " return hash.hexdigest()", "\n@api.route(\"/files\", methods=[\"GET\"])\n@Permissions.FILES_LIST.require(403)\n@with_revalidation_checking(\n etag_factory=lambda lm=None: _create_etag(\n request.path,\n request.values.get(\"filter\", False),\n request.values.get(\"recursive\", False),\n lm=lm,\n ),\n lastmodified_factory=lambda: _create_lastmodified(\n request.path, request.values.get(\"recursive\", False)\n ),\n unless=lambda: request.values.get(\"force\", False)\n or request.values.get(\"_refresh\", False),\n)\ndef readGcodeFiles():\n filter = request.values.get(\"filter\", False)\n recursive = request.values.get(\"recursive\", \"false\") in valid_boolean_trues\n force = request.values.get(\"force\", \"false\") in valid_boolean_trues", " files = _getFileList(\n FileDestinations.LOCAL,\n filter=filter,\n recursive=recursive,\n allow_from_cache=not force,\n )\n files.extend(_getFileList(FileDestinations.SDCARD, allow_from_cache=not force))", " usage = psutil.disk_usage(settings().getBaseFolder(\"uploads\", check_writable=False))\n return jsonify(files=files, free=usage.free, total=usage.total)", "\n@api.route(\"/files/test\", methods=[\"POST\"])\n@Permissions.FILES_LIST.require(403)\ndef runFilesTest():\n valid_commands = {\n \"sanitize\": [\"storage\", \"path\", \"filename\"],\n \"exists\": [\"storage\", \"path\", \"filename\"],\n }", " command, data, response = get_json_command_from_request(request, valid_commands)\n if response is not None:\n return response", " def sanitize(storage, path, filename):\n sanitized_path = fileManager.sanitize_path(storage, path)\n sanitized_name = fileManager.sanitize_name(storage, filename)\n joined = fileManager.join_path(storage, sanitized_path, sanitized_name)\n return sanitized_path, sanitized_name, joined", " if command == \"sanitize\":\n _, _, sanitized = sanitize(data[\"storage\"], data[\"path\"], data[\"filename\"])\n return jsonify(sanitized=sanitized)\n elif command == \"exists\":\n storage = data[\"storage\"]\n path = data[\"path\"]\n filename = data[\"filename\"]", " sanitized_path, _, sanitized = sanitize(storage, path, filename)", " exists = fileManager.file_exists(storage, sanitized)\n if exists:\n suggestion = filename\n name, ext = os.path.splitext(filename)\n counter = 0\n while fileManager.file_exists(\n storage,\n fileManager.join_path(\n storage,\n sanitized_path,\n fileManager.sanitize_name(storage, suggestion),\n ),\n ):\n counter += 1\n suggestion = f\"{name}_{counter}{ext}\"\n return jsonify(exists=True, suggestion=suggestion)\n else:\n return jsonify(exists=False)", "\n@api.route(\"/files/<string:origin>\", methods=[\"GET\"])\n@Permissions.FILES_LIST.require(403)\n@with_revalidation_checking(\n etag_factory=lambda lm=None: _create_etag(\n request.path,\n request.values.get(\"filter\", False),\n request.values.get(\"recursive\", False),\n lm=lm,\n ),\n lastmodified_factory=lambda: _create_lastmodified(\n request.path, request.values.get(\"recursive\", False)\n ),\n unless=lambda: request.values.get(\"force\", False)\n or request.values.get(\"_refresh\", False),\n)\ndef readGcodeFilesForOrigin(origin):\n if origin not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:\n abort(404)", " filter = request.values.get(\"filter\", False)\n recursive = request.values.get(\"recursive\", \"false\") in valid_boolean_trues\n force = request.values.get(\"force\", \"false\") in valid_boolean_trues", " files = _getFileList(\n origin, filter=filter, recursive=recursive, allow_from_cache=not force\n )", " if origin == FileDestinations.LOCAL:\n usage = psutil.disk_usage(\n settings().getBaseFolder(\"uploads\", check_writable=False)\n )\n return jsonify(files=files, free=usage.free, total=usage.total)\n else:\n return jsonify(files=files)", "\n@api.route(\"/files/<string:target>/<path:filename>\", methods=[\"GET\"])\n@Permissions.FILES_LIST.require(403)\n@with_revalidation_checking(\n etag_factory=lambda lm=None: _create_etag(\n request.path,\n request.values.get(\"filter\", False),\n request.values.get(\"recursive\", False),\n lm=lm,\n ),\n lastmodified_factory=lambda: _create_lastmodified(\n request.path, request.values.get(\"recursive\", False)\n ),\n unless=lambda: request.values.get(\"force\", False)\n or request.values.get(\"_refresh\", False),\n)\ndef readGcodeFile(target, filename):\n if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:\n abort(404)", " if not _validate(target, filename):\n abort(404)", " recursive = False\n if \"recursive\" in request.values:\n recursive = request.values[\"recursive\"] in valid_boolean_trues", " file = _getFileDetails(target, filename, recursive=recursive)\n if not file:\n abort(404)", " return jsonify(file)", "\ndef _getFileDetails(origin, path, recursive=True):\n parent, path = os.path.split(path)\n files = _getFileList(origin, path=parent, recursive=recursive, level=1)", " for f in files:\n if f[\"name\"] == path:\n return f\n else:\n return None", "\n@time_this(\n logtarget=__name__ + \".timings\",\n message=\"{func}({func_args},{func_kwargs}) took {timing:.2f}ms\",\n incl_func_args=True,\n log_enter=True,\n message_enter=\"Entering {func}({func_args},{func_kwargs})...\",\n)\ndef _getFileList(\n origin, path=None, filter=None, recursive=False, level=0, allow_from_cache=True\n):\n if origin == FileDestinations.SDCARD:\n sdFileList = printer.get_sd_files(refresh=not allow_from_cache)", " files = []\n if sdFileList is not None:\n for f in sdFileList:\n type_path = octoprint.filemanager.get_file_type(f[\"name\"])\n if not type_path:\n # only supported extensions\n continue\n else:\n file_type = type_path[0]", " file = {\n \"type\": file_type,\n \"typePath\": type_path,\n \"name\": f[\"name\"],\n \"display\": f[\"display\"] if f[\"display\"] else f[\"name\"],\n \"path\": f[\"name\"],\n \"origin\": FileDestinations.SDCARD,\n \"refs\": {\n \"resource\": url_for(\n \".readGcodeFile\",\n target=FileDestinations.SDCARD,\n filename=f[\"name\"],\n _external=True,\n )\n },\n }\n if f[\"size\"] is not None:\n file.update({\"size\": f[\"size\"]})\n files.append(file)\n else:\n filter_func = None\n if filter:\n filter_func = lambda entry, entry_data: octoprint.filemanager.valid_file_type(\n entry, type=filter\n )", " with _file_cache_mutex:\n cache_key = f\"{origin}:{path}:{recursive}:{filter}\"\n files, lastmodified = _file_cache.get(cache_key, ([], None))\n # recursive needs to be True for lastmodified queries so we get lastmodified of whole subtree - #3422\n if (\n not allow_from_cache\n or lastmodified is None\n or lastmodified\n < fileManager.last_modified(origin, path=path, recursive=True)\n ):\n files = list(\n fileManager.list_files(\n origin,\n path=path,\n filter=filter_func,\n recursive=recursive,\n level=level,\n force_refresh=not allow_from_cache,\n )[origin].values()\n )\n lastmodified = fileManager.last_modified(\n origin, path=path, recursive=True\n )\n _file_cache[cache_key] = (files, lastmodified)", " def analyse_recursively(files, path=None):\n if path is None:\n path = \"\"", " result = []\n for file_or_folder in files:\n # make a shallow copy in order to not accidentally modify the cached data\n file_or_folder = dict(file_or_folder)", " file_or_folder[\"origin\"] = FileDestinations.LOCAL", " if file_or_folder[\"type\"] == \"folder\":\n if \"children\" in file_or_folder:\n file_or_folder[\"children\"] = analyse_recursively(\n file_or_folder[\"children\"].values(),\n path + file_or_folder[\"name\"] + \"/\",\n )", " file_or_folder[\"refs\"] = {\n \"resource\": url_for(\n \".readGcodeFile\",\n target=FileDestinations.LOCAL,\n filename=path + file_or_folder[\"name\"],\n _external=True,\n )\n }\n else:\n if (\n \"analysis\" in file_or_folder\n and octoprint.filemanager.valid_file_type(\n file_or_folder[\"name\"], type=\"gcode\"\n )\n ):\n file_or_folder[\"gcodeAnalysis\"] = file_or_folder[\"analysis\"]\n del file_or_folder[\"analysis\"]", " if (\n \"history\" in file_or_folder\n and octoprint.filemanager.valid_file_type(\n file_or_folder[\"name\"], type=\"gcode\"\n )\n ):\n # convert print log\n history = file_or_folder[\"history\"]\n del file_or_folder[\"history\"]\n success = 0\n failure = 0\n last = None\n for entry in history:\n success += 1 if \"success\" in entry and entry[\"success\"] else 0\n failure += (\n 1 if \"success\" in entry and not entry[\"success\"] else 0\n )\n if not last or (\n \"timestamp\" in entry\n and \"timestamp\" in last\n and entry[\"timestamp\"] > last[\"timestamp\"]\n ):\n last = entry\n if last:\n prints = {\n \"success\": success,\n \"failure\": failure,\n \"last\": {\n \"success\": last[\"success\"],\n \"date\": last[\"timestamp\"],\n },\n }\n if \"printTime\" in last:\n prints[\"last\"][\"printTime\"] = last[\"printTime\"]\n file_or_folder[\"prints\"] = prints", " file_or_folder[\"refs\"] = {\n \"resource\": url_for(\n \".readGcodeFile\",\n target=FileDestinations.LOCAL,\n filename=file_or_folder[\"path\"],\n _external=True,\n ),\n \"download\": url_for(\"index\", _external=True)\n + \"downloads/files/\"\n + FileDestinations.LOCAL\n + \"/\"\n + urlquote(file_or_folder[\"path\"]),\n }", " result.append(file_or_folder)", " return result", " files = analyse_recursively(files)", " return files", "\ndef _verifyFileExists(origin, filename):\n if origin == FileDestinations.SDCARD:\n return filename in (x[\"name\"] for x in printer.get_sd_files())\n else:\n return fileManager.file_exists(origin, filename)", "\ndef _verifyFolderExists(origin, foldername):\n if origin == FileDestinations.SDCARD:\n return False\n else:\n return fileManager.folder_exists(origin, foldername)", "\ndef _isBusy(target, path):\n currentOrigin, currentPath = _getCurrentFile()\n if (\n currentPath is not None\n and currentOrigin == target\n and fileManager.file_in_path(FileDestinations.LOCAL, path, currentPath)\n and (printer.is_printing() or printer.is_paused())\n ):\n return True", " return any(\n target == x[0] and fileManager.file_in_path(FileDestinations.LOCAL, path, x[1])\n for x in fileManager.get_busy_files()\n )", "\n@api.route(\"/files/<string:target>\", methods=[\"POST\"])\n@no_firstrun_access\n@Permissions.FILES_UPLOAD.require(403)\ndef uploadGcodeFile(target):\n input_name = \"file\"\n input_upload_name = (\n input_name + \".\" + settings().get([\"server\", \"uploads\", \"nameSuffix\"])\n )\n input_upload_path = (\n input_name + \".\" + settings().get([\"server\", \"uploads\", \"pathSuffix\"])\n )\n if input_upload_name in request.values and input_upload_path in request.values:\n if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:\n abort(404)", " upload = octoprint.filemanager.util.DiskFileWrapper(\n request.values[input_upload_name], request.values[input_upload_path]\n )", " # Store any additional user data the caller may have passed.\n userdata = None\n if \"userdata\" in request.values:\n import json", " try:\n userdata = json.loads(request.values[\"userdata\"])\n except Exception:\n abort(400, description=\"userdata contains invalid JSON\")", " # check preconditions for SD upload\n if target == FileDestinations.SDCARD and not settings().getBoolean(\n [\"feature\", \"sdSupport\"]\n ):\n abort(404)", " sd = target == FileDestinations.SDCARD\n if sd:\n # validate that all preconditions for SD upload are met before attempting it\n if not (\n printer.is_operational()\n and not (printer.is_printing() or printer.is_paused())\n ):\n abort(\n 409,\n description=\"Can not upload to SD card, printer is either not operational or already busy\",\n )\n if not printer.is_sd_ready():\n abort(409, description=\"Can not upload to SD card, not yet initialized\")", " # evaluate select and print parameter and if set check permissions & preconditions\n # and adjust as necessary\n #\n # we do NOT abort(409) here since this would be a backwards incompatible behaviour change\n # on the API, but instead return the actually effective select and print flags in the response\n #\n # note that this behaviour might change in a future API version\n select_request = (\n \"select\" in request.values\n and request.values[\"select\"] in valid_boolean_trues\n and Permissions.FILES_SELECT.can()\n )\n print_request = (\n \"print\" in request.values\n and request.values[\"print\"] in valid_boolean_trues\n and Permissions.PRINT.can()\n )", " to_select = select_request\n to_print = print_request\n if (to_select or to_print) and not (\n printer.is_operational()\n and not (printer.is_printing() or printer.is_paused())\n ):\n # can't select or print files if not operational or ready\n to_select = to_print = False", " # determine future filename of file to be uploaded, abort if it can't be uploaded\n try:\n # FileDestinations.LOCAL = should normally be target, but can't because SDCard handling isn't implemented yet\n canonPath, canonFilename = fileManager.canonicalize(\n FileDestinations.LOCAL, upload.filename\n )\n if request.values.get(\"path\"):\n canonPath = request.values.get(\"path\")\n if request.values.get(\"filename\"):\n canonFilename = request.values.get(\"filename\")", " futurePath = fileManager.sanitize_path(FileDestinations.LOCAL, canonPath)\n futureFilename = fileManager.sanitize_name(\n FileDestinations.LOCAL, canonFilename\n )\n except Exception:\n canonFilename = None\n futurePath = None\n futureFilename = None", " if futureFilename is None:\n abort(400, description=\"Can not upload file, invalid file name\")", " # prohibit overwriting currently selected file while it's being printed\n futureFullPath = fileManager.join_path(\n FileDestinations.LOCAL, futurePath, futureFilename\n )\n futureFullPathInStorage = fileManager.path_in_storage(\n FileDestinations.LOCAL, futureFullPath\n )", " if not printer.can_modify_file(futureFullPathInStorage, sd):\n abort(\n 409,\n description=\"Trying to overwrite file that is currently being printed\",\n )", " if (\n fileManager.file_exists(FileDestinations.LOCAL, futureFullPathInStorage)\n and request.values.get(\"noOverwrite\") in valid_boolean_trues\n ):\n abort(409, description=\"File already exists and noOverwrite was set\")", " reselect = printer.is_current_file(futureFullPathInStorage, sd)", " user = current_user.get_name()", " def fileProcessingFinished(filename, absFilename, destination):\n \"\"\"\n Callback for when the file processing (upload, optional slicing, addition to analysis queue) has\n finished.", " Depending on the file's destination triggers either streaming to SD card or directly calls to_select.\n \"\"\"", " if (\n destination == FileDestinations.SDCARD\n and octoprint.filemanager.valid_file_type(filename, \"machinecode\")\n ):\n return filename, printer.add_sd_file(\n filename,\n absFilename,\n on_success=selectAndOrPrint,\n tags={\"source:api\", \"api:files.sd\"},\n )\n else:\n selectAndOrPrint(filename, absFilename, destination)\n return filename", " def selectAndOrPrint(filename, absFilename, destination):\n \"\"\"\n Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only\n the case after they have finished streaming to the printer, which is why this callback is also used\n for the corresponding call to addSdFile.", " Selects the just uploaded file if either to_select or to_print are True, or if the\n exact file is already selected, such reloading it.\n \"\"\"\n if octoprint.filemanager.valid_file_type(added_file, \"gcode\") and (\n to_select or to_print or reselect\n ):\n printer.select_file(\n absFilename,\n destination == FileDestinations.SDCARD,\n to_print,\n user,\n )", " try:\n added_file = fileManager.add_file(\n FileDestinations.LOCAL,\n futureFullPathInStorage,\n upload,\n allow_overwrite=True,\n display=canonFilename,\n )\n except octoprint.filemanager.storage.StorageError as e:\n if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE:\n abort(415, description=\"Could not upload file, invalid type\")\n else:\n abort(500, description=\"Could not upload file\")\n else:\n filename = fileProcessingFinished(\n added_file,\n fileManager.path_on_disk(FileDestinations.LOCAL, added_file),\n target,\n )\n done = not sd", " if userdata is not None:\n # upload included userdata, add this now to the metadata\n fileManager.set_additional_metadata(\n FileDestinations.LOCAL, added_file, \"userdata\", userdata\n )", " sdFilename = None\n if isinstance(filename, tuple):\n filename, sdFilename = filename", " payload = {\n \"name\": futureFilename,\n \"path\": filename,\n \"target\": target,\n \"select\": select_request,\n \"print\": print_request,\n \"effective_select\": to_select,\n \"effective_print\": to_print,\n }\n if userdata is not None:\n payload[\"userdata\"] = userdata\n eventManager.fire(Events.UPLOAD, payload)", " files = {}\n location = url_for(\n \".readGcodeFile\",\n target=FileDestinations.LOCAL,\n filename=filename,\n _external=True,\n )\n files.update(\n {\n FileDestinations.LOCAL: {\n \"name\": futureFilename,\n \"path\": filename,\n \"origin\": FileDestinations.LOCAL,\n \"refs\": {\n \"resource\": location,\n \"download\": url_for(\"index\", _external=True)\n + \"downloads/files/\"\n + FileDestinations.LOCAL\n + \"/\"\n + urlquote(filename),\n },\n }\n }\n )", " if sd and sdFilename:\n location = url_for(\n \".readGcodeFile\",\n target=FileDestinations.SDCARD,\n filename=sdFilename,\n _external=True,\n )\n files.update(\n {\n FileDestinations.SDCARD: {\n \"name\": sdFilename,\n \"path\": sdFilename,\n \"origin\": FileDestinations.SDCARD,\n \"refs\": {\"resource\": location},\n }\n }\n )", " r = make_response(\n jsonify(\n files=files,\n done=done,\n effectiveSelect=to_select,\n effectivePrint=to_print,\n ),\n 201,\n )\n r.headers[\"Location\"] = location\n return r", " elif \"foldername\" in request.values:\n foldername = request.values[\"foldername\"]", " if target not in [FileDestinations.LOCAL]:\n abort(400, description=\"target is invalid\")", " canonPath, canonName = fileManager.canonicalize(target, foldername)\n futurePath = fileManager.sanitize_path(target, canonPath)\n futureName = fileManager.sanitize_name(target, canonName)\n if not futureName or not futurePath:\n abort(400, description=\"folder name is empty\")", " if \"path\" in request.values and request.values[\"path\"]:\n futurePath = fileManager.sanitize_path(\n FileDestinations.LOCAL, request.values[\"path\"]\n )", " futureFullPath = fileManager.join_path(target, futurePath, futureName)\n if octoprint.filemanager.valid_file_type(futureName):\n abort(409, description=\"Can't create folder, please try another name\")", " try:\n added_folder = fileManager.add_folder(\n target, futureFullPath, display=canonName\n )\n except octoprint.filemanager.storage.StorageError as e:\n if e.code == octoprint.filemanager.storage.StorageError.INVALID_DIRECTORY:\n abort(400, description=\"Could not create folder, invalid directory\")\n else:\n abort(500, description=\"Could not create folder\")", " location = url_for(\n \".readGcodeFile\",\n target=FileDestinations.LOCAL,\n filename=added_folder,\n _external=True,\n )\n folder = {\n \"name\": futureName,\n \"path\": added_folder,\n \"origin\": target,\n \"refs\": {\"resource\": location},\n }", " r = make_response(jsonify(folder=folder, done=True), 201)\n r.headers[\"Location\"] = location\n return r", " else:\n abort(400, description=\"No file to upload and no folder to create\")", "\n@api.route(\"/files/<string:target>/<path:filename>\", methods=[\"POST\"])\n@no_firstrun_access\ndef gcodeFileCommand(filename, target):\n if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:\n abort(404)", " if not _validate(target, filename):\n abort(404)", " # valid file commands, dict mapping command name to mandatory parameters\n valid_commands = {\n \"select\": [],\n \"unselect\": [],\n \"slice\": [],\n \"analyse\": [],\n \"copy\": [\"destination\"],\n \"move\": [\"destination\"],\n }", " command, data, response = get_json_command_from_request(request, valid_commands)\n if response is not None:\n return response", " user = current_user.get_name()", " if command == \"select\":\n with Permissions.FILES_SELECT.require(403):\n if not _verifyFileExists(target, filename):\n abort(404)", " # selects/loads a file\n if not octoprint.filemanager.valid_file_type(filename, type=\"machinecode\"):\n abort(\n 415,\n description=\"Cannot select file for printing, not a machinecode file\",\n )", " if not printer.is_ready():\n abort(\n 409,\n description=\"Printer is already printing, cannot select a new file\",\n )", " printAfterLoading = False\n if \"print\" in data and data[\"print\"] in valid_boolean_trues:\n with Permissions.PRINT.require(403):\n if not printer.is_operational():\n abort(\n 409,\n description=\"Printer is not operational, cannot directly start printing\",\n )\n printAfterLoading = True", " sd = False\n if target == FileDestinations.SDCARD:\n filenameToSelect = filename\n sd = True\n else:\n filenameToSelect = fileManager.path_on_disk(target, filename)\n printer.select_file(filenameToSelect, sd, printAfterLoading, user)", " elif command == \"unselect\":\n with Permissions.FILES_SELECT.require(403):\n if not printer.is_ready():\n return make_response(\n \"Printer is already printing, cannot unselect current file\", 409\n )", " _, currentFilename = _getCurrentFile()\n if currentFilename is None:\n return make_response(\n \"Cannot unselect current file when there is no file selected\", 409\n )", " if filename != currentFilename and filename != \"current\":\n return make_response(\n \"Only the currently selected file can be unselected\", 400\n )", " printer.unselect_file()", " elif command == \"slice\":\n with Permissions.SLICE.require(403):\n if not _verifyFileExists(target, filename):\n abort(404)", " try:\n if \"slicer\" in data:\n slicer = data[\"slicer\"]\n del data[\"slicer\"]\n slicer_instance = slicingManager.get_slicer(slicer)", " elif \"cura\" in slicingManager.registered_slicers:\n slicer = \"cura\"\n slicer_instance = slicingManager.get_slicer(\"cura\")", " else:\n abort(415, description=\"Cannot slice file, no slicer available\")\n except octoprint.slicing.UnknownSlicer:\n abort(404)", " if not any(\n [\n octoprint.filemanager.valid_file_type(filename, type=source_file_type)\n for source_file_type in slicer_instance.get_slicer_properties().get(\n \"source_file_types\", [\"model\"]\n )\n ]\n ):\n abort(415, description=\"Cannot slice file, not a model file\")", " cores = psutil.cpu_count()\n if (\n slicer_instance.get_slicer_properties().get(\"same_device\", True)\n and (printer.is_printing() or printer.is_paused())\n and (cores is None or cores < 2)\n ):\n # slicer runs on same device as OctoPrint, slicing while printing is hence disabled\n abort(\n 409,\n description=\"Cannot slice on this slicer while printing on single core systems or systems of unknown core count due to performance reasons\",\n )", " if \"destination\" in data and data[\"destination\"]:\n destination = data[\"destination\"]\n del data[\"destination\"]\n elif \"gcode\" in data and data[\"gcode\"]:\n destination = data[\"gcode\"]\n del data[\"gcode\"]\n else:\n import os", " name, _ = os.path.splitext(filename)\n destination = (\n name\n + \".\"\n + slicer_instance.get_slicer_properties().get(\n \"destination_extensions\", [\"gco\", \"gcode\", \"g\"]\n )[0]\n )", " full_path = destination\n if \"path\" in data and data[\"path\"]:\n full_path = fileManager.join_path(target, data[\"path\"], destination)\n else:\n path, _ = fileManager.split_path(target, filename)\n if path:\n full_path = fileManager.join_path(target, path, destination)", " canon_path, canon_name = fileManager.canonicalize(target, full_path)\n sanitized_name = fileManager.sanitize_name(target, canon_name)", " if canon_path:\n full_path = fileManager.join_path(target, canon_path, sanitized_name)\n else:\n full_path = sanitized_name", " # prohibit overwriting the file that is currently being printed\n currentOrigin, currentFilename = _getCurrentFile()\n if (\n currentFilename == full_path\n and currentOrigin == target\n and (printer.is_printing() or printer.is_paused())\n ):\n abort(\n 409,\n description=\"Trying to slice into file that is currently being printed\",\n )", " if \"profile\" in data and data[\"profile\"]:\n profile = data[\"profile\"]\n del data[\"profile\"]\n else:\n profile = None", " if \"printerProfile\" in data and data[\"printerProfile\"]:\n printerProfile = data[\"printerProfile\"]\n del data[\"printerProfile\"]\n else:\n printerProfile = None", " if (\n \"position\" in data\n and data[\"position\"]\n and isinstance(data[\"position\"], dict)\n and \"x\" in data[\"position\"]\n and \"y\" in data[\"position\"]\n ):\n position = data[\"position\"]\n del data[\"position\"]\n else:\n position = None", " select_after_slicing = False\n if \"select\" in data and data[\"select\"] in valid_boolean_trues:\n if not printer.is_operational():\n abort(\n 409,\n description=\"Printer is not operational, cannot directly select for printing\",\n )\n select_after_slicing = True", " print_after_slicing = False\n if \"print\" in data and data[\"print\"] in valid_boolean_trues:\n if not printer.is_operational():\n abort(\n 409,\n description=\"Printer is not operational, cannot directly start printing\",\n )\n select_after_slicing = print_after_slicing = True", " override_keys = [\n k for k in data if k.startswith(\"profile.\") and data[k] is not None\n ]\n overrides = {}\n for key in override_keys:\n overrides[key[len(\"profile.\") :]] = data[key]", " def slicing_done(target, path, select_after_slicing, print_after_slicing):\n if select_after_slicing or print_after_slicing:\n sd = False\n if target == FileDestinations.SDCARD:\n filenameToSelect = path\n sd = True\n else:\n filenameToSelect = fileManager.path_on_disk(target, path)\n printer.select_file(filenameToSelect, sd, print_after_slicing, user)", " try:\n fileManager.slice(\n slicer,\n target,\n filename,\n target,\n full_path,\n profile=profile,\n printer_profile_id=printerProfile,\n position=position,\n overrides=overrides,\n display=canon_name,\n callback=slicing_done,\n callback_args=(\n target,\n full_path,\n select_after_slicing,\n print_after_slicing,\n ),\n )\n except octoprint.slicing.UnknownProfile:\n abort(404, description=\"Unknown profile\")", " location = url_for(\n \".readGcodeFile\",\n target=target,\n filename=full_path,\n _external=True,\n )\n result = {\n \"name\": destination,\n \"path\": full_path,\n \"display\": canon_name,\n \"origin\": FileDestinations.LOCAL,\n \"refs\": {\n \"resource\": location,\n \"download\": url_for(\"index\", _external=True)\n + \"downloads/files/\"\n + target\n + \"/\"\n + urlquote(full_path),\n },\n }", " r = make_response(jsonify(result), 202)\n r.headers[\"Location\"] = location\n return r", " elif command == \"analyse\":\n with Permissions.FILES_UPLOAD.require(403):\n if not _verifyFileExists(target, filename):\n abort(404)", " printer_profile = None\n if \"printerProfile\" in data and data[\"printerProfile\"]:\n printer_profile = data[\"printerProfile\"]", " if not fileManager.analyse(\n target, filename, printer_profile_id=printer_profile\n ):\n abort(400, description=\"No analysis possible\")", " elif command == \"copy\" or command == \"move\":\n with Permissions.FILES_UPLOAD.require(403):\n # Copy and move are only possible on local storage\n if target not in [FileDestinations.LOCAL]:\n abort(400, description=f\"Unsupported target for {command}\")", " if not _verifyFileExists(target, filename) and not _verifyFolderExists(\n target, filename\n ):\n abort(404)", " path, name = fileManager.split_path(target, filename)", " destination = data[\"destination\"]\n dst_path, dst_name = fileManager.split_path(target, destination)\n sanitized_destination = fileManager.join_path(\n target, dst_path, fileManager.sanitize_name(target, dst_name)\n )", " # Check for exception thrown by _verifyFolderExists, if outside the root directory\n try:\n if (\n _verifyFolderExists(target, destination)\n and sanitized_destination != filename\n ):\n # destination is an existing folder and not ourselves (= display rename), we'll assume we are supposed\n # to move filename to this folder under the same name\n destination = fileManager.join_path(target, destination, name)", " if _verifyFileExists(target, destination) or _verifyFolderExists(\n target, destination\n ):\n abort(409, description=\"File or folder does already exist\")", " except Exception:\n abort(\n 409, description=\"Exception thrown by storage, bad folder/file name?\"\n )", " is_file = fileManager.file_exists(target, filename)\n is_folder = fileManager.folder_exists(target, filename)", " if not (is_file or is_folder):\n abort(400, description=f\"Neither file nor folder, can't {command}\")\n", " if command == \"copy\":\n # destination already there? error...\n if _verifyFileExists(target, destination) or _verifyFolderExists(\n target, destination\n ):\n abort(409, description=\"File or folder does already exist\")", " if is_file:\n fileManager.copy_file(target, filename, destination)", " else:", " fileManager.copy_folder(target, filename, destination)", " elif command == \"move\":\n with Permissions.FILES_DELETE.require(403):\n if _isBusy(target, filename):\n abort(\n 409,\n description=\"Trying to move a file or folder that is currently in use\",\n )", " # destination already there AND not ourselves (= display rename)? error...\n if (\n _verifyFileExists(target, destination)\n or _verifyFolderExists(target, destination)\n ) and sanitized_destination != filename:\n abort(409, description=\"File or folder does already exist\")", " # deselect the file if it's currently selected\n currentOrigin, currentFilename = _getCurrentFile()\n if currentFilename is not None and filename == currentFilename:\n printer.unselect_file()", " if is_file:\n fileManager.move_file(target, filename, destination)\n else:\n fileManager.move_folder(target, filename, destination)", "\n location = url_for(\n \".readGcodeFile\",\n target=target,\n filename=destination,\n _external=True,\n )\n result = {\n \"name\": name,\n \"path\": destination,\n \"origin\": FileDestinations.LOCAL,\n \"refs\": {\"resource\": location},\n }\n if is_file:\n result[\"refs\"][\"download\"] = (\n url_for(\"index\", _external=True)\n + \"downloads/files/\"\n + target\n + \"/\"\n + urlquote(destination)\n )", " r = make_response(jsonify(result), 201)\n r.headers[\"Location\"] = location\n return r", " return NO_CONTENT", "\n@api.route(\"/files/<string:target>/<path:filename>\", methods=[\"DELETE\"])\n@no_firstrun_access\n@Permissions.FILES_DELETE.require(403)\ndef deleteGcodeFile(filename, target):\n if not _validate(target, filename):\n abort(404)", " if not _verifyFileExists(target, filename) and not _verifyFolderExists(\n target, filename\n ):\n abort(404)", " if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:\n abort(404)", " if _verifyFileExists(target, filename):\n if _isBusy(target, filename):\n abort(409, description=\"Trying to delete a file that is currently in use\")", " # deselect the file if it's currently selected\n currentOrigin, currentPath = _getCurrentFile()\n if (\n currentPath is not None\n and currentOrigin == target\n and filename == currentPath\n ):\n printer.unselect_file()", " # delete it\n if target == FileDestinations.SDCARD:\n printer.delete_sd_file(filename, tags={\"source:api\", \"api:files.sd\"})\n else:\n fileManager.remove_file(target, filename)", " elif _verifyFolderExists(target, filename):\n if _isBusy(target, filename):\n abort(\n 409,\n description=\"Trying to delete a folder that contains a file that is currently in use\",\n )", " # deselect the file if it's currently selected\n currentOrigin, currentPath = _getCurrentFile()\n if (\n currentPath is not None\n and currentOrigin == target\n and fileManager.file_in_path(target, filename, currentPath)\n ):\n printer.unselect_file()", " # delete it\n fileManager.remove_folder(target, filename, recursive=True)", " return NO_CONTENT", "\ndef _getCurrentFile():\n currentJob = printer.get_current_job()\n if (\n currentJob is not None\n and \"file\" in currentJob\n and \"path\" in currentJob[\"file\"]\n and \"origin\" in currentJob[\"file\"]\n ):\n return currentJob[\"file\"][\"origin\"], currentJob[\"file\"][\"path\"]\n else:\n return None, None", "\ndef _validate(target, filename):\n if target == FileDestinations.SDCARD:\n # we make no assumptions about the shape of valid SDCard file names\n return True\n else:\n return filename == \"/\".join(\n map(lambda x: fileManager.sanitize_name(target, x), filename.split(\"/\"))\n )", "\nclass WerkzeugFileWrapper(octoprint.filemanager.util.AbstractFileWrapper):\n \"\"\"\n A wrapper around a Werkzeug ``FileStorage`` object.", " Arguments:\n file_obj (werkzeug.datastructures.FileStorage): The Werkzeug ``FileStorage`` instance to wrap.", " .. seealso::", " `werkzeug.datastructures.FileStorage <http://werkzeug.pocoo.org/docs/0.10/datastructures/#werkzeug.datastructures.FileStorage>`_\n The documentation of Werkzeug's ``FileStorage`` class.\n \"\"\"", " def __init__(self, file_obj):\n octoprint.filemanager.util.AbstractFileWrapper.__init__(self, file_obj.filename)\n self.file_obj = file_obj", " def save(self, path):\n \"\"\"\n Delegates to ``werkzeug.datastructures.FileStorage.save``\n \"\"\"\n self.file_obj.save(path)", " def stream(self):\n \"\"\"\n Returns ``werkzeug.datastructures.FileStorage.stream``\n \"\"\"\n return self.file_obj.stream" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [984, 842, 1177], "buggy_code_start_loc": [956, 42, 1141], "filenames": ["src/octoprint/filemanager/storage.py", "src/octoprint/server/__init__.py", "src/octoprint/server/api/files.py"], "fixing_code_end_loc": [997, 854, 1190], "fixing_code_start_loc": [957, 43, 1141], "message": "Unrestricted Upload of File with Dangerous Type in GitHub repository octoprint/octoprint prior to 1.8.3.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:octoprint:octoprint:*:*:*:*:*:*:*:*", "matchCriteriaId": "900F81F7-9FC4-44CE-ABD6-1E82DC120B4B", "versionEndExcluding": "1.8.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Unrestricted Upload of File with Dangerous Type in GitHub repository octoprint/octoprint prior to 1.8.3."}, {"lang": "es", "value": "Una Descarga sin Restricciones de Archivos de Tipo Peligroso en el repositorio GitHub octoprint/octoprint versiones anteriores a 1.8.3"}], "evaluatorComment": null, "id": "CVE-2022-2872", "lastModified": "2022-09-23T17:58:22.120", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:L/UI:R/S:U/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 1.2, "impactScore": 2.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-09-21T10:15:09.327", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/octoprint/octoprint/commit/3e3c11811e216fb371a33e28412df83f9701e5b0"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/b966c74d-6f3f-49fe-b40a-eaf25e362c56"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-434"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/octoprint/octoprint/commit/3e3c11811e216fb371a33e28412df83f9701e5b0"}, "type": "CWE-434"}
328
Determine whether the {function_name} code is vulnerable or not.
[ "__author__ = \"Gina Häußge <osd@foosel.net>\"\n__license__ = \"GNU Affero General Public License http://www.gnu.org/licenses/agpl.html\"\n__copyright__ = \"Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License\"", "import hashlib\nimport logging\nimport os\nimport threading\nfrom urllib.parse import quote as urlquote", "import psutil\nfrom flask import abort, jsonify, make_response, request, url_for", "import octoprint.filemanager\nimport octoprint.filemanager.storage\nimport octoprint.filemanager.util\nimport octoprint.slicing\nfrom octoprint.access.permissions import Permissions\nfrom octoprint.events import Events\nfrom octoprint.filemanager.destinations import FileDestinations\nfrom octoprint.server import (\n NO_CONTENT,\n current_user,\n eventManager,\n fileManager,\n printer,\n slicingManager,\n)\nfrom octoprint.server.api import api\nfrom octoprint.server.util.flask import (\n get_json_command_from_request,\n no_firstrun_access,\n with_revalidation_checking,\n)\nfrom octoprint.settings import settings, valid_boolean_trues\nfrom octoprint.util import sv, time_this", "# ~~ GCODE file handling", "_file_cache = {}\n_file_cache_mutex = threading.RLock()", "_DATA_FORMAT_VERSION = \"v2\"", "\ndef _clear_file_cache():\n with _file_cache_mutex:\n _file_cache.clear()", "\ndef _create_lastmodified(path, recursive):\n path = path[len(\"/api/files\") :]\n if path.startswith(\"/\"):\n path = path[1:]", " if path == \"\":\n # all storages involved\n lms = [0]\n for storage in fileManager.registered_storages:\n try:\n lms.append(fileManager.last_modified(storage, recursive=recursive))\n except Exception:\n logging.getLogger(__name__).exception(\n \"There was an error retrieving the last modified data from storage {}\".format(\n storage\n )\n )\n lms.append(None)", " if any(filter(lambda x: x is None, lms)):\n # we return None if ANY of the involved storages returned None\n return None", " # if we reach this point, we return the maximum of all dates\n return max(lms)", " else:\n if \"/\" in path:\n storage, path_in_storage = path.split(\"/\", 1)\n else:\n storage = path\n path_in_storage = None", " try:\n return fileManager.last_modified(\n storage, path=path_in_storage, recursive=recursive\n )\n except Exception:\n logging.getLogger(__name__).exception(\n \"There was an error retrieving the last modified data from storage {} and path {}\".format(\n storage, path_in_storage\n )\n )\n return None", "\ndef _create_etag(path, filter, recursive, lm=None):\n if lm is None:\n lm = _create_lastmodified(path, recursive)", " if lm is None:\n return None", " hash = hashlib.sha1()", " def hash_update(value):\n value = value.encode(\"utf-8\")\n hash.update(value)", " hash_update(str(lm))\n hash_update(str(filter))\n hash_update(str(recursive))", " path = path[len(\"/api/files\") :]\n if path.startswith(\"/\"):\n path = path[1:]", " if \"/\" in path:\n storage, _ = path.split(\"/\", 1)\n else:\n storage = path", " if path == \"\" or storage == FileDestinations.SDCARD:\n # include sd data in etag\n hash_update(repr(sorted(printer.get_sd_files(), key=lambda x: sv(x[\"name\"]))))", " hash_update(_DATA_FORMAT_VERSION) # increment version if we change the API format", " return hash.hexdigest()", "\n@api.route(\"/files\", methods=[\"GET\"])\n@Permissions.FILES_LIST.require(403)\n@with_revalidation_checking(\n etag_factory=lambda lm=None: _create_etag(\n request.path,\n request.values.get(\"filter\", False),\n request.values.get(\"recursive\", False),\n lm=lm,\n ),\n lastmodified_factory=lambda: _create_lastmodified(\n request.path, request.values.get(\"recursive\", False)\n ),\n unless=lambda: request.values.get(\"force\", False)\n or request.values.get(\"_refresh\", False),\n)\ndef readGcodeFiles():\n filter = request.values.get(\"filter\", False)\n recursive = request.values.get(\"recursive\", \"false\") in valid_boolean_trues\n force = request.values.get(\"force\", \"false\") in valid_boolean_trues", " files = _getFileList(\n FileDestinations.LOCAL,\n filter=filter,\n recursive=recursive,\n allow_from_cache=not force,\n )\n files.extend(_getFileList(FileDestinations.SDCARD, allow_from_cache=not force))", " usage = psutil.disk_usage(settings().getBaseFolder(\"uploads\", check_writable=False))\n return jsonify(files=files, free=usage.free, total=usage.total)", "\n@api.route(\"/files/test\", methods=[\"POST\"])\n@Permissions.FILES_LIST.require(403)\ndef runFilesTest():\n valid_commands = {\n \"sanitize\": [\"storage\", \"path\", \"filename\"],\n \"exists\": [\"storage\", \"path\", \"filename\"],\n }", " command, data, response = get_json_command_from_request(request, valid_commands)\n if response is not None:\n return response", " def sanitize(storage, path, filename):\n sanitized_path = fileManager.sanitize_path(storage, path)\n sanitized_name = fileManager.sanitize_name(storage, filename)\n joined = fileManager.join_path(storage, sanitized_path, sanitized_name)\n return sanitized_path, sanitized_name, joined", " if command == \"sanitize\":\n _, _, sanitized = sanitize(data[\"storage\"], data[\"path\"], data[\"filename\"])\n return jsonify(sanitized=sanitized)\n elif command == \"exists\":\n storage = data[\"storage\"]\n path = data[\"path\"]\n filename = data[\"filename\"]", " sanitized_path, _, sanitized = sanitize(storage, path, filename)", " exists = fileManager.file_exists(storage, sanitized)\n if exists:\n suggestion = filename\n name, ext = os.path.splitext(filename)\n counter = 0\n while fileManager.file_exists(\n storage,\n fileManager.join_path(\n storage,\n sanitized_path,\n fileManager.sanitize_name(storage, suggestion),\n ),\n ):\n counter += 1\n suggestion = f\"{name}_{counter}{ext}\"\n return jsonify(exists=True, suggestion=suggestion)\n else:\n return jsonify(exists=False)", "\n@api.route(\"/files/<string:origin>\", methods=[\"GET\"])\n@Permissions.FILES_LIST.require(403)\n@with_revalidation_checking(\n etag_factory=lambda lm=None: _create_etag(\n request.path,\n request.values.get(\"filter\", False),\n request.values.get(\"recursive\", False),\n lm=lm,\n ),\n lastmodified_factory=lambda: _create_lastmodified(\n request.path, request.values.get(\"recursive\", False)\n ),\n unless=lambda: request.values.get(\"force\", False)\n or request.values.get(\"_refresh\", False),\n)\ndef readGcodeFilesForOrigin(origin):\n if origin not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:\n abort(404)", " filter = request.values.get(\"filter\", False)\n recursive = request.values.get(\"recursive\", \"false\") in valid_boolean_trues\n force = request.values.get(\"force\", \"false\") in valid_boolean_trues", " files = _getFileList(\n origin, filter=filter, recursive=recursive, allow_from_cache=not force\n )", " if origin == FileDestinations.LOCAL:\n usage = psutil.disk_usage(\n settings().getBaseFolder(\"uploads\", check_writable=False)\n )\n return jsonify(files=files, free=usage.free, total=usage.total)\n else:\n return jsonify(files=files)", "\n@api.route(\"/files/<string:target>/<path:filename>\", methods=[\"GET\"])\n@Permissions.FILES_LIST.require(403)\n@with_revalidation_checking(\n etag_factory=lambda lm=None: _create_etag(\n request.path,\n request.values.get(\"filter\", False),\n request.values.get(\"recursive\", False),\n lm=lm,\n ),\n lastmodified_factory=lambda: _create_lastmodified(\n request.path, request.values.get(\"recursive\", False)\n ),\n unless=lambda: request.values.get(\"force\", False)\n or request.values.get(\"_refresh\", False),\n)\ndef readGcodeFile(target, filename):\n if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:\n abort(404)", " if not _validate(target, filename):\n abort(404)", " recursive = False\n if \"recursive\" in request.values:\n recursive = request.values[\"recursive\"] in valid_boolean_trues", " file = _getFileDetails(target, filename, recursive=recursive)\n if not file:\n abort(404)", " return jsonify(file)", "\ndef _getFileDetails(origin, path, recursive=True):\n parent, path = os.path.split(path)\n files = _getFileList(origin, path=parent, recursive=recursive, level=1)", " for f in files:\n if f[\"name\"] == path:\n return f\n else:\n return None", "\n@time_this(\n logtarget=__name__ + \".timings\",\n message=\"{func}({func_args},{func_kwargs}) took {timing:.2f}ms\",\n incl_func_args=True,\n log_enter=True,\n message_enter=\"Entering {func}({func_args},{func_kwargs})...\",\n)\ndef _getFileList(\n origin, path=None, filter=None, recursive=False, level=0, allow_from_cache=True\n):\n if origin == FileDestinations.SDCARD:\n sdFileList = printer.get_sd_files(refresh=not allow_from_cache)", " files = []\n if sdFileList is not None:\n for f in sdFileList:\n type_path = octoprint.filemanager.get_file_type(f[\"name\"])\n if not type_path:\n # only supported extensions\n continue\n else:\n file_type = type_path[0]", " file = {\n \"type\": file_type,\n \"typePath\": type_path,\n \"name\": f[\"name\"],\n \"display\": f[\"display\"] if f[\"display\"] else f[\"name\"],\n \"path\": f[\"name\"],\n \"origin\": FileDestinations.SDCARD,\n \"refs\": {\n \"resource\": url_for(\n \".readGcodeFile\",\n target=FileDestinations.SDCARD,\n filename=f[\"name\"],\n _external=True,\n )\n },\n }\n if f[\"size\"] is not None:\n file.update({\"size\": f[\"size\"]})\n files.append(file)\n else:\n filter_func = None\n if filter:\n filter_func = lambda entry, entry_data: octoprint.filemanager.valid_file_type(\n entry, type=filter\n )", " with _file_cache_mutex:\n cache_key = f\"{origin}:{path}:{recursive}:{filter}\"\n files, lastmodified = _file_cache.get(cache_key, ([], None))\n # recursive needs to be True for lastmodified queries so we get lastmodified of whole subtree - #3422\n if (\n not allow_from_cache\n or lastmodified is None\n or lastmodified\n < fileManager.last_modified(origin, path=path, recursive=True)\n ):\n files = list(\n fileManager.list_files(\n origin,\n path=path,\n filter=filter_func,\n recursive=recursive,\n level=level,\n force_refresh=not allow_from_cache,\n )[origin].values()\n )\n lastmodified = fileManager.last_modified(\n origin, path=path, recursive=True\n )\n _file_cache[cache_key] = (files, lastmodified)", " def analyse_recursively(files, path=None):\n if path is None:\n path = \"\"", " result = []\n for file_or_folder in files:\n # make a shallow copy in order to not accidentally modify the cached data\n file_or_folder = dict(file_or_folder)", " file_or_folder[\"origin\"] = FileDestinations.LOCAL", " if file_or_folder[\"type\"] == \"folder\":\n if \"children\" in file_or_folder:\n file_or_folder[\"children\"] = analyse_recursively(\n file_or_folder[\"children\"].values(),\n path + file_or_folder[\"name\"] + \"/\",\n )", " file_or_folder[\"refs\"] = {\n \"resource\": url_for(\n \".readGcodeFile\",\n target=FileDestinations.LOCAL,\n filename=path + file_or_folder[\"name\"],\n _external=True,\n )\n }\n else:\n if (\n \"analysis\" in file_or_folder\n and octoprint.filemanager.valid_file_type(\n file_or_folder[\"name\"], type=\"gcode\"\n )\n ):\n file_or_folder[\"gcodeAnalysis\"] = file_or_folder[\"analysis\"]\n del file_or_folder[\"analysis\"]", " if (\n \"history\" in file_or_folder\n and octoprint.filemanager.valid_file_type(\n file_or_folder[\"name\"], type=\"gcode\"\n )\n ):\n # convert print log\n history = file_or_folder[\"history\"]\n del file_or_folder[\"history\"]\n success = 0\n failure = 0\n last = None\n for entry in history:\n success += 1 if \"success\" in entry and entry[\"success\"] else 0\n failure += (\n 1 if \"success\" in entry and not entry[\"success\"] else 0\n )\n if not last or (\n \"timestamp\" in entry\n and \"timestamp\" in last\n and entry[\"timestamp\"] > last[\"timestamp\"]\n ):\n last = entry\n if last:\n prints = {\n \"success\": success,\n \"failure\": failure,\n \"last\": {\n \"success\": last[\"success\"],\n \"date\": last[\"timestamp\"],\n },\n }\n if \"printTime\" in last:\n prints[\"last\"][\"printTime\"] = last[\"printTime\"]\n file_or_folder[\"prints\"] = prints", " file_or_folder[\"refs\"] = {\n \"resource\": url_for(\n \".readGcodeFile\",\n target=FileDestinations.LOCAL,\n filename=file_or_folder[\"path\"],\n _external=True,\n ),\n \"download\": url_for(\"index\", _external=True)\n + \"downloads/files/\"\n + FileDestinations.LOCAL\n + \"/\"\n + urlquote(file_or_folder[\"path\"]),\n }", " result.append(file_or_folder)", " return result", " files = analyse_recursively(files)", " return files", "\ndef _verifyFileExists(origin, filename):\n if origin == FileDestinations.SDCARD:\n return filename in (x[\"name\"] for x in printer.get_sd_files())\n else:\n return fileManager.file_exists(origin, filename)", "\ndef _verifyFolderExists(origin, foldername):\n if origin == FileDestinations.SDCARD:\n return False\n else:\n return fileManager.folder_exists(origin, foldername)", "\ndef _isBusy(target, path):\n currentOrigin, currentPath = _getCurrentFile()\n if (\n currentPath is not None\n and currentOrigin == target\n and fileManager.file_in_path(FileDestinations.LOCAL, path, currentPath)\n and (printer.is_printing() or printer.is_paused())\n ):\n return True", " return any(\n target == x[0] and fileManager.file_in_path(FileDestinations.LOCAL, path, x[1])\n for x in fileManager.get_busy_files()\n )", "\n@api.route(\"/files/<string:target>\", methods=[\"POST\"])\n@no_firstrun_access\n@Permissions.FILES_UPLOAD.require(403)\ndef uploadGcodeFile(target):\n input_name = \"file\"\n input_upload_name = (\n input_name + \".\" + settings().get([\"server\", \"uploads\", \"nameSuffix\"])\n )\n input_upload_path = (\n input_name + \".\" + settings().get([\"server\", \"uploads\", \"pathSuffix\"])\n )\n if input_upload_name in request.values and input_upload_path in request.values:\n if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:\n abort(404)", " upload = octoprint.filemanager.util.DiskFileWrapper(\n request.values[input_upload_name], request.values[input_upload_path]\n )", " # Store any additional user data the caller may have passed.\n userdata = None\n if \"userdata\" in request.values:\n import json", " try:\n userdata = json.loads(request.values[\"userdata\"])\n except Exception:\n abort(400, description=\"userdata contains invalid JSON\")", " # check preconditions for SD upload\n if target == FileDestinations.SDCARD and not settings().getBoolean(\n [\"feature\", \"sdSupport\"]\n ):\n abort(404)", " sd = target == FileDestinations.SDCARD\n if sd:\n # validate that all preconditions for SD upload are met before attempting it\n if not (\n printer.is_operational()\n and not (printer.is_printing() or printer.is_paused())\n ):\n abort(\n 409,\n description=\"Can not upload to SD card, printer is either not operational or already busy\",\n )\n if not printer.is_sd_ready():\n abort(409, description=\"Can not upload to SD card, not yet initialized\")", " # evaluate select and print parameter and if set check permissions & preconditions\n # and adjust as necessary\n #\n # we do NOT abort(409) here since this would be a backwards incompatible behaviour change\n # on the API, but instead return the actually effective select and print flags in the response\n #\n # note that this behaviour might change in a future API version\n select_request = (\n \"select\" in request.values\n and request.values[\"select\"] in valid_boolean_trues\n and Permissions.FILES_SELECT.can()\n )\n print_request = (\n \"print\" in request.values\n and request.values[\"print\"] in valid_boolean_trues\n and Permissions.PRINT.can()\n )", " to_select = select_request\n to_print = print_request\n if (to_select or to_print) and not (\n printer.is_operational()\n and not (printer.is_printing() or printer.is_paused())\n ):\n # can't select or print files if not operational or ready\n to_select = to_print = False", " # determine future filename of file to be uploaded, abort if it can't be uploaded\n try:\n # FileDestinations.LOCAL = should normally be target, but can't because SDCard handling isn't implemented yet\n canonPath, canonFilename = fileManager.canonicalize(\n FileDestinations.LOCAL, upload.filename\n )\n if request.values.get(\"path\"):\n canonPath = request.values.get(\"path\")\n if request.values.get(\"filename\"):\n canonFilename = request.values.get(\"filename\")", " futurePath = fileManager.sanitize_path(FileDestinations.LOCAL, canonPath)\n futureFilename = fileManager.sanitize_name(\n FileDestinations.LOCAL, canonFilename\n )\n except Exception:\n canonFilename = None\n futurePath = None\n futureFilename = None", " if futureFilename is None:\n abort(400, description=\"Can not upload file, invalid file name\")", " # prohibit overwriting currently selected file while it's being printed\n futureFullPath = fileManager.join_path(\n FileDestinations.LOCAL, futurePath, futureFilename\n )\n futureFullPathInStorage = fileManager.path_in_storage(\n FileDestinations.LOCAL, futureFullPath\n )", " if not printer.can_modify_file(futureFullPathInStorage, sd):\n abort(\n 409,\n description=\"Trying to overwrite file that is currently being printed\",\n )", " if (\n fileManager.file_exists(FileDestinations.LOCAL, futureFullPathInStorage)\n and request.values.get(\"noOverwrite\") in valid_boolean_trues\n ):\n abort(409, description=\"File already exists and noOverwrite was set\")", " reselect = printer.is_current_file(futureFullPathInStorage, sd)", " user = current_user.get_name()", " def fileProcessingFinished(filename, absFilename, destination):\n \"\"\"\n Callback for when the file processing (upload, optional slicing, addition to analysis queue) has\n finished.", " Depending on the file's destination triggers either streaming to SD card or directly calls to_select.\n \"\"\"", " if (\n destination == FileDestinations.SDCARD\n and octoprint.filemanager.valid_file_type(filename, \"machinecode\")\n ):\n return filename, printer.add_sd_file(\n filename,\n absFilename,\n on_success=selectAndOrPrint,\n tags={\"source:api\", \"api:files.sd\"},\n )\n else:\n selectAndOrPrint(filename, absFilename, destination)\n return filename", " def selectAndOrPrint(filename, absFilename, destination):\n \"\"\"\n Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only\n the case after they have finished streaming to the printer, which is why this callback is also used\n for the corresponding call to addSdFile.", " Selects the just uploaded file if either to_select or to_print are True, or if the\n exact file is already selected, such reloading it.\n \"\"\"\n if octoprint.filemanager.valid_file_type(added_file, \"gcode\") and (\n to_select or to_print or reselect\n ):\n printer.select_file(\n absFilename,\n destination == FileDestinations.SDCARD,\n to_print,\n user,\n )", " try:\n added_file = fileManager.add_file(\n FileDestinations.LOCAL,\n futureFullPathInStorage,\n upload,\n allow_overwrite=True,\n display=canonFilename,\n )\n except octoprint.filemanager.storage.StorageError as e:\n if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE:\n abort(415, description=\"Could not upload file, invalid type\")\n else:\n abort(500, description=\"Could not upload file\")\n else:\n filename = fileProcessingFinished(\n added_file,\n fileManager.path_on_disk(FileDestinations.LOCAL, added_file),\n target,\n )\n done = not sd", " if userdata is not None:\n # upload included userdata, add this now to the metadata\n fileManager.set_additional_metadata(\n FileDestinations.LOCAL, added_file, \"userdata\", userdata\n )", " sdFilename = None\n if isinstance(filename, tuple):\n filename, sdFilename = filename", " payload = {\n \"name\": futureFilename,\n \"path\": filename,\n \"target\": target,\n \"select\": select_request,\n \"print\": print_request,\n \"effective_select\": to_select,\n \"effective_print\": to_print,\n }\n if userdata is not None:\n payload[\"userdata\"] = userdata\n eventManager.fire(Events.UPLOAD, payload)", " files = {}\n location = url_for(\n \".readGcodeFile\",\n target=FileDestinations.LOCAL,\n filename=filename,\n _external=True,\n )\n files.update(\n {\n FileDestinations.LOCAL: {\n \"name\": futureFilename,\n \"path\": filename,\n \"origin\": FileDestinations.LOCAL,\n \"refs\": {\n \"resource\": location,\n \"download\": url_for(\"index\", _external=True)\n + \"downloads/files/\"\n + FileDestinations.LOCAL\n + \"/\"\n + urlquote(filename),\n },\n }\n }\n )", " if sd and sdFilename:\n location = url_for(\n \".readGcodeFile\",\n target=FileDestinations.SDCARD,\n filename=sdFilename,\n _external=True,\n )\n files.update(\n {\n FileDestinations.SDCARD: {\n \"name\": sdFilename,\n \"path\": sdFilename,\n \"origin\": FileDestinations.SDCARD,\n \"refs\": {\"resource\": location},\n }\n }\n )", " r = make_response(\n jsonify(\n files=files,\n done=done,\n effectiveSelect=to_select,\n effectivePrint=to_print,\n ),\n 201,\n )\n r.headers[\"Location\"] = location\n return r", " elif \"foldername\" in request.values:\n foldername = request.values[\"foldername\"]", " if target not in [FileDestinations.LOCAL]:\n abort(400, description=\"target is invalid\")", " canonPath, canonName = fileManager.canonicalize(target, foldername)\n futurePath = fileManager.sanitize_path(target, canonPath)\n futureName = fileManager.sanitize_name(target, canonName)\n if not futureName or not futurePath:\n abort(400, description=\"folder name is empty\")", " if \"path\" in request.values and request.values[\"path\"]:\n futurePath = fileManager.sanitize_path(\n FileDestinations.LOCAL, request.values[\"path\"]\n )", " futureFullPath = fileManager.join_path(target, futurePath, futureName)\n if octoprint.filemanager.valid_file_type(futureName):\n abort(409, description=\"Can't create folder, please try another name\")", " try:\n added_folder = fileManager.add_folder(\n target, futureFullPath, display=canonName\n )\n except octoprint.filemanager.storage.StorageError as e:\n if e.code == octoprint.filemanager.storage.StorageError.INVALID_DIRECTORY:\n abort(400, description=\"Could not create folder, invalid directory\")\n else:\n abort(500, description=\"Could not create folder\")", " location = url_for(\n \".readGcodeFile\",\n target=FileDestinations.LOCAL,\n filename=added_folder,\n _external=True,\n )\n folder = {\n \"name\": futureName,\n \"path\": added_folder,\n \"origin\": target,\n \"refs\": {\"resource\": location},\n }", " r = make_response(jsonify(folder=folder, done=True), 201)\n r.headers[\"Location\"] = location\n return r", " else:\n abort(400, description=\"No file to upload and no folder to create\")", "\n@api.route(\"/files/<string:target>/<path:filename>\", methods=[\"POST\"])\n@no_firstrun_access\ndef gcodeFileCommand(filename, target):\n if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:\n abort(404)", " if not _validate(target, filename):\n abort(404)", " # valid file commands, dict mapping command name to mandatory parameters\n valid_commands = {\n \"select\": [],\n \"unselect\": [],\n \"slice\": [],\n \"analyse\": [],\n \"copy\": [\"destination\"],\n \"move\": [\"destination\"],\n }", " command, data, response = get_json_command_from_request(request, valid_commands)\n if response is not None:\n return response", " user = current_user.get_name()", " if command == \"select\":\n with Permissions.FILES_SELECT.require(403):\n if not _verifyFileExists(target, filename):\n abort(404)", " # selects/loads a file\n if not octoprint.filemanager.valid_file_type(filename, type=\"machinecode\"):\n abort(\n 415,\n description=\"Cannot select file for printing, not a machinecode file\",\n )", " if not printer.is_ready():\n abort(\n 409,\n description=\"Printer is already printing, cannot select a new file\",\n )", " printAfterLoading = False\n if \"print\" in data and data[\"print\"] in valid_boolean_trues:\n with Permissions.PRINT.require(403):\n if not printer.is_operational():\n abort(\n 409,\n description=\"Printer is not operational, cannot directly start printing\",\n )\n printAfterLoading = True", " sd = False\n if target == FileDestinations.SDCARD:\n filenameToSelect = filename\n sd = True\n else:\n filenameToSelect = fileManager.path_on_disk(target, filename)\n printer.select_file(filenameToSelect, sd, printAfterLoading, user)", " elif command == \"unselect\":\n with Permissions.FILES_SELECT.require(403):\n if not printer.is_ready():\n return make_response(\n \"Printer is already printing, cannot unselect current file\", 409\n )", " _, currentFilename = _getCurrentFile()\n if currentFilename is None:\n return make_response(\n \"Cannot unselect current file when there is no file selected\", 409\n )", " if filename != currentFilename and filename != \"current\":\n return make_response(\n \"Only the currently selected file can be unselected\", 400\n )", " printer.unselect_file()", " elif command == \"slice\":\n with Permissions.SLICE.require(403):\n if not _verifyFileExists(target, filename):\n abort(404)", " try:\n if \"slicer\" in data:\n slicer = data[\"slicer\"]\n del data[\"slicer\"]\n slicer_instance = slicingManager.get_slicer(slicer)", " elif \"cura\" in slicingManager.registered_slicers:\n slicer = \"cura\"\n slicer_instance = slicingManager.get_slicer(\"cura\")", " else:\n abort(415, description=\"Cannot slice file, no slicer available\")\n except octoprint.slicing.UnknownSlicer:\n abort(404)", " if not any(\n [\n octoprint.filemanager.valid_file_type(filename, type=source_file_type)\n for source_file_type in slicer_instance.get_slicer_properties().get(\n \"source_file_types\", [\"model\"]\n )\n ]\n ):\n abort(415, description=\"Cannot slice file, not a model file\")", " cores = psutil.cpu_count()\n if (\n slicer_instance.get_slicer_properties().get(\"same_device\", True)\n and (printer.is_printing() or printer.is_paused())\n and (cores is None or cores < 2)\n ):\n # slicer runs on same device as OctoPrint, slicing while printing is hence disabled\n abort(\n 409,\n description=\"Cannot slice on this slicer while printing on single core systems or systems of unknown core count due to performance reasons\",\n )", " if \"destination\" in data and data[\"destination\"]:\n destination = data[\"destination\"]\n del data[\"destination\"]\n elif \"gcode\" in data and data[\"gcode\"]:\n destination = data[\"gcode\"]\n del data[\"gcode\"]\n else:\n import os", " name, _ = os.path.splitext(filename)\n destination = (\n name\n + \".\"\n + slicer_instance.get_slicer_properties().get(\n \"destination_extensions\", [\"gco\", \"gcode\", \"g\"]\n )[0]\n )", " full_path = destination\n if \"path\" in data and data[\"path\"]:\n full_path = fileManager.join_path(target, data[\"path\"], destination)\n else:\n path, _ = fileManager.split_path(target, filename)\n if path:\n full_path = fileManager.join_path(target, path, destination)", " canon_path, canon_name = fileManager.canonicalize(target, full_path)\n sanitized_name = fileManager.sanitize_name(target, canon_name)", " if canon_path:\n full_path = fileManager.join_path(target, canon_path, sanitized_name)\n else:\n full_path = sanitized_name", " # prohibit overwriting the file that is currently being printed\n currentOrigin, currentFilename = _getCurrentFile()\n if (\n currentFilename == full_path\n and currentOrigin == target\n and (printer.is_printing() or printer.is_paused())\n ):\n abort(\n 409,\n description=\"Trying to slice into file that is currently being printed\",\n )", " if \"profile\" in data and data[\"profile\"]:\n profile = data[\"profile\"]\n del data[\"profile\"]\n else:\n profile = None", " if \"printerProfile\" in data and data[\"printerProfile\"]:\n printerProfile = data[\"printerProfile\"]\n del data[\"printerProfile\"]\n else:\n printerProfile = None", " if (\n \"position\" in data\n and data[\"position\"]\n and isinstance(data[\"position\"], dict)\n and \"x\" in data[\"position\"]\n and \"y\" in data[\"position\"]\n ):\n position = data[\"position\"]\n del data[\"position\"]\n else:\n position = None", " select_after_slicing = False\n if \"select\" in data and data[\"select\"] in valid_boolean_trues:\n if not printer.is_operational():\n abort(\n 409,\n description=\"Printer is not operational, cannot directly select for printing\",\n )\n select_after_slicing = True", " print_after_slicing = False\n if \"print\" in data and data[\"print\"] in valid_boolean_trues:\n if not printer.is_operational():\n abort(\n 409,\n description=\"Printer is not operational, cannot directly start printing\",\n )\n select_after_slicing = print_after_slicing = True", " override_keys = [\n k for k in data if k.startswith(\"profile.\") and data[k] is not None\n ]\n overrides = {}\n for key in override_keys:\n overrides[key[len(\"profile.\") :]] = data[key]", " def slicing_done(target, path, select_after_slicing, print_after_slicing):\n if select_after_slicing or print_after_slicing:\n sd = False\n if target == FileDestinations.SDCARD:\n filenameToSelect = path\n sd = True\n else:\n filenameToSelect = fileManager.path_on_disk(target, path)\n printer.select_file(filenameToSelect, sd, print_after_slicing, user)", " try:\n fileManager.slice(\n slicer,\n target,\n filename,\n target,\n full_path,\n profile=profile,\n printer_profile_id=printerProfile,\n position=position,\n overrides=overrides,\n display=canon_name,\n callback=slicing_done,\n callback_args=(\n target,\n full_path,\n select_after_slicing,\n print_after_slicing,\n ),\n )\n except octoprint.slicing.UnknownProfile:\n abort(404, description=\"Unknown profile\")", " location = url_for(\n \".readGcodeFile\",\n target=target,\n filename=full_path,\n _external=True,\n )\n result = {\n \"name\": destination,\n \"path\": full_path,\n \"display\": canon_name,\n \"origin\": FileDestinations.LOCAL,\n \"refs\": {\n \"resource\": location,\n \"download\": url_for(\"index\", _external=True)\n + \"downloads/files/\"\n + target\n + \"/\"\n + urlquote(full_path),\n },\n }", " r = make_response(jsonify(result), 202)\n r.headers[\"Location\"] = location\n return r", " elif command == \"analyse\":\n with Permissions.FILES_UPLOAD.require(403):\n if not _verifyFileExists(target, filename):\n abort(404)", " printer_profile = None\n if \"printerProfile\" in data and data[\"printerProfile\"]:\n printer_profile = data[\"printerProfile\"]", " if not fileManager.analyse(\n target, filename, printer_profile_id=printer_profile\n ):\n abort(400, description=\"No analysis possible\")", " elif command == \"copy\" or command == \"move\":\n with Permissions.FILES_UPLOAD.require(403):\n # Copy and move are only possible on local storage\n if target not in [FileDestinations.LOCAL]:\n abort(400, description=f\"Unsupported target for {command}\")", " if not _verifyFileExists(target, filename) and not _verifyFolderExists(\n target, filename\n ):\n abort(404)", " path, name = fileManager.split_path(target, filename)", " destination = data[\"destination\"]\n dst_path, dst_name = fileManager.split_path(target, destination)\n sanitized_destination = fileManager.join_path(\n target, dst_path, fileManager.sanitize_name(target, dst_name)\n )", " # Check for exception thrown by _verifyFolderExists, if outside the root directory\n try:\n if (\n _verifyFolderExists(target, destination)\n and sanitized_destination != filename\n ):\n # destination is an existing folder and not ourselves (= display rename), we'll assume we are supposed\n # to move filename to this folder under the same name\n destination = fileManager.join_path(target, destination, name)", " if _verifyFileExists(target, destination) or _verifyFolderExists(\n target, destination\n ):\n abort(409, description=\"File or folder does already exist\")", " except Exception:\n abort(\n 409, description=\"Exception thrown by storage, bad folder/file name?\"\n )", " is_file = fileManager.file_exists(target, filename)\n is_folder = fileManager.folder_exists(target, filename)", " if not (is_file or is_folder):\n abort(400, description=f\"Neither file nor folder, can't {command}\")\n", " try:\n if command == \"copy\":\n # destination already there? error...\n if _verifyFileExists(target, destination) or _verifyFolderExists(\n target, destination\n ):\n abort(409, description=\"File or folder does already exist\")", " if is_file:\n fileManager.copy_file(target, filename, destination)\n else:\n fileManager.copy_folder(target, filename, destination)", " elif command == \"move\":\n with Permissions.FILES_DELETE.require(403):\n if _isBusy(target, filename):\n abort(\n 409,\n description=\"Trying to move a file or folder that is currently in use\",\n )", " # destination already there AND not ourselves (= display rename)? error...\n if (\n _verifyFileExists(target, destination)\n or _verifyFolderExists(target, destination)\n ) and sanitized_destination != filename:\n abort(409, description=\"File or folder does already exist\")", " # deselect the file if it's currently selected\n currentOrigin, currentFilename = _getCurrentFile()\n if currentFilename is not None and filename == currentFilename:\n printer.unselect_file()", " if is_file:\n fileManager.move_file(target, filename, destination)\n else:\n fileManager.move_folder(target, filename, destination)", " except octoprint.filemanager.storage.StorageError as e:\n if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE:\n abort(\n 415,\n description=f\"Could not {command} {filename} to {destination}, invalid type\",\n )", " else:", " abort(\n 500,\n description=f\"Could not {command} {filename} to {destination}\",\n )", "\n location = url_for(\n \".readGcodeFile\",\n target=target,\n filename=destination,\n _external=True,\n )\n result = {\n \"name\": name,\n \"path\": destination,\n \"origin\": FileDestinations.LOCAL,\n \"refs\": {\"resource\": location},\n }\n if is_file:\n result[\"refs\"][\"download\"] = (\n url_for(\"index\", _external=True)\n + \"downloads/files/\"\n + target\n + \"/\"\n + urlquote(destination)\n )", " r = make_response(jsonify(result), 201)\n r.headers[\"Location\"] = location\n return r", " return NO_CONTENT", "\n@api.route(\"/files/<string:target>/<path:filename>\", methods=[\"DELETE\"])\n@no_firstrun_access\n@Permissions.FILES_DELETE.require(403)\ndef deleteGcodeFile(filename, target):\n if not _validate(target, filename):\n abort(404)", " if not _verifyFileExists(target, filename) and not _verifyFolderExists(\n target, filename\n ):\n abort(404)", " if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:\n abort(404)", " if _verifyFileExists(target, filename):\n if _isBusy(target, filename):\n abort(409, description=\"Trying to delete a file that is currently in use\")", " # deselect the file if it's currently selected\n currentOrigin, currentPath = _getCurrentFile()\n if (\n currentPath is not None\n and currentOrigin == target\n and filename == currentPath\n ):\n printer.unselect_file()", " # delete it\n if target == FileDestinations.SDCARD:\n printer.delete_sd_file(filename, tags={\"source:api\", \"api:files.sd\"})\n else:\n fileManager.remove_file(target, filename)", " elif _verifyFolderExists(target, filename):\n if _isBusy(target, filename):\n abort(\n 409,\n description=\"Trying to delete a folder that contains a file that is currently in use\",\n )", " # deselect the file if it's currently selected\n currentOrigin, currentPath = _getCurrentFile()\n if (\n currentPath is not None\n and currentOrigin == target\n and fileManager.file_in_path(target, filename, currentPath)\n ):\n printer.unselect_file()", " # delete it\n fileManager.remove_folder(target, filename, recursive=True)", " return NO_CONTENT", "\ndef _getCurrentFile():\n currentJob = printer.get_current_job()\n if (\n currentJob is not None\n and \"file\" in currentJob\n and \"path\" in currentJob[\"file\"]\n and \"origin\" in currentJob[\"file\"]\n ):\n return currentJob[\"file\"][\"origin\"], currentJob[\"file\"][\"path\"]\n else:\n return None, None", "\ndef _validate(target, filename):\n if target == FileDestinations.SDCARD:\n # we make no assumptions about the shape of valid SDCard file names\n return True\n else:\n return filename == \"/\".join(\n map(lambda x: fileManager.sanitize_name(target, x), filename.split(\"/\"))\n )", "\nclass WerkzeugFileWrapper(octoprint.filemanager.util.AbstractFileWrapper):\n \"\"\"\n A wrapper around a Werkzeug ``FileStorage`` object.", " Arguments:\n file_obj (werkzeug.datastructures.FileStorage): The Werkzeug ``FileStorage`` instance to wrap.", " .. seealso::", " `werkzeug.datastructures.FileStorage <http://werkzeug.pocoo.org/docs/0.10/datastructures/#werkzeug.datastructures.FileStorage>`_\n The documentation of Werkzeug's ``FileStorage`` class.\n \"\"\"", " def __init__(self, file_obj):\n octoprint.filemanager.util.AbstractFileWrapper.__init__(self, file_obj.filename)\n self.file_obj = file_obj", " def save(self, path):\n \"\"\"\n Delegates to ``werkzeug.datastructures.FileStorage.save``\n \"\"\"\n self.file_obj.save(path)", " def stream(self):\n \"\"\"\n Returns ``werkzeug.datastructures.FileStorage.stream``\n \"\"\"\n return self.file_obj.stream" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [984, 842, 1177], "buggy_code_start_loc": [956, 42, 1141], "filenames": ["src/octoprint/filemanager/storage.py", "src/octoprint/server/__init__.py", "src/octoprint/server/api/files.py"], "fixing_code_end_loc": [997, 854, 1190], "fixing_code_start_loc": [957, 43, 1141], "message": "Unrestricted Upload of File with Dangerous Type in GitHub repository octoprint/octoprint prior to 1.8.3.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:octoprint:octoprint:*:*:*:*:*:*:*:*", "matchCriteriaId": "900F81F7-9FC4-44CE-ABD6-1E82DC120B4B", "versionEndExcluding": "1.8.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Unrestricted Upload of File with Dangerous Type in GitHub repository octoprint/octoprint prior to 1.8.3."}, {"lang": "es", "value": "Una Descarga sin Restricciones de Archivos de Tipo Peligroso en el repositorio GitHub octoprint/octoprint versiones anteriores a 1.8.3"}], "evaluatorComment": null, "id": "CVE-2022-2872", "lastModified": "2022-09-23T17:58:22.120", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:L/UI:R/S:U/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 1.2, "impactScore": 2.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-09-21T10:15:09.327", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/octoprint/octoprint/commit/3e3c11811e216fb371a33e28412df83f9701e5b0"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/b966c74d-6f3f-49fe-b40a-eaf25e362c56"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-434"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/octoprint/octoprint/commit/3e3c11811e216fb371a33e28412df83f9701e5b0"}, "type": "CWE-434"}
328
Determine whether the {function_name} code is vulnerable or not.
[ "package io.metersphere.gateway.filter;", "import org.apache.commons.lang3.StringUtils;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.cloud.client.discovery.DiscoveryClient;\nimport org.springframework.cloud.gateway.support.ServerWebExchangeUtils;\nimport org.springframework.http.server.reactive.ServerHttpRequest;\nimport org.springframework.stereotype.Component;\nimport org.springframework.web.server.ServerWebExchange;\nimport org.springframework.web.server.WebFilter;\nimport org.springframework.web.server.WebFilterChain;\nimport reactor.core.publisher.Mono;", "import javax.annotation.Resource;\nimport java.util.Optional;", "@Component\npublic class SessionFilter implements WebFilter {\n // 所有模块的前缀\n private static final String[] PREFIX = new String[]{\"/setting\", \"/project\", \"/api\", \"/performance\", \"/track\", \"/workstation\", \"/ui\", \"/report\"};\n private static final String[] TO_SUB_SERVICE = new String[]{\"/license\", \"/system\", \"/resource\", \"/sso/callback/logout\", \"/sso/callback/cas/logout\"};\n private static final String PERFORMANCE_DOWNLOAD_PREFIX = \"/jmeter/\";\n private static final String API_DOWNLOAD_PREFIX = \"/api/jmeter/\";", " private static final String TRACK_IMAGE_PREFIX = \"/resource/md/get/url\";", "\n @Resource\n private DiscoveryClient discoveryClient;\n @Value(\"${spring.application.name}\")\n private String serviceName;", " @Override\n public Mono<Void> filter(final ServerWebExchange exchange, final WebFilterChain chain) {\n ServerHttpRequest req = exchange.getRequest();\n String path = req.getURI().getRawPath();", " // 转发 css js 到具体的模块\n if (path.startsWith(\"/css\") || path.startsWith(\"/js\")) {\n for (String prefix : PREFIX) {\n if (path.contains(prefix)) {\n return addPrefix(prefix, exchange, chain);\n }\n }\n }", " if (path.startsWith(TRACK_IMAGE_PREFIX)) {\n return addPrefix(\"/track\", exchange, chain);\n }", " // 有些url直接转到 sub-service\n for (String prefix : TO_SUB_SERVICE) {\n if (path.startsWith(prefix)) {\n Optional<String> svc = discoveryClient.getServices().stream().filter(s -> !StringUtils.equals(serviceName, s)).findAny();\n if (svc.isEmpty()) {\n break;\n }\n String service = svc.get();\n return addPrefix(\"/\" + service + \"/\", exchange, chain);\n }\n }", " // 从当前站点下载资源\n if (path.startsWith(PERFORMANCE_DOWNLOAD_PREFIX)) {\n return addPrefix(\"/performance\", exchange, chain);\n }", " if (path.startsWith(API_DOWNLOAD_PREFIX)) {\n return addPrefix(\"/api\", exchange, chain);\n }", " return chain.filter(exchange);\n }", " private Mono<Void> addPrefix(String prefix, final ServerWebExchange exchange, final WebFilterChain chain) {\n ServerHttpRequest req = exchange.getRequest();\n String path = req.getURI().getRawPath();\n ServerWebExchangeUtils.addOriginalRequestUrl(exchange, req.getURI());\n String newPath = prefix + path;\n ServerHttpRequest request = req.mutate().path(newPath).build();\n exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, request.getURI());\n return chain.filter(exchange.mutate().request(request).build());\n }\n}" ]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 113, 27, 22, 821, 90, 246, 337, 684, 42], "buggy_code_start_loc": [24, 109, 26, 18, 62, 90, 7, 9, 495, 3], "filenames": ["framework/gateway/src/main/java/io/metersphere/gateway/filter/SessionFilter.java", "framework/sdk-parent/xpack-interface/src/main/java/io/metersphere/xpack/track/issue/IssuesPlatform.java", "pom.xml", "test-track/backend/src/main/java/io/metersphere/controller/IssueProxyResourceController.java", "test-track/backend/src/main/java/io/metersphere/service/IssuesService.java", "test-track/backend/src/main/java/io/metersphere/service/PlatformPluginService.java", "test-track/backend/src/main/java/io/metersphere/service/issue/client/ZentaoClient.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/AbstractIssuePlatform.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/ZentaoPlatform.java", "test-track/backend/src/main/java/io/metersphere/service/wapper/IssueProxyResourceService.java"], "fixing_code_end_loc": [25, 113, 27, 23, 788, 92, 263, 343, 692, 42], "fixing_code_start_loc": [24, 109, 26, 18, 61, 91, 6, 8, 495, 3], "message": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:metersphere:metersphere:*:*:*:*:*:*:*:*", "matchCriteriaId": "218B4FEB-FDBE-46DB-A728-3CB89E37D5BA", "versionEndExcluding": "2.5.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds."}], "evaluatorComment": null, "id": "CVE-2022-23544", "lastModified": "2023-01-05T04:52:16.033", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.2, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 2.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-12-28T00:15:13.567", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/security/advisories/GHSA-vrv6-cg45-rmjj"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}, {"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, "type": "CWE-918"}
329
Determine whether the {function_name} code is vulnerable or not.
[ "package io.metersphere.gateway.filter;", "import org.apache.commons.lang3.StringUtils;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.cloud.client.discovery.DiscoveryClient;\nimport org.springframework.cloud.gateway.support.ServerWebExchangeUtils;\nimport org.springframework.http.server.reactive.ServerHttpRequest;\nimport org.springframework.stereotype.Component;\nimport org.springframework.web.server.ServerWebExchange;\nimport org.springframework.web.server.WebFilter;\nimport org.springframework.web.server.WebFilterChain;\nimport reactor.core.publisher.Mono;", "import javax.annotation.Resource;\nimport java.util.Optional;", "@Component\npublic class SessionFilter implements WebFilter {\n // 所有模块的前缀\n private static final String[] PREFIX = new String[]{\"/setting\", \"/project\", \"/api\", \"/performance\", \"/track\", \"/workstation\", \"/ui\", \"/report\"};\n private static final String[] TO_SUB_SERVICE = new String[]{\"/license\", \"/system\", \"/resource\", \"/sso/callback/logout\", \"/sso/callback/cas/logout\"};\n private static final String PERFORMANCE_DOWNLOAD_PREFIX = \"/jmeter/\";\n private static final String API_DOWNLOAD_PREFIX = \"/api/jmeter/\";", " private static final String TRACK_IMAGE_PREFIX = \"/resource/md/get/path\";", "\n @Resource\n private DiscoveryClient discoveryClient;\n @Value(\"${spring.application.name}\")\n private String serviceName;", " @Override\n public Mono<Void> filter(final ServerWebExchange exchange, final WebFilterChain chain) {\n ServerHttpRequest req = exchange.getRequest();\n String path = req.getURI().getRawPath();", " // 转发 css js 到具体的模块\n if (path.startsWith(\"/css\") || path.startsWith(\"/js\")) {\n for (String prefix : PREFIX) {\n if (path.contains(prefix)) {\n return addPrefix(prefix, exchange, chain);\n }\n }\n }", " if (path.startsWith(TRACK_IMAGE_PREFIX)) {\n return addPrefix(\"/track\", exchange, chain);\n }", " // 有些url直接转到 sub-service\n for (String prefix : TO_SUB_SERVICE) {\n if (path.startsWith(prefix)) {\n Optional<String> svc = discoveryClient.getServices().stream().filter(s -> !StringUtils.equals(serviceName, s)).findAny();\n if (svc.isEmpty()) {\n break;\n }\n String service = svc.get();\n return addPrefix(\"/\" + service + \"/\", exchange, chain);\n }\n }", " // 从当前站点下载资源\n if (path.startsWith(PERFORMANCE_DOWNLOAD_PREFIX)) {\n return addPrefix(\"/performance\", exchange, chain);\n }", " if (path.startsWith(API_DOWNLOAD_PREFIX)) {\n return addPrefix(\"/api\", exchange, chain);\n }", " return chain.filter(exchange);\n }", " private Mono<Void> addPrefix(String prefix, final ServerWebExchange exchange, final WebFilterChain chain) {\n ServerHttpRequest req = exchange.getRequest();\n String path = req.getURI().getRawPath();\n ServerWebExchangeUtils.addOriginalRequestUrl(exchange, req.getURI());\n String newPath = prefix + path;\n ServerHttpRequest request = req.mutate().path(newPath).build();\n exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, request.getURI());\n return chain.filter(exchange.mutate().request(request).build());\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 113, 27, 22, 821, 90, 246, 337, 684, 42], "buggy_code_start_loc": [24, 109, 26, 18, 62, 90, 7, 9, 495, 3], "filenames": ["framework/gateway/src/main/java/io/metersphere/gateway/filter/SessionFilter.java", "framework/sdk-parent/xpack-interface/src/main/java/io/metersphere/xpack/track/issue/IssuesPlatform.java", "pom.xml", "test-track/backend/src/main/java/io/metersphere/controller/IssueProxyResourceController.java", "test-track/backend/src/main/java/io/metersphere/service/IssuesService.java", "test-track/backend/src/main/java/io/metersphere/service/PlatformPluginService.java", "test-track/backend/src/main/java/io/metersphere/service/issue/client/ZentaoClient.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/AbstractIssuePlatform.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/ZentaoPlatform.java", "test-track/backend/src/main/java/io/metersphere/service/wapper/IssueProxyResourceService.java"], "fixing_code_end_loc": [25, 113, 27, 23, 788, 92, 263, 343, 692, 42], "fixing_code_start_loc": [24, 109, 26, 18, 61, 91, 6, 8, 495, 3], "message": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:metersphere:metersphere:*:*:*:*:*:*:*:*", "matchCriteriaId": "218B4FEB-FDBE-46DB-A728-3CB89E37D5BA", "versionEndExcluding": "2.5.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds."}], "evaluatorComment": null, "id": "CVE-2022-23544", "lastModified": "2023-01-05T04:52:16.033", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.2, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 2.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-12-28T00:15:13.567", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/security/advisories/GHSA-vrv6-cg45-rmjj"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}, {"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, "type": "CWE-918"}
329
Determine whether the {function_name} code is vulnerable or not.
[ "package io.metersphere.xpack.track.issue;", "import io.metersphere.base.domain.IssuesWithBLOBs;\nimport io.metersphere.base.domain.Project;\nimport io.metersphere.dto.UserDTO;\nimport io.metersphere.xpack.track.dto.*;\nimport io.metersphere.xpack.track.dto.request.IssuesRequest;\nimport io.metersphere.xpack.track.dto.request.IssuesUpdateRequest;\nimport org.springframework.http.ResponseEntity;", "import java.io.File;\nimport java.util.List;", "public interface IssuesPlatform {", " /**\n * 获取平台相关联的缺陷\n *\n * @return platform issues list\n */\n List<IssuesDao> getIssue(IssuesRequest request);", " /*获取平台相关需求*/\n List<DemandDTO> getDemandList(String projectId);", " /**\n * 添加缺陷到缺陷平台\n *\n * @param issuesRequest issueRequest\n */\n IssuesWithBLOBs addIssue(IssuesUpdateRequest issuesRequest);", " /**\n * 更新缺陷\n * @param request\n */\n void updateIssue(IssuesUpdateRequest request);", " /**\n * 删除缺陷平台缺陷\n *\n * @param id issue id\n */\n void deleteIssue(String id);", " /**\n * 测试平台联通性\n */\n void testAuth();", " /**\n * 用户信息测试\n */\n void userAuth(UserDTO.PlatformInfo userInfo);", " /**\n * 获取缺陷平台项目下的相关人员\n * @return platform user list\n */\n List<PlatformUser> getPlatformUser();", " /**\n * 同步缺陷最新变更\n * @param project\n * @param tapdIssues\n */\n void syncIssues(Project project, List<IssuesDao> tapdIssues);", " /**\n * 同步缺陷全量的缺陷\n * @param project\n */\n void syncAllIssues(Project project, IssueSyncRequest syncRequest);", " /**\n * 获取第三方平台缺陷模板\n * @return\n */\n IssueTemplateDao getThirdPartTemplate();", " /**\n * 检查其它平台关联的ID是否存在\n * @param relateId 其它平台在MS项目上关联的相关ID\n * @return Boolean\n */\n Boolean checkProjectExist(String relateId);", " /**\n * 更新缺陷关联关系\n * @param request\n */\n void removeIssueParentLink(IssuesUpdateRequest request);", " /**\n * 更新需求与缺陷关联关系\n *\n * @param testCase\n */\n void updateDemandIssueLink(EditTestCaseRequest testCase, Project project);", " /**\n * @param request\n * @param type add or edit\n */\n void updateDemandHyperLink(EditTestCaseRequest request, Project project, String type);", " /**\n * Get请求的代理", " * @param url", " * @return\n */", " ResponseEntity proxyForGet(String url, Class responseEntityClazz);", "\n /**\n * 同步MS缺陷附件到第三方平台\n * @param issuesRequest 平台参数\n * @param file 附件\n * @param syncType 同步操作类型: UPLOAD, DELETE\n */\n void syncIssuesAttachment(IssuesUpdateRequest issuesRequest, File file, AttachmentSyncType syncType);", "\n /**\n * 获取第三方平台的状态集合\n * @param issueKey\n * @return\n */\n List<PlatformStatusDTO> getTransitions(String issueKey);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 113, 27, 22, 821, 90, 246, 337, 684, 42], "buggy_code_start_loc": [24, 109, 26, 18, 62, 90, 7, 9, 495, 3], "filenames": ["framework/gateway/src/main/java/io/metersphere/gateway/filter/SessionFilter.java", "framework/sdk-parent/xpack-interface/src/main/java/io/metersphere/xpack/track/issue/IssuesPlatform.java", "pom.xml", "test-track/backend/src/main/java/io/metersphere/controller/IssueProxyResourceController.java", "test-track/backend/src/main/java/io/metersphere/service/IssuesService.java", "test-track/backend/src/main/java/io/metersphere/service/PlatformPluginService.java", "test-track/backend/src/main/java/io/metersphere/service/issue/client/ZentaoClient.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/AbstractIssuePlatform.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/ZentaoPlatform.java", "test-track/backend/src/main/java/io/metersphere/service/wapper/IssueProxyResourceService.java"], "fixing_code_end_loc": [25, 113, 27, 23, 788, 92, 263, 343, 692, 42], "fixing_code_start_loc": [24, 109, 26, 18, 61, 91, 6, 8, 495, 3], "message": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:metersphere:metersphere:*:*:*:*:*:*:*:*", "matchCriteriaId": "218B4FEB-FDBE-46DB-A728-3CB89E37D5BA", "versionEndExcluding": "2.5.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds."}], "evaluatorComment": null, "id": "CVE-2022-23544", "lastModified": "2023-01-05T04:52:16.033", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.2, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 2.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-12-28T00:15:13.567", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/security/advisories/GHSA-vrv6-cg45-rmjj"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}, {"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, "type": "CWE-918"}
329
Determine whether the {function_name} code is vulnerable or not.
[ "package io.metersphere.xpack.track.issue;", "import io.metersphere.base.domain.IssuesWithBLOBs;\nimport io.metersphere.base.domain.Project;\nimport io.metersphere.dto.UserDTO;\nimport io.metersphere.xpack.track.dto.*;\nimport io.metersphere.xpack.track.dto.request.IssuesRequest;\nimport io.metersphere.xpack.track.dto.request.IssuesUpdateRequest;\nimport org.springframework.http.ResponseEntity;", "import java.io.File;\nimport java.util.List;", "public interface IssuesPlatform {", " /**\n * 获取平台相关联的缺陷\n *\n * @return platform issues list\n */\n List<IssuesDao> getIssue(IssuesRequest request);", " /*获取平台相关需求*/\n List<DemandDTO> getDemandList(String projectId);", " /**\n * 添加缺陷到缺陷平台\n *\n * @param issuesRequest issueRequest\n */\n IssuesWithBLOBs addIssue(IssuesUpdateRequest issuesRequest);", " /**\n * 更新缺陷\n * @param request\n */\n void updateIssue(IssuesUpdateRequest request);", " /**\n * 删除缺陷平台缺陷\n *\n * @param id issue id\n */\n void deleteIssue(String id);", " /**\n * 测试平台联通性\n */\n void testAuth();", " /**\n * 用户信息测试\n */\n void userAuth(UserDTO.PlatformInfo userInfo);", " /**\n * 获取缺陷平台项目下的相关人员\n * @return platform user list\n */\n List<PlatformUser> getPlatformUser();", " /**\n * 同步缺陷最新变更\n * @param project\n * @param tapdIssues\n */\n void syncIssues(Project project, List<IssuesDao> tapdIssues);", " /**\n * 同步缺陷全量的缺陷\n * @param project\n */\n void syncAllIssues(Project project, IssueSyncRequest syncRequest);", " /**\n * 获取第三方平台缺陷模板\n * @return\n */\n IssueTemplateDao getThirdPartTemplate();", " /**\n * 检查其它平台关联的ID是否存在\n * @param relateId 其它平台在MS项目上关联的相关ID\n * @return Boolean\n */\n Boolean checkProjectExist(String relateId);", " /**\n * 更新缺陷关联关系\n * @param request\n */\n void removeIssueParentLink(IssuesUpdateRequest request);", " /**\n * 更新需求与缺陷关联关系\n *\n * @param testCase\n */\n void updateDemandIssueLink(EditTestCaseRequest testCase, Project project);", " /**\n * @param request\n * @param type add or edit\n */\n void updateDemandHyperLink(EditTestCaseRequest request, Project project, String type);", " /**\n * Get请求的代理", " * @param path", " * @return\n */", " ResponseEntity proxyForGet(String path, Class responseEntityClazz);", "\n /**\n * 同步MS缺陷附件到第三方平台\n * @param issuesRequest 平台参数\n * @param file 附件\n * @param syncType 同步操作类型: UPLOAD, DELETE\n */\n void syncIssuesAttachment(IssuesUpdateRequest issuesRequest, File file, AttachmentSyncType syncType);", "\n /**\n * 获取第三方平台的状态集合\n * @param issueKey\n * @return\n */\n List<PlatformStatusDTO> getTransitions(String issueKey);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 113, 27, 22, 821, 90, 246, 337, 684, 42], "buggy_code_start_loc": [24, 109, 26, 18, 62, 90, 7, 9, 495, 3], "filenames": ["framework/gateway/src/main/java/io/metersphere/gateway/filter/SessionFilter.java", "framework/sdk-parent/xpack-interface/src/main/java/io/metersphere/xpack/track/issue/IssuesPlatform.java", "pom.xml", "test-track/backend/src/main/java/io/metersphere/controller/IssueProxyResourceController.java", "test-track/backend/src/main/java/io/metersphere/service/IssuesService.java", "test-track/backend/src/main/java/io/metersphere/service/PlatformPluginService.java", "test-track/backend/src/main/java/io/metersphere/service/issue/client/ZentaoClient.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/AbstractIssuePlatform.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/ZentaoPlatform.java", "test-track/backend/src/main/java/io/metersphere/service/wapper/IssueProxyResourceService.java"], "fixing_code_end_loc": [25, 113, 27, 23, 788, 92, 263, 343, 692, 42], "fixing_code_start_loc": [24, 109, 26, 18, 61, 91, 6, 8, 495, 3], "message": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:metersphere:metersphere:*:*:*:*:*:*:*:*", "matchCriteriaId": "218B4FEB-FDBE-46DB-A728-3CB89E37D5BA", "versionEndExcluding": "2.5.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds."}], "evaluatorComment": null, "id": "CVE-2022-23544", "lastModified": "2023-01-05T04:52:16.033", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.2, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 2.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-12-28T00:15:13.567", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/security/advisories/GHSA-vrv6-cg45-rmjj"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}, {"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, "type": "CWE-918"}
329
Determine whether the {function_name} code is vulnerable or not.
[ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>", " <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>2.7.5</version>\n <relativePath/>\n </parent>", " <packaging>pom</packaging>\n <groupId>io.metersphere</groupId>\n <artifactId>metersphere</artifactId>\n <version>${revision}</version>\n <name>metersphere</name>\n <description>MeterSphere</description>", " <properties>\n <revision>main</revision>\n <java.version>11</java.version>\n <spring-cloud.version>2021.0.5</spring-cloud.version>\n <spring-security.version>5.7.5</spring-security.version>\n <dubbo.version>2.7.18</dubbo.version>", " <platform-plugin-sdk.version>1.0.0</platform-plugin-sdk.version>", " <flyway.version>7.15.0</flyway.version>\n <shiro.version>1.10.1</shiro.version>\n <mssql-jdbc.version>7.4.1.jre8</mssql-jdbc.version>\n <postgresql.version>42.3.8</postgresql.version>\n <java-websocket.version>1.5.3</java-websocket.version>\n <easyexcel.version>3.1.1</easyexcel.version>\n <dom4j.version>2.1.3</dom4j.version>\n <guava.version>31.1-jre</guava.version>\n <pagehelper.version>5.3.2</pagehelper.version>\n <metersphere-jmeter-functions.version>1.5</metersphere-jmeter-functions.version>\n <quartz-starter.version>1.0.6</quartz-starter.version>\n <redisson-starter.version>3.17.7</redisson-starter.version>\n <guice.version>5.1.0</guice.version>\n <mybatis-starter.version>2.3.0</mybatis-starter.version>\n <reflections.version>0.10.2</reflections.version>\n <bcprov-jdk15on.version>1.70</bcprov-jdk15on.version>\n <commons-io.version>2.11.0</commons-io.version>\n <commons-text.version>1.10.0</commons-text.version>\n <xstream.version>1.4.19</xstream.version>\n <xmlbeans.version>3.1.0</xmlbeans.version>\n <swagger-parser.version>2.1.5</swagger-parser.version>\n <rhino.version>1.7.14</rhino.version>\n <jsoup.version>1.15.3</jsoup.version>\n <commonmark.version>0.19.0</commonmark.version>\n <commons-compress.version>1.21</commons-compress.version>\n <htmlcleaner.version>2.26</htmlcleaner.version>\n <xmindjbehaveplugin.version>0.8</xmindjbehaveplugin.version>\n <metersphere-plugin-core.version>2.0</metersphere-plugin-core.version>\n <plexus.version>3.0.24</plexus.version>\n <common-random.version>1.0.14</common-random.version>\n <generex.version>1.0.2</generex.version>\n <json-lib.version>2.4</json-lib.version>\n <json-schema-validator.version>2.2.14</json-schema-validator.version>\n <xz.version>1.9</xz.version>\n <springdoc-openapi-ui.version>1.6.11</springdoc-openapi-ui.version>\n <flatten.version>1.2.7</flatten.version>\n <jmeter.version>5.5</jmeter.version>\n <codehaus-groovy.version>3.0.11</codehaus-groovy.version>\n <jython.version>2.7.3</jython.version>\n <docker-java.version>3.2.13</docker-java.version>\n <jmeter-plugins-webdriver.version>3.4.4</jmeter-plugins-webdriver.version>\n <oracle-database.version>19.7.0.0</oracle-database.version>\n <zookeeper.version>3.8.0</zookeeper.version>\n <commons-beanutils.version>1.9.4</commons-beanutils.version>\n <jmeter-plugins-dubbo.version>2.7.17</jmeter-plugins-dubbo.version>\n <hessian-lite.version>3.2.13</hessian-lite.version>\n <avro.version>1.11.1</avro.version>\n <dec.version>0.1.2</dec.version>\n <dingtalk-sdk.version>2.0.0</dingtalk-sdk.version>\n <org-json.version>20220924</org-json.version>\n <jmeter-plugins-dubbo.version>2.7.17</jmeter-plugins-dubbo.version>\n <nacos.version>1.4.4</nacos.version>\n <minio.version>8.4.5</minio.version>\n <hikaricp.version>5.0.1</hikaricp.version>\n <xmlgraphics-commons.version>2.7</xmlgraphics-commons.version>\n <commons-fileupload.version>1.4</commons-fileupload.version>\n <jgit.version>6.3.0.202209071007-r</jgit.version>\n <!-- frontend -->\n <frontend-maven-plugin.version>1.12.1</frontend-maven-plugin.version>\n <node.version>v16.10.0</node.version>\n <npm.version>8.12.1</npm.version>\n <!-- -->\n <skipAntRunForJenkins>false</skipAntRunForJenkins>\n </properties>", " <modules>\n <module>framework</module>\n <module>api-test</module>\n <module>performance-test</module>\n <module>project-management</module>\n <module>report-stat</module>\n <module>system-setting</module>\n <module>test-track</module>\n <module>workstation</module>\n </modules>", " <dependencies>\n <dependency>\n <groupId>org.springframework.cloud</groupId>\n <artifactId>spring-cloud-starter</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-configuration-processor</artifactId>\n <optional>true</optional>\n </dependency>\n <dependency>\n <groupId>org.projectlombok</groupId>\n <artifactId>lombok</artifactId>\n <optional>true</optional>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-test</artifactId>\n <scope>test</scope>\n </dependency>\n <dependency>\n <groupId>io.projectreactor</groupId>\n <artifactId>reactor-test</artifactId>\n <scope>test</scope>\n </dependency>\n <dependency>\n <groupId>org.springframework.kafka</groupId>\n <artifactId>spring-kafka-test</artifactId>\n <scope>test</scope>\n </dependency>\n </dependencies>", " <dependencyManagement>\n <dependencies>\n <dependency>\n <groupId>org.springframework.cloud</groupId>\n <artifactId>spring-cloud-dependencies</artifactId>\n <version>${spring-cloud.version}</version>\n <type>pom</type>\n <scope>import</scope>\n </dependency>\n </dependencies>\n </dependencyManagement>\n <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <configuration>\n <release>${java.version}</release>\n </configuration>\n </plugin>\n <plugin>\n <groupId>org.codehaus.mojo</groupId>\n <artifactId>flatten-maven-plugin</artifactId>\n <version>${flatten.version}</version>\n <configuration>\n <updatePomFile>true</updatePomFile>\n <flattenMode>resolveCiFriendliesOnly</flattenMode>\n </configuration>\n <executions>\n <execution>\n <id>flatten</id>\n <phase>process-resources</phase>\n <goals>\n <goal>flatten</goal>\n </goals>\n </execution>\n <execution>\n <id>flatten.clean</id>\n <phase>clean</phase>\n <goals>\n <goal>clean</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n </plugins>\n </build>\n</project>" ]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 113, 27, 22, 821, 90, 246, 337, 684, 42], "buggy_code_start_loc": [24, 109, 26, 18, 62, 90, 7, 9, 495, 3], "filenames": ["framework/gateway/src/main/java/io/metersphere/gateway/filter/SessionFilter.java", "framework/sdk-parent/xpack-interface/src/main/java/io/metersphere/xpack/track/issue/IssuesPlatform.java", "pom.xml", "test-track/backend/src/main/java/io/metersphere/controller/IssueProxyResourceController.java", "test-track/backend/src/main/java/io/metersphere/service/IssuesService.java", "test-track/backend/src/main/java/io/metersphere/service/PlatformPluginService.java", "test-track/backend/src/main/java/io/metersphere/service/issue/client/ZentaoClient.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/AbstractIssuePlatform.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/ZentaoPlatform.java", "test-track/backend/src/main/java/io/metersphere/service/wapper/IssueProxyResourceService.java"], "fixing_code_end_loc": [25, 113, 27, 23, 788, 92, 263, 343, 692, 42], "fixing_code_start_loc": [24, 109, 26, 18, 61, 91, 6, 8, 495, 3], "message": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:metersphere:metersphere:*:*:*:*:*:*:*:*", "matchCriteriaId": "218B4FEB-FDBE-46DB-A728-3CB89E37D5BA", "versionEndExcluding": "2.5.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds."}], "evaluatorComment": null, "id": "CVE-2022-23544", "lastModified": "2023-01-05T04:52:16.033", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.2, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 2.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-12-28T00:15:13.567", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/security/advisories/GHSA-vrv6-cg45-rmjj"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}, {"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, "type": "CWE-918"}
329
Determine whether the {function_name} code is vulnerable or not.
[ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>", " <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>2.7.5</version>\n <relativePath/>\n </parent>", " <packaging>pom</packaging>\n <groupId>io.metersphere</groupId>\n <artifactId>metersphere</artifactId>\n <version>${revision}</version>\n <name>metersphere</name>\n <description>MeterSphere</description>", " <properties>\n <revision>main</revision>\n <java.version>11</java.version>\n <spring-cloud.version>2021.0.5</spring-cloud.version>\n <spring-security.version>5.7.5</spring-security.version>\n <dubbo.version>2.7.18</dubbo.version>", " <platform-plugin-sdk.version>1.1.0</platform-plugin-sdk.version>", " <flyway.version>7.15.0</flyway.version>\n <shiro.version>1.10.1</shiro.version>\n <mssql-jdbc.version>7.4.1.jre8</mssql-jdbc.version>\n <postgresql.version>42.3.8</postgresql.version>\n <java-websocket.version>1.5.3</java-websocket.version>\n <easyexcel.version>3.1.1</easyexcel.version>\n <dom4j.version>2.1.3</dom4j.version>\n <guava.version>31.1-jre</guava.version>\n <pagehelper.version>5.3.2</pagehelper.version>\n <metersphere-jmeter-functions.version>1.5</metersphere-jmeter-functions.version>\n <quartz-starter.version>1.0.6</quartz-starter.version>\n <redisson-starter.version>3.17.7</redisson-starter.version>\n <guice.version>5.1.0</guice.version>\n <mybatis-starter.version>2.3.0</mybatis-starter.version>\n <reflections.version>0.10.2</reflections.version>\n <bcprov-jdk15on.version>1.70</bcprov-jdk15on.version>\n <commons-io.version>2.11.0</commons-io.version>\n <commons-text.version>1.10.0</commons-text.version>\n <xstream.version>1.4.19</xstream.version>\n <xmlbeans.version>3.1.0</xmlbeans.version>\n <swagger-parser.version>2.1.5</swagger-parser.version>\n <rhino.version>1.7.14</rhino.version>\n <jsoup.version>1.15.3</jsoup.version>\n <commonmark.version>0.19.0</commonmark.version>\n <commons-compress.version>1.21</commons-compress.version>\n <htmlcleaner.version>2.26</htmlcleaner.version>\n <xmindjbehaveplugin.version>0.8</xmindjbehaveplugin.version>\n <metersphere-plugin-core.version>2.0</metersphere-plugin-core.version>\n <plexus.version>3.0.24</plexus.version>\n <common-random.version>1.0.14</common-random.version>\n <generex.version>1.0.2</generex.version>\n <json-lib.version>2.4</json-lib.version>\n <json-schema-validator.version>2.2.14</json-schema-validator.version>\n <xz.version>1.9</xz.version>\n <springdoc-openapi-ui.version>1.6.11</springdoc-openapi-ui.version>\n <flatten.version>1.2.7</flatten.version>\n <jmeter.version>5.5</jmeter.version>\n <codehaus-groovy.version>3.0.11</codehaus-groovy.version>\n <jython.version>2.7.3</jython.version>\n <docker-java.version>3.2.13</docker-java.version>\n <jmeter-plugins-webdriver.version>3.4.4</jmeter-plugins-webdriver.version>\n <oracle-database.version>19.7.0.0</oracle-database.version>\n <zookeeper.version>3.8.0</zookeeper.version>\n <commons-beanutils.version>1.9.4</commons-beanutils.version>\n <jmeter-plugins-dubbo.version>2.7.17</jmeter-plugins-dubbo.version>\n <hessian-lite.version>3.2.13</hessian-lite.version>\n <avro.version>1.11.1</avro.version>\n <dec.version>0.1.2</dec.version>\n <dingtalk-sdk.version>2.0.0</dingtalk-sdk.version>\n <org-json.version>20220924</org-json.version>\n <jmeter-plugins-dubbo.version>2.7.17</jmeter-plugins-dubbo.version>\n <nacos.version>1.4.4</nacos.version>\n <minio.version>8.4.5</minio.version>\n <hikaricp.version>5.0.1</hikaricp.version>\n <xmlgraphics-commons.version>2.7</xmlgraphics-commons.version>\n <commons-fileupload.version>1.4</commons-fileupload.version>\n <jgit.version>6.3.0.202209071007-r</jgit.version>\n <!-- frontend -->\n <frontend-maven-plugin.version>1.12.1</frontend-maven-plugin.version>\n <node.version>v16.10.0</node.version>\n <npm.version>8.12.1</npm.version>\n <!-- -->\n <skipAntRunForJenkins>false</skipAntRunForJenkins>\n </properties>", " <modules>\n <module>framework</module>\n <module>api-test</module>\n <module>performance-test</module>\n <module>project-management</module>\n <module>report-stat</module>\n <module>system-setting</module>\n <module>test-track</module>\n <module>workstation</module>\n </modules>", " <dependencies>\n <dependency>\n <groupId>org.springframework.cloud</groupId>\n <artifactId>spring-cloud-starter</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-configuration-processor</artifactId>\n <optional>true</optional>\n </dependency>\n <dependency>\n <groupId>org.projectlombok</groupId>\n <artifactId>lombok</artifactId>\n <optional>true</optional>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-test</artifactId>\n <scope>test</scope>\n </dependency>\n <dependency>\n <groupId>io.projectreactor</groupId>\n <artifactId>reactor-test</artifactId>\n <scope>test</scope>\n </dependency>\n <dependency>\n <groupId>org.springframework.kafka</groupId>\n <artifactId>spring-kafka-test</artifactId>\n <scope>test</scope>\n </dependency>\n </dependencies>", " <dependencyManagement>\n <dependencies>\n <dependency>\n <groupId>org.springframework.cloud</groupId>\n <artifactId>spring-cloud-dependencies</artifactId>\n <version>${spring-cloud.version}</version>\n <type>pom</type>\n <scope>import</scope>\n </dependency>\n </dependencies>\n </dependencyManagement>\n <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <configuration>\n <release>${java.version}</release>\n </configuration>\n </plugin>\n <plugin>\n <groupId>org.codehaus.mojo</groupId>\n <artifactId>flatten-maven-plugin</artifactId>\n <version>${flatten.version}</version>\n <configuration>\n <updatePomFile>true</updatePomFile>\n <flattenMode>resolveCiFriendliesOnly</flattenMode>\n </configuration>\n <executions>\n <execution>\n <id>flatten</id>\n <phase>process-resources</phase>\n <goals>\n <goal>flatten</goal>\n </goals>\n </execution>\n <execution>\n <id>flatten.clean</id>\n <phase>clean</phase>\n <goals>\n <goal>clean</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n </plugins>\n </build>\n</project>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 113, 27, 22, 821, 90, 246, 337, 684, 42], "buggy_code_start_loc": [24, 109, 26, 18, 62, 90, 7, 9, 495, 3], "filenames": ["framework/gateway/src/main/java/io/metersphere/gateway/filter/SessionFilter.java", "framework/sdk-parent/xpack-interface/src/main/java/io/metersphere/xpack/track/issue/IssuesPlatform.java", "pom.xml", "test-track/backend/src/main/java/io/metersphere/controller/IssueProxyResourceController.java", "test-track/backend/src/main/java/io/metersphere/service/IssuesService.java", "test-track/backend/src/main/java/io/metersphere/service/PlatformPluginService.java", "test-track/backend/src/main/java/io/metersphere/service/issue/client/ZentaoClient.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/AbstractIssuePlatform.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/ZentaoPlatform.java", "test-track/backend/src/main/java/io/metersphere/service/wapper/IssueProxyResourceService.java"], "fixing_code_end_loc": [25, 113, 27, 23, 788, 92, 263, 343, 692, 42], "fixing_code_start_loc": [24, 109, 26, 18, 61, 91, 6, 8, 495, 3], "message": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:metersphere:metersphere:*:*:*:*:*:*:*:*", "matchCriteriaId": "218B4FEB-FDBE-46DB-A728-3CB89E37D5BA", "versionEndExcluding": "2.5.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds."}], "evaluatorComment": null, "id": "CVE-2022-23544", "lastModified": "2023-01-05T04:52:16.033", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.2, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 2.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-12-28T00:15:13.567", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/security/advisories/GHSA-vrv6-cg45-rmjj"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}, {"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, "type": "CWE-918"}
329
Determine whether the {function_name} code is vulnerable or not.
[ "package io.metersphere.controller;", "import io.metersphere.service.wapper.IssueProxyResourceService;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.RestController;", "import javax.annotation.Resource;", "@RestController\n@RequestMapping(value = \"/resource\")\npublic class IssueProxyResourceController {\n @Resource\n IssueProxyResourceService issueProxyResourceService;\n", " @GetMapping(value = \"/md/get/url\")\n public ResponseEntity<byte[]> getFileByUrl(@RequestParam (\"url\") String url, @RequestParam (value = \"platform\", required = false) String platform,\n @RequestParam (value = \"workspace_id\", required = false) String workspaceId) {\n return issueProxyResourceService.getMdImageByUrl(url, platform, workspaceId);", " }\n}" ]
[ 1, 1, 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 113, 27, 22, 821, 90, 246, 337, 684, 42], "buggy_code_start_loc": [24, 109, 26, 18, 62, 90, 7, 9, 495, 3], "filenames": ["framework/gateway/src/main/java/io/metersphere/gateway/filter/SessionFilter.java", "framework/sdk-parent/xpack-interface/src/main/java/io/metersphere/xpack/track/issue/IssuesPlatform.java", "pom.xml", "test-track/backend/src/main/java/io/metersphere/controller/IssueProxyResourceController.java", "test-track/backend/src/main/java/io/metersphere/service/IssuesService.java", "test-track/backend/src/main/java/io/metersphere/service/PlatformPluginService.java", "test-track/backend/src/main/java/io/metersphere/service/issue/client/ZentaoClient.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/AbstractIssuePlatform.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/ZentaoPlatform.java", "test-track/backend/src/main/java/io/metersphere/service/wapper/IssueProxyResourceService.java"], "fixing_code_end_loc": [25, 113, 27, 23, 788, 92, 263, 343, 692, 42], "fixing_code_start_loc": [24, 109, 26, 18, 61, 91, 6, 8, 495, 3], "message": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:metersphere:metersphere:*:*:*:*:*:*:*:*", "matchCriteriaId": "218B4FEB-FDBE-46DB-A728-3CB89E37D5BA", "versionEndExcluding": "2.5.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds."}], "evaluatorComment": null, "id": "CVE-2022-23544", "lastModified": "2023-01-05T04:52:16.033", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.2, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 2.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-12-28T00:15:13.567", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/security/advisories/GHSA-vrv6-cg45-rmjj"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}, {"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, "type": "CWE-918"}
329
Determine whether the {function_name} code is vulnerable or not.
[ "package io.metersphere.controller;", "import io.metersphere.service.wapper.IssueProxyResourceService;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.RestController;", "import javax.annotation.Resource;", "@RestController\n@RequestMapping(value = \"/resource\")\npublic class IssueProxyResourceController {\n @Resource\n IssueProxyResourceService issueProxyResourceService;\n", " @GetMapping(value = \"/md/get/path\")\n public ResponseEntity<byte[]> getFileByPath(@RequestParam (\"path\") String path,\n @RequestParam (value = \"platform\") String platform,\n @RequestParam (value = \"workspaceId\") String workspaceId) {\n return issueProxyResourceService.getMdImageByPath(path, platform, workspaceId);", " }\n}" ]
[ 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 113, 27, 22, 821, 90, 246, 337, 684, 42], "buggy_code_start_loc": [24, 109, 26, 18, 62, 90, 7, 9, 495, 3], "filenames": ["framework/gateway/src/main/java/io/metersphere/gateway/filter/SessionFilter.java", "framework/sdk-parent/xpack-interface/src/main/java/io/metersphere/xpack/track/issue/IssuesPlatform.java", "pom.xml", "test-track/backend/src/main/java/io/metersphere/controller/IssueProxyResourceController.java", "test-track/backend/src/main/java/io/metersphere/service/IssuesService.java", "test-track/backend/src/main/java/io/metersphere/service/PlatformPluginService.java", "test-track/backend/src/main/java/io/metersphere/service/issue/client/ZentaoClient.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/AbstractIssuePlatform.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/ZentaoPlatform.java", "test-track/backend/src/main/java/io/metersphere/service/wapper/IssueProxyResourceService.java"], "fixing_code_end_loc": [25, 113, 27, 23, 788, 92, 263, 343, 692, 42], "fixing_code_start_loc": [24, 109, 26, 18, 61, 91, 6, 8, 495, 3], "message": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:metersphere:metersphere:*:*:*:*:*:*:*:*", "matchCriteriaId": "218B4FEB-FDBE-46DB-A728-3CB89E37D5BA", "versionEndExcluding": "2.5.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds."}], "evaluatorComment": null, "id": "CVE-2022-23544", "lastModified": "2023-01-05T04:52:16.033", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.2, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 2.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-12-28T00:15:13.567", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/security/advisories/GHSA-vrv6-cg45-rmjj"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}, {"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, "type": "CWE-918"}
329
Determine whether the {function_name} code is vulnerable or not.
[ "package io.metersphere.service;", "import com.alibaba.excel.EasyExcelFactory;\nimport com.alibaba.excel.util.DateUtils;\nimport com.alibaba.fastjson.JSONArray;\nimport com.alibaba.fastjson.JSONObject;\nimport com.github.pagehelper.Page;\nimport com.github.pagehelper.PageHelper;\nimport io.metersphere.base.domain.*;\nimport io.metersphere.base.mapper.*;\nimport io.metersphere.base.mapper.ext.ExtIssueCommentMapper;\nimport io.metersphere.base.mapper.ext.ExtIssuesMapper;\nimport io.metersphere.commons.constants.*;\nimport io.metersphere.commons.exception.MSException;\nimport io.metersphere.commons.utils.*;\nimport io.metersphere.constants.AttachmentType;\nimport io.metersphere.constants.IssueStatus;\nimport io.metersphere.constants.SystemCustomField;\nimport io.metersphere.dto.*;\nimport io.metersphere.excel.constants.IssueExportHeadField;\nimport io.metersphere.excel.domain.ExcelErrData;\nimport io.metersphere.excel.domain.ExcelResponse;\nimport io.metersphere.excel.domain.IssueExcelData;\nimport io.metersphere.excel.domain.IssueExcelDataFactory;\nimport io.metersphere.excel.handler.IssueTemplateHeadWriteHandler;\nimport io.metersphere.excel.listener.IssueExcelListener;\nimport io.metersphere.excel.utils.EasyExcelExporter;\nimport io.metersphere.i18n.Translator;\nimport io.metersphere.log.utils.ReflexObjectUtil;\nimport io.metersphere.log.vo.DetailColumn;\nimport io.metersphere.log.vo.OperatingLogDetails;\nimport io.metersphere.log.vo.track.TestPlanReference;\nimport io.metersphere.plan.dto.PlanReportIssueDTO;\nimport io.metersphere.plan.dto.TestCaseReportStatusResultDTO;\nimport io.metersphere.plan.dto.TestPlanSimpleReportDTO;\nimport io.metersphere.plan.service.TestPlanService;\nimport io.metersphere.plan.service.TestPlanTestCaseService;\nimport io.metersphere.plan.utils.TestPlanStatusCalculator;\nimport io.metersphere.platform.api.Platform;\nimport io.metersphere.platform.domain.*;\nimport io.metersphere.platform.domain.PlatformAttachment;\nimport io.metersphere.request.IntegrationRequest;\nimport io.metersphere.xpack.track.dto.AttachmentRequest;\nimport io.metersphere.request.issues.IssueExportRequest;\nimport io.metersphere.request.issues.IssueImportRequest;\nimport io.metersphere.request.issues.PlatformIssueTypeRequest;\nimport io.metersphere.request.testcase.AuthUserIssueRequest;\nimport io.metersphere.request.testcase.IssuesCountRequest;\nimport io.metersphere.service.issue.domain.zentao.ZentaoBuild;\nimport io.metersphere.service.issue.platform.*;\nimport io.metersphere.service.remote.project.TrackCustomFieldTemplateService;\nimport io.metersphere.service.remote.project.TrackIssueTemplateService;\nimport io.metersphere.service.wapper.TrackProjectService;\nimport io.metersphere.service.wapper.UserService;\nimport io.metersphere.utils.DistinctKeyUtil;\nimport io.metersphere.xpack.track.dto.PlatformStatusDTO;\nimport io.metersphere.xpack.track.dto.PlatformUser;\nimport io.metersphere.xpack.track.dto.*;\nimport io.metersphere.xpack.track.dto.request.IssuesRequest;\nimport io.metersphere.xpack.track.dto.request.IssuesUpdateRequest;\nimport io.metersphere.xpack.track.issue.IssuesPlatform;", "import jodd.util.CollectionUtil;", "import io.metersphere.xpack.track.service.XpackIssueService;\nimport org.apache.commons.collections.CollectionUtils;\nimport org.apache.commons.collections.MapUtils;\nimport org.apache.commons.lang3.BooleanUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.ibatis.session.ExecutorType;\nimport org.apache.ibatis.session.SqlSession;\nimport org.apache.ibatis.session.SqlSessionFactory;\nimport org.mybatis.spring.SqlSessionUtils;\nimport org.springframework.context.annotation.Lazy;\nimport org.springframework.data.redis.core.StringRedisTemplate;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\nimport org.springframework.web.multipart.MultipartFile;", "import javax.annotation.Resource;\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.*;\nimport java.util.concurrent.TimeUnit;\nimport java.util.function.BiConsumer;\nimport java.util.stream.Collectors;", "@Service\n@Transactional(rollbackFor = Exception.class)\npublic class IssuesService {", " @Resource\n private BaseIntegrationService baseIntegrationService;\n @Resource\n private TrackProjectService trackProjectService;\n @Resource\n private BaseUserService baseUserService;\n @Resource\n private BaseProjectService baseProjectService;\n @Resource\n private TestPlanService testPlanService;\n @Lazy\n @Resource\n private io.metersphere.service.TestCaseService testCaseService;\n @Resource\n private IssuesMapper issuesMapper;\n @Resource\n private TestCaseIssuesMapper testCaseIssuesMapper;\n @Resource\n private ExtIssuesMapper extIssuesMapper;\n @Resource\n private TrackCustomFieldTemplateService trackCustomFieldTemplateService;\n @Resource\n private BaseCustomFieldService baseCustomFieldService;\n @Resource\n private TrackIssueTemplateService trackIssueTemplateService;\n @Resource\n private TestCaseIssueService testCaseIssueService;\n @Lazy\n @Resource\n private TestPlanTestCaseService testPlanTestCaseService;\n @Resource\n private IssueFollowMapper issueFollowMapper;\n @Resource\n private TestPlanTestCaseMapper testPlanTestCaseMapper;\n @Resource\n private CustomFieldIssuesService customFieldIssuesService;\n @Resource\n private CustomFieldIssuesMapper customFieldIssuesMapper;\n @Resource\n StringRedisTemplate stringRedisTemplate;\n @Resource\n private AttachmentService attachmentService;\n @Resource\n private ProjectMapper projectMapper;\n @Resource\n SqlSessionFactory sqlSessionFactory;\n @Resource\n private FileMetadataMapper fileMetadataMapper;\n @Resource\n private ExtIssueCommentMapper extIssueCommentMapper;\n @Resource\n private PlatformPluginService platformPluginService;\n @Resource\n private UserService userService;", " private static final String SYNC_THIRD_PARTY_ISSUES_KEY = \"ISSUE:SYNC\";", " public void testAuth(String workspaceId, String platform) {\n IssuesRequest issuesRequest = new IssuesRequest();\n issuesRequest.setWorkspaceId(workspaceId);\n IssuesPlatform abstractPlatform = IssueFactory.createPlatform(platform, issuesRequest);\n abstractPlatform.testAuth();\n }", "\n public IssuesWithBLOBs addIssues(IssuesUpdateRequest issuesRequest, List<MultipartFile> files) {\n Project project = baseProjectService.getProjectById(issuesRequest.getProjectId());\n IssuesWithBLOBs issues = null;\n if (PlatformPluginService.isPluginPlatform(project.getPlatform())) {\n PlatformIssuesUpdateRequest platformIssuesUpdateRequest =\n JSON.parseObject(JSON.toJSONString(issuesRequest), PlatformIssuesUpdateRequest.class);\n List<PlatformCustomFieldItemDTO> customFieldItemDTOS =\n JSON.parseArray(JSON.toJSONString(issuesRequest.getRequestFields()), PlatformCustomFieldItemDTO.class);\n platformIssuesUpdateRequest.setCustomFieldList(customFieldItemDTOS); // todo 全部插件化后去掉\n platformIssuesUpdateRequest.setUserPlatformUserConfig(userService.getCurrentPlatformInfoStr(SessionUtils.getCurrentWorkspaceId()));\n platformIssuesUpdateRequest.setProjectConfig(PlatformPluginService.getCompatibleProjectConfig(project));", " issues = platformPluginService.getPlatform(project.getPlatform())\n .addIssue(platformIssuesUpdateRequest);", " insertIssues(issues);\n issuesRequest.setId(issues.getId());\n issues.setPlatform(project.getPlatform());\n // 用例与第三方缺陷平台中的缺陷关联\n handleTestCaseIssues(issuesRequest);", " // 如果是复制新增, 同步MS附件到Jira\n if (StringUtils.isNotEmpty(issuesRequest.getCopyIssueId())) {\n AttachmentRequest attachmentRequest = new AttachmentRequest();\n attachmentRequest.setBelongId(issuesRequest.getCopyIssueId());\n attachmentRequest.setBelongType(AttachmentType.ISSUE.type());\n List<String> attachmentIds = attachmentService.getAttachmentIdsByParam(attachmentRequest);\n if (CollectionUtils.isNotEmpty(attachmentIds)) {\n for (String attachmentId : attachmentIds) {\n FileAttachmentMetadata fileAttachmentMetadata = attachmentService.getFileAttachmentMetadataByFileId(attachmentId);\n File file = new File(fileAttachmentMetadata.getFilePath() + \"/\" + fileAttachmentMetadata.getName());\n attachmentService.syncIssuesAttachment(issues, file, AttachmentSyncType.UPLOAD);\n }\n }\n }\n } else {\n List<IssuesPlatform> platformList = getAddPlatforms(issuesRequest);\n for (IssuesPlatform platform : platformList) {\n issues = platform.addIssue(issuesRequest);\n }\n }", " if (issuesRequest.getIsPlanEdit()) {\n issuesRequest.getAddResourceIds().forEach(l -> {\n testCaseIssueService.updateIssuesCount(l);\n });\n }\n String issuesId = issues.getId();\n saveFollows(issuesId, issuesRequest.getFollows());\n customFieldIssuesService.addFields(issuesId, issuesRequest.getAddFields());\n customFieldIssuesService.editFields(issuesId, issuesRequest.getEditFields());\n if (StringUtils.isNotEmpty(issuesRequest.getCopyIssueId())) {\n final String platformId = issues.getPlatformId();\n // 复制新增, 同步缺陷的MS附件\n AttachmentRequest attachmentRequest = new AttachmentRequest();\n attachmentRequest.setCopyBelongId(issuesRequest.getCopyIssueId());\n attachmentRequest.setBelongId(issues.getId());\n attachmentRequest.setBelongType(AttachmentType.ISSUE.type());\n attachmentService.copyAttachment(attachmentRequest);", " // MS附件同步到其他平台, Jira, Zentao已经在创建缺陷时处理, AzureDevops单独处理\n if (StringUtils.equals(issuesRequest.getPlatform(), IssuesManagePlatform.AzureDevops.toString())) {\n AttachmentRequest request = new AttachmentRequest();\n request.setBelongId(issuesRequest.getCopyIssueId());\n request.setBelongType(AttachmentType.ISSUE.type());\n uploadAzureCopyAttachment(request, issuesRequest.getPlatform(), platformId);\n }\n } else {\n final String issueId = issues.getId();\n final String platform = issues.getPlatform();\n // 新增, 需保存并同步所有待上传的附件\n if (CollectionUtils.isNotEmpty(files)) {\n files.forEach(file -> {\n AttachmentRequest attachmentRequest = new AttachmentRequest();\n attachmentRequest.setBelongId(issueId);\n attachmentRequest.setBelongType(AttachmentType.ISSUE.type());\n attachmentService.uploadAttachment(attachmentRequest, file);\n });\n }\n // 处理待关联的文件附件, 生成关联记录, 并同步至第三方平台\n if (CollectionUtils.isNotEmpty(issuesRequest.getRelateFileMetaIds())) {\n SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);\n FileAssociationMapper associationBatchMapper = sqlSession.getMapper(FileAssociationMapper.class);\n AttachmentModuleRelationMapper attachmentModuleRelationBatchMapper = sqlSession.getMapper(AttachmentModuleRelationMapper.class);\n FileAttachmentMetadataMapper fileAttachmentMetadataBatchMapper = sqlSession.getMapper(FileAttachmentMetadataMapper.class);\n issuesRequest.getRelateFileMetaIds().forEach(filemetaId -> {\n FileMetadata fileMetadata = fileMetadataMapper.selectByPrimaryKey(filemetaId);\n FileAssociation fileAssociation = new FileAssociation();\n fileAssociation.setId(UUID.randomUUID().toString());\n fileAssociation.setFileMetadataId(filemetaId);\n fileAssociation.setFileType(fileMetadata.getType());\n fileAssociation.setType(FileAssociationType.ISSUE.name());\n fileAssociation.setProjectId(fileMetadata.getProjectId());\n fileAssociation.setSourceItemId(filemetaId);\n fileAssociation.setSourceId(issueId);\n associationBatchMapper.insert(fileAssociation);\n AttachmentModuleRelation relation = new AttachmentModuleRelation();\n relation.setRelationId(issueId);\n relation.setRelationType(AttachmentType.ISSUE.type());\n relation.setFileMetadataRefId(fileAssociation.getId());\n relation.setAttachmentId(UUID.randomUUID().toString());\n attachmentModuleRelationBatchMapper.insert(relation);\n FileAttachmentMetadata fileAttachmentMetadata = new FileAttachmentMetadata();\n BeanUtils.copyBean(fileAttachmentMetadata, fileMetadata);\n fileAttachmentMetadata.setId(relation.getAttachmentId());\n fileAttachmentMetadata.setCreator(fileMetadata.getCreateUser() == null ? StringUtils.EMPTY : fileMetadata.getCreateUser());\n fileAttachmentMetadata.setFilePath(fileMetadata.getPath() == null ? StringUtils.EMPTY : fileMetadata.getPath());\n fileAttachmentMetadataBatchMapper.insert(fileAttachmentMetadata);\n // 下载文件管理文件, 同步到第三方平台\n File refFile = attachmentService.downloadMetadataFile(filemetaId, fileMetadata.getName());\n if (PlatformPluginService.isPluginPlatform(platform)) {\n issuesRequest.setPlatform(platform);\n attachmentService.syncIssuesAttachment(issuesRequest, refFile, AttachmentSyncType.UPLOAD);\n } else {\n IssuesRequest addIssueRequest = new IssuesRequest();\n addIssueRequest.setWorkspaceId(SessionUtils.getCurrentWorkspaceId());\n addIssueRequest.setProjectId(SessionUtils.getCurrentProjectId());\n Objects.requireNonNull(IssueFactory.createPlatform(platform, addIssueRequest))\n .syncIssuesAttachment(issuesRequest, refFile, AttachmentSyncType.UPLOAD);\n }\n FileUtils.deleteFile(FileUtils.ATTACHMENT_TMP_DIR + File.separator + fileMetadata.getName());\n });\n sqlSession.flushStatements();\n if (sqlSession != null && sqlSessionFactory != null) {\n SqlSessionUtils.closeSqlSession(sqlSession, sqlSessionFactory);\n }\n }\n }\n return getIssue(issues.getId());\n }", " protected IssuesWithBLOBs insertIssues(IssuesWithBLOBs issues) {\n if (StringUtils.isBlank(issues.getId())) {\n issues.setId(UUID.randomUUID().toString());\n }\n issues.setCreateTime(System.currentTimeMillis());\n issues.setUpdateTime(System.currentTimeMillis());\n issues.setNum(getNextNum(issues.getProjectId()));\n issues.setCreator(SessionUtils.getUserId());\n issuesMapper.insert(issues);\n return issues;\n }", " protected int getNextNum(String projectId) {\n Issues issue = extIssuesMapper.getNextNum(projectId);\n if (issue == null || issue.getNum() == null) {\n return 100001;\n } else {\n return Optional.of(issue.getNum() + 1).orElse(100001);\n }\n }", " public void handleTestCaseIssues(IssuesUpdateRequest issuesRequest) {\n String issuesId = issuesRequest.getId();\n List<String> deleteCaseIds = issuesRequest.getDeleteResourceIds();", " if (!org.springframework.util.CollectionUtils.isEmpty(deleteCaseIds)) {\n TestCaseIssuesExample example = new TestCaseIssuesExample();\n example.createCriteria()\n .andResourceIdIn(deleteCaseIds)\n .andIssuesIdEqualTo(issuesId);\n // 测试计划的用例 deleteCaseIds 是空的, 不会进到这里\n example.or(\n example.createCriteria()\n .andRefIdIn(deleteCaseIds)\n .andIssuesIdEqualTo(issuesId)\n );\n testCaseIssuesMapper.deleteByExample(example);\n }", " List<String> addCaseIds = issuesRequest.getAddResourceIds();", " if (!org.springframework.util.CollectionUtils.isEmpty(addCaseIds)) {\n if (issuesRequest.getIsPlanEdit()) {\n addCaseIds.forEach(caseId -> {\n testCaseIssueService.add(issuesId, caseId, issuesRequest.getRefId(), IssueRefType.PLAN_FUNCTIONAL.name());\n testCaseIssueService.updateIssuesCount(caseId);\n });\n } else {\n addCaseIds.forEach(caseId -> testCaseIssueService.add(issuesId, caseId, null, IssueRefType.FUNCTIONAL.name()));\n }\n }\n }", " public IssuesWithBLOBs updateIssues(IssuesUpdateRequest issuesRequest) {\n PlatformIssuesUpdateRequest platformIssuesUpdateRequest = JSON.parseObject(JSON.toJSONString(issuesRequest), PlatformIssuesUpdateRequest.class);\n Project project = baseProjectService.getProjectById(issuesRequest.getProjectId());\n if (PlatformPluginService.isPluginPlatform(project.getPlatform())) {", " Platform platform = platformPluginService.getPlatform(project.getPlatform());", " if (platform.isAttachmentUploadSupport()) {\n AttachmentRequest attachmentRequest = new AttachmentRequest();\n attachmentRequest.setBelongId(issuesRequest.getId());\n attachmentRequest.setBelongType(AttachmentType.ISSUE.type());\n List<FileAttachmentMetadata> fileAttachmentMetadata = attachmentService.listMetadata(attachmentRequest);\n Set<String> msAttachmentNames = fileAttachmentMetadata.stream()\n .map(FileAttachmentMetadata::getName)\n .collect(Collectors.toSet());\n // 获得缺陷MS附件名称\n platformIssuesUpdateRequest.setMsAttachmentNames(msAttachmentNames);\n }", " List<PlatformCustomFieldItemDTO> customFieldItemDTOS = JSON.parseArray(JSON.toJSONString(issuesRequest.getRequestFields()), PlatformCustomFieldItemDTO.class);\n platformIssuesUpdateRequest.setCustomFieldList(customFieldItemDTOS); // todo 全部插件化后去掉\n platformIssuesUpdateRequest.setUserPlatformUserConfig(userService.getCurrentPlatformInfoStr(SessionUtils.getCurrentWorkspaceId()));\n platformIssuesUpdateRequest.setProjectConfig(PlatformPluginService.getCompatibleProjectConfig(project));\n IssuesWithBLOBs issue = platformPluginService.getPlatform(project.getPlatform())\n .updateIssue(platformIssuesUpdateRequest);", " issue.setUpdateTime(System.currentTimeMillis());\n issuesMapper.updateByPrimaryKeySelective(issue);\n handleTestCaseIssues(issuesRequest);\n } else {\n List<IssuesPlatform> platformList = getUpdatePlatforms(issuesRequest);\n platformList.forEach(platform -> {\n platform.updateIssue(issuesRequest);\n });\n }", " customFieldIssuesService.editFields(issuesRequest.getId(), issuesRequest.getEditFields());\n customFieldIssuesService.addFields(issuesRequest.getId(), issuesRequest.getAddFields());", " return getIssue(issuesRequest.getId());\n }", " public void saveFollows(String issueId, List<String> follows) {\n IssueFollowExample example = new IssueFollowExample();\n example.createCriteria().andIssueIdEqualTo(issueId);\n issueFollowMapper.deleteByExample(example);\n if (!CollectionUtils.isEmpty(follows)) {\n for (String follow : follows) {\n IssueFollow issueFollow = new IssueFollow();\n issueFollow.setIssueId(issueId);\n issueFollow.setFollowId(follow);\n issueFollowMapper.insert(issueFollow);\n }\n }\n }", " public List<IssuesPlatform> getAddPlatforms(IssuesUpdateRequest updateRequest) {\n List<String> platforms = new ArrayList<>();\n // 缺陷管理关联\n platforms.add(getPlatform(updateRequest.getProjectId()));", " if (CollectionUtils.isEmpty(platforms)) {\n platforms.add(IssuesManagePlatform.Local.toString());\n }\n IssuesRequest issuesRequest = new IssuesRequest();\n BeanUtils.copyBean(issuesRequest, updateRequest);\n return IssueFactory.createPlatforms(platforms, issuesRequest);\n }", " public List<IssuesPlatform> getUpdatePlatforms(IssuesUpdateRequest updateRequest) {\n String id = updateRequest.getId();\n IssuesWithBLOBs issuesWithBLOBs = issuesMapper.selectByPrimaryKey(id);\n String platform = issuesWithBLOBs.getPlatform();\n List<String> platforms = new ArrayList<>();\n if (StringUtils.isBlank(platform)) {\n platforms.add(IssuesManagePlatform.Local.toString());\n } else {\n platforms.add(platform);\n }\n IssuesRequest issuesRequest = new IssuesRequest();\n BeanUtils.copyBean(issuesRequest, updateRequest);\n return IssueFactory.createPlatforms(platforms, issuesRequest);\n }", " public List<IssuesDao> getIssues(String caseResourceId, String refType) {\n IssuesRequest issueRequest = new IssuesRequest();\n issueRequest.setCaseResourceId(caseResourceId);\n ServiceUtils.getDefaultOrder(issueRequest.getOrders());\n issueRequest.setRefType(refType);\n List<IssuesDao> issues = extIssuesMapper.getIssuesByCaseId(issueRequest);\n handleCustomFieldStatus(issues);\n return DistinctKeyUtil.distinctByKey(issues, IssuesDao::getId);\n }", " private void handleCustomFieldStatus(List<IssuesDao> issues) {\n if (CollectionUtils.isEmpty(issues)) {\n return;\n }\n List<String> issueIds = issues.stream().map(Issues::getId).collect(Collectors.toList());\n String projectId = issues.get(0).getProjectId();\n Project project = projectMapper.selectByPrimaryKey(projectId);\n if (project == null) {\n return;\n }\n String templateId = project.getIssueTemplateId();\n if (StringUtils.isBlank(templateId)) {\n return;\n }\n // 模版对于同一个系统字段应该只关联一次\n List<CustomFieldDao> customFields = trackCustomFieldTemplateService.getCustomFieldByTemplateId(templateId);\n List<String> fieldIds = customFields.stream()\n .filter(customField -> StringUtils.equals(SystemCustomField.ISSUE_STATUS, customField.getName()))\n .map(CustomFieldDao::getId).collect(Collectors.toList());\n if (CollectionUtils.isEmpty(fieldIds)) {\n return;\n }\n // 该系统字段的自定义ID\n String customFieldId = fieldIds.get(0);\n CustomFieldIssuesExample example = new CustomFieldIssuesExample();\n example.createCriteria().andFieldIdEqualTo(customFieldId).andResourceIdIn(issueIds);\n List<CustomFieldIssues> customFieldIssues = customFieldIssuesMapper.selectByExample(example);\n Map<String, String> statusMap = customFieldIssues.stream().collect(Collectors.toMap(CustomFieldIssues::getResourceId, CustomFieldIssues::getValue));\n if (MapUtils.isEmpty(statusMap)) {\n return;\n }\n for (IssuesDao issue : issues) {\n issue.setStatus(statusMap.getOrDefault(issue.getId(), StringUtils.EMPTY).replaceAll(\"\\\"\", StringUtils.EMPTY));\n }\n }", " public IssuesWithBLOBs getIssue(String id) {\n IssuesDao issuesWithBLOBs = extIssuesMapper.selectByPrimaryKey(id);\n if (issuesWithBLOBs == null) {\n return null;\n }\n IssuesRequest issuesRequest = new IssuesRequest();\n Project project = baseProjectService.getProjectById(issuesWithBLOBs.getProjectId());\n issuesRequest.setWorkspaceId(project.getWorkspaceId());\n issuesRequest.setProjectId(issuesWithBLOBs.getProjectId());\n issuesRequest.setUserId(issuesWithBLOBs.getCreator());\n if (StringUtils.equals(issuesWithBLOBs.getPlatform(), IssuesManagePlatform.Tapd.name())) {\n TapdPlatform tapdPlatform = (TapdPlatform) IssueFactory.createPlatform(IssuesManagePlatform.Tapd.name(), issuesRequest);\n List<String> tapdUsers = tapdPlatform.getTapdUsers(issuesWithBLOBs.getProjectId(), issuesWithBLOBs.getPlatformId());\n issuesWithBLOBs.setTapdUsers(tapdUsers);\n }\n if (StringUtils.equals(issuesWithBLOBs.getPlatform(), IssuesManagePlatform.Zentao.name())) {\n ZentaoPlatform zentaoPlatform = (ZentaoPlatform) IssueFactory.createPlatform(IssuesManagePlatform.Zentao.name(), issuesRequest);\n zentaoPlatform.getZentaoAssignedAndBuilds(issuesWithBLOBs);\n }\n buildCustomField(issuesWithBLOBs);\n return issuesWithBLOBs;\n }", " public String getPlatform(String projectId) {\n Project project = baseProjectService.getProjectById(projectId);\n return project.getPlatform();\n }", " public List<String> getPlatforms(Project project) {\n String workspaceId = project.getWorkspaceId();\n boolean tapd = isIntegratedPlatform(workspaceId, IssuesManagePlatform.Tapd.toString());\n boolean jira = isIntegratedPlatform(workspaceId, IssuesManagePlatform.Jira.toString());\n boolean zentao = isIntegratedPlatform(workspaceId, IssuesManagePlatform.Zentao.toString());\n boolean azure = isIntegratedPlatform(workspaceId, IssuesManagePlatform.AzureDevops.toString());", " List<String> platforms = new ArrayList<>();\n if (tapd) {\n // 是否关联了项目\n String tapdId = project.getTapdId();\n if (StringUtils.isNotBlank(tapdId) && StringUtils.equals(project.getPlatform(), IssuesManagePlatform.Tapd.toString())) {\n platforms.add(IssuesManagePlatform.Tapd.name());\n }", " }", " if (jira) {\n String jiraKey = project.getJiraKey();\n if (StringUtils.isNotBlank(jiraKey) && PlatformPluginService.isPluginPlatform(project.getPlatform())) {\n platforms.add(IssuesManagePlatform.Jira.name());\n }\n }", " if (zentao) {\n String zentaoId = project.getZentaoId();\n if (StringUtils.isNotBlank(zentaoId) && StringUtils.equals(project.getPlatform(), IssuesManagePlatform.Zentao.toString())) {\n platforms.add(IssuesManagePlatform.Zentao.name());\n }\n }", " if (azure) {\n String azureDevopsId = project.getAzureDevopsId();\n if (StringUtils.isNotBlank(azureDevopsId) && StringUtils.equals(project.getPlatform(), IssuesManagePlatform.AzureDevops.toString())) {\n platforms.add(IssuesManagePlatform.AzureDevops.name());\n }\n }", " return platforms;\n }", "\n /**\n * 是否关联平台\n */\n public boolean isIntegratedPlatform(String workspaceId, String platform) {\n IntegrationRequest request = new IntegrationRequest();\n request.setPlatform(platform);\n request.setWorkspaceId(workspaceId);\n ServiceIntegration integration = baseIntegrationService.get(request);\n return StringUtils.isNotBlank(integration.getId());\n }", " public void closeLocalIssue(String issueId) {\n IssuesWithBLOBs issues = new IssuesWithBLOBs();\n issues.setId(issueId);\n issues.setStatus(\"closed\");\n issuesMapper.updateByPrimaryKeySelective(issues);\n }", " public List<PlatformUser> getTapdProjectUsers(IssuesRequest request) {\n IssuesPlatform platform = IssueFactory.createPlatform(IssuesManagePlatform.Tapd.name(), request);\n return platform.getPlatformUser();\n }", " public List<PlatformUser> getZentaoUsers(IssuesRequest request) {\n IssuesPlatform platform = IssueFactory.createPlatform(IssuesManagePlatform.Zentao.name(), request);\n return platform.getPlatformUser();\n }", " public void deleteIssue(String id) {\n issuesMapper.deleteByPrimaryKey(id);\n TestCaseIssuesExample example = new TestCaseIssuesExample();\n example.createCriteria().andIssuesIdEqualTo(id);\n List<TestCaseIssues> testCaseIssues = testCaseIssuesMapper.selectByExample(example);\n testCaseIssues.forEach(i -> {\n if (i.getRefType().equals(IssueRefType.PLAN_FUNCTIONAL.name())) {\n testCaseIssueService.updateIssuesCount(i.getResourceId());\n }\n });\n customFieldIssuesService.deleteByResourceId(id);\n testCaseIssuesMapper.deleteByExample(example);\n }", " public void deleteIssueRelate(IssuesRequest request) {\n String caseResourceId = request.getCaseResourceId();\n String id = request.getId();\n TestCaseIssuesExample example = new TestCaseIssuesExample();\n if (request.getIsPlanEdit() == true) {\n example.createCriteria().andResourceIdEqualTo(caseResourceId).andIssuesIdEqualTo(id);\n testCaseIssuesMapper.deleteByExample(example);\n testCaseIssueService.updateIssuesCount(caseResourceId);\n } else {\n IssuesUpdateRequest updateRequest = new IssuesUpdateRequest();\n updateRequest.setId(request.getId());\n updateRequest.setResourceId(request.getCaseResourceId());\n updateRequest.setProjectId(request.getProjectId());\n updateRequest.setWorkspaceId(request.getWorkspaceId());\n List<IssuesPlatform> platformList = getUpdatePlatforms(updateRequest);\n platformList.forEach(platform -> {\n platform.removeIssueParentLink(updateRequest);\n });", " extIssuesMapper.deleteIssues(id, caseResourceId);\n TestPlanTestCaseExample testPlanTestCaseExample = new TestPlanTestCaseExample();\n testPlanTestCaseExample.createCriteria().andCaseIdEqualTo(caseResourceId);\n List<TestPlanTestCase> list = testPlanTestCaseMapper.selectByExample(testPlanTestCaseExample);\n list.forEach(item -> {\n testCaseIssueService.updateIssuesCount(item.getId());\n });\n }\n }", " public void delete(String id) {\n IssuesWithBLOBs issuesWithBLOBs = issuesMapper.selectByPrimaryKey(id);\n List platforms = new ArrayList<>();\n platforms.add(issuesWithBLOBs.getPlatform());\n String projectId = issuesWithBLOBs.getProjectId();\n Project project = baseProjectService.getProjectById(projectId);\n IssuesRequest issuesRequest = new IssuesRequest();\n issuesRequest.setWorkspaceId(project.getWorkspaceId());\n if (PlatformPluginService.isPluginPlatform(issuesWithBLOBs.getPlatform())) {\n platformPluginService.getPlatform(issuesWithBLOBs.getPlatform())\n .deleteIssue(issuesWithBLOBs.getPlatformId());\n deleteIssue(id);\n } else {\n IssuesPlatform platform = IssueFactory.createPlatform(issuesWithBLOBs.getPlatform(), issuesRequest);\n platform.deleteIssue(id);\n }", " // 删除缺陷对应的附件\n AttachmentRequest request = new AttachmentRequest();\n request.setBelongId(id);\n request.setBelongType(AttachmentType.ISSUE.type());\n attachmentService.deleteAttachment(request);\n }", " public void batchDelete(IssuesUpdateRequest request) {\n if (request.getBatchDeleteAll()) {\n IssuesRequest issuesRequest = new IssuesRequest();\n issuesRequest.setWorkspaceId(SessionUtils.getCurrentWorkspaceId());\n issuesRequest.setProjectId(SessionUtils.getCurrentProjectId());\n List<IssuesDao> issuesDaos = listByWorkspaceId(issuesRequest);\n if (CollectionUtils.isNotEmpty(issuesDaos)) {\n issuesDaos.parallelStream().forEach(issuesDao -> {\n delete(issuesDao.getId());\n });\n }\n } else {\n if (CollectionUtils.isNotEmpty(request.getBatchDeleteIds())) {\n request.getBatchDeleteIds().parallelStream().forEach(id -> delete(id));\n }\n }\n }", " public List<ZentaoBuild> getZentaoBuilds(IssuesRequest request) {\n try {\n ZentaoPlatform platform = (ZentaoPlatform) IssueFactory.createPlatform(IssuesManagePlatform.Zentao.name(), request);\n return platform.getBuilds();\n } catch (Exception e) {\n LogUtil.error(\"get zentao builds fail.\");\n LogUtil.error(e.getMessage(), e);\n MSException.throwException(Translator.get(\"zentao_get_project_builds_fail\"));\n }\n return null;\n }", " public List<IssuesDao> list(IssuesRequest request) {\n request.setOrders(ServiceUtils.getDefaultOrderByField(request.getOrders(), \"create_time\"));\n request.getOrders().forEach(order -> {\n if (StringUtils.isNotEmpty(order.getName()) && order.getName().startsWith(\"custom\")) {\n request.setIsCustomSorted(true);\n request.setCustomFieldId(order.getName().replace(\"custom_\", StringUtils.EMPTY));\n order.setPrefix(\"cfi\");\n order.setName(\"value\");\n }\n });\n ServiceUtils.setBaseQueryRequestCustomMultipleFields(request);\n List<IssuesDao> issues = extIssuesMapper.getIssues(request);", " Map<String, Set<String>> caseSetMap = getCaseSetMap(issues);\n Map<String, User> userMap = getUserMap(issues);\n Map<String, String> planMap = getPlanMap(issues);", " issues.forEach(item -> {\n User createUser = userMap.get(item.getCreator());\n if (createUser != null) {\n item.setCreatorName(createUser.getName());\n }\n String resourceName = planMap.get(item.getResourceId());\n if (StringUtils.isNotBlank(resourceName)) {\n item.setResourceName(resourceName);\n }", " Set<String> caseIdSet = caseSetMap.get(item.getId());\n if (caseIdSet == null) {\n caseIdSet = new HashSet<>();\n }\n item.setCaseIds(new ArrayList<>(caseIdSet));\n item.setCaseCount(caseIdSet.size());\n });\n buildCustomField(issues);", " //处理MD图片链接内容\n handleJiraIssueMdUrl(request.getWorkspaceId(), request.getProjectId(), issues);", " return issues;\n }", " private void buildCustomField(List<IssuesDao> data) {\n if (CollectionUtils.isEmpty(data)) {\n return;\n }\n Map<String, List<CustomFieldDao>> fieldMap =\n customFieldIssuesService.getMapByResourceIds(data.stream().map(IssuesDao::getId).collect(Collectors.toList()));\n data.forEach(i -> i.setFields(fieldMap.get(i.getId())));\n }", " private void buildCustomField(IssuesDao data) {\n CustomFieldIssuesExample example = new CustomFieldIssuesExample();\n example.createCriteria().andResourceIdEqualTo(data.getId());\n List<CustomFieldIssues> customFieldTestCases = customFieldIssuesMapper.selectByExample(example);\n List<CustomFieldDao> fields = new ArrayList<>();\n customFieldTestCases.forEach(i -> {\n CustomFieldDao customFieldDao = new CustomFieldDao();\n customFieldDao.setId(i.getFieldId());\n customFieldDao.setValue(i.getValue());\n customFieldDao.setTextValue(i.getTextValue());\n fields.add(customFieldDao);\n });\n data.setFields(fields);\n }", " private void buildCustomField(List<IssuesDao> data, Boolean isThirdTemplate, List<CustomFieldDao> customFields) {\n if (CollectionUtils.isEmpty(data)) {\n return;\n }", " Map<String, List<CustomFieldDao>> fieldMap =\n customFieldIssuesService.getMapByResourceIds(data.stream().map(IssuesDao::getId).collect(Collectors.toList()));\n try {\n Map<String, CustomField> fieldMaps = new HashMap<>();\n if (isThirdTemplate) {\n fieldMaps = customFields.stream().collect(Collectors.toMap(CustomFieldDao::getId, field -> (CustomField) field));\n } else {\n List<CustomFieldDao> customfields = fieldMap.get(data.get(0).getId());\n if (CollectionUtils.isNotEmpty(customfields) && customfields.size() > 0) {\n List<String> ids = customfields.stream().map(CustomFieldDao::getId).collect(Collectors.toList());\n List<CustomField> issueFields = baseCustomFieldService.getFieldByIds(ids);\n fieldMaps = issueFields.stream().collect(Collectors.toMap(CustomField::getId, field -> field));\n }\n }", " for (Map.Entry<String, List<CustomFieldDao>> entry : fieldMap.entrySet()) {\n for (CustomFieldDao fieldDao : entry.getValue()) {\n CustomField customField = fieldMaps.get(fieldDao.getId());\n if (customField != null) {\n fieldDao.setName(customField.getName());\n if (StringUtils.equalsAnyIgnoreCase(customField.getType(), CustomFieldType.RICH_TEXT.getValue(), CustomFieldType.TEXTAREA.getValue())) {\n fieldDao.setValue(fieldDao.getTextValue());\n }\n if (StringUtils.equalsAnyIgnoreCase(customField.getType(), CustomFieldType.DATE.getValue()) && StringUtils.isNotEmpty(fieldDao.getValue()) && !StringUtils.equals(fieldDao.getValue(), \"null\")) {\n Date date = DateUtils.parseDate(fieldDao.getValue().replaceAll(\"\\\"\", StringUtils.EMPTY), \"yyyy-MM-dd\");\n String format = DateUtils.format(date, \"yyyy/MM/dd\");\n fieldDao.setValue(\"\\\"\" + format + \"\\\"\");\n }\n if (StringUtils.equalsAnyIgnoreCase(customField.getType(), CustomFieldType.DATETIME.getValue()) && StringUtils.isNotEmpty(fieldDao.getValue()) && !StringUtils.equals(fieldDao.getValue(), \"null\")) {\n Date date = null;\n if (fieldDao.getValue().contains(\"T\") && fieldDao.getValue().length() == 18) {\n date = DateUtils.parseDate(fieldDao.getValue().replaceAll(\"\\\"\", StringUtils.EMPTY), \"yyyy-MM-dd'T'HH:mm\");\n } else if (fieldDao.getValue().contains(\"T\") && fieldDao.getValue().length() == 21) {\n date = DateUtils.parseDate(fieldDao.getValue().replaceAll(\"\\\"\", StringUtils.EMPTY), \"yyyy-MM-dd'T'HH:mm:ss\");\n } else if (fieldDao.getValue().contains(\"T\") && fieldDao.getValue().length() > 21) {\n date = DateUtils.parseDate(fieldDao.getValue().replaceAll(\"\\\"\", StringUtils.EMPTY).substring(0, 19), \"yyyy-MM-dd'T'HH:mm:ss\");\n } else {\n date = DateUtils.parseDate(fieldDao.getValue().replaceAll(\"\\\"\", StringUtils.EMPTY));\n }\n String format = DateUtils.format(date, \"yyyy/MM/dd HH:mm:ss\");\n fieldDao.setValue(\"\\\"\" + format + \"\\\"\");\n }\n if (StringUtils.equalsAnyIgnoreCase(customField.getType(), CustomFieldType.SELECT.getValue(),\n CustomFieldType.MULTIPLE_SELECT.getValue(), CustomFieldType.CHECKBOX.getValue(), CustomFieldType.RADIO.getValue())\n && !StringUtils.equalsAnyIgnoreCase(customField.getName(), SystemCustomField.ISSUE_STATUS)) {\n fieldDao.setValue(parseOptionValue(customField.getOptions(), fieldDao.getValue()));\n }\n }\n }\n }", " data.forEach(i -> i.setFields(fieldMap.get(i.getId())));\n } catch (Exception e) {\n MSException.throwException(e.getMessage());\n }", " }\n", " private void handleJiraIssueMdUrl(String workPlaceId, String projectId, List<IssuesDao> issues) {\n issues.forEach(issue -> {\n if (StringUtils.isNotEmpty(issue.getDescription()) && issue.getDescription().contains(\"platform=Jira&\")) {\n issue.setDescription(replaceJiraMdUrlParam(issue.getDescription(), workPlaceId, projectId));\n }\n if (StringUtils.isNotEmpty(issue.getCustomFields()) && issue.getCustomFields().contains(\"platform=Jira&\")) {\n issue.setCustomFields(replaceJiraMdUrlParam(issue.getCustomFields(), workPlaceId, projectId));\n }\n if (CollectionUtils.isNotEmpty(issue.getFields())) {\n issue.getFields().forEach(field -> {\n if (StringUtils.isNotEmpty(field.getTextValue()) && field.getTextValue().contains(\"platform=Jira&\")) {\n field.setTextValue(replaceJiraMdUrlParam(field.getTextValue(), workPlaceId, projectId));\n }\n if (StringUtils.isNotEmpty(field.getValue()) && field.getValue().contains(\"platform=Jira&\")) {\n field.setValue(replaceJiraMdUrlParam(field.getValue(), workPlaceId, projectId));\n }\n });\n }\n });\n }", " private String replaceJiraMdUrlParam(String url, String workspaceId, String projectId) {\n if (url.contains(\"&workspace_id=\")) {\n return url;\n }\n return url.replaceAll(\"platform=Jira&\",\n \"platform=Jira&workspace_id=\" + workspaceId + \"&\");\n }\n", " private Map<String, List<IssueCommentDTO>> getCommentMap(List<IssuesDao> issues) {\n List<String> issueIds = issues.stream().map(IssuesDao::getId).collect(Collectors.toList());\n List<IssueCommentDTO> comments = extIssueCommentMapper.getCommentsByIssueIds(issueIds);\n Map<String, List<IssueCommentDTO>> commentMap = comments.stream().collect(Collectors.groupingBy(IssueCommentDTO::getIssueId));\n return commentMap;\n }", " private Map<String, String> getPlanMap(List<IssuesDao> issues) {\n List<String> resourceIds = issues.stream().map(IssuesDao::getResourceId)\n .filter(Objects::nonNull)\n .collect(Collectors.toList());", " List<TestPlan> testPlans = testPlanService.getTestPlanByIds(resourceIds);\n Map<String, String> planMap = new HashMap<>();\n if (testPlans != null) {\n planMap = testPlans.stream()\n .collect(Collectors.toMap(TestPlan::getId, TestPlan::getName));\n }\n return planMap;\n }", " private Map<String, User> getUserMap(List<IssuesDao> issues) {\n List<String> userIds = issues.stream()\n .map(IssuesDao::getCreator)\n .collect(Collectors.toList());\n return ServiceUtils.getUserMap(userIds);\n }", " private Map<String, Set<String>> getCaseSetMap(List<IssuesDao> issues) {\n List<String> ids = issues.stream().map(Issues::getId).collect(Collectors.toList());\n Map<String, Set<String>> map = new HashMap<>();\n if (ids.size() == 0) {\n return map;\n }\n TestCaseIssuesExample example = new TestCaseIssuesExample();\n example.createCriteria()\n .andIssuesIdIn(ids);\n List<TestCaseIssues> testCaseIssues = testCaseIssuesMapper.selectByExample(example);", " List<String> caseIds = testCaseIssues.stream().map(x ->\n x.getRefType().equals(IssueRefType.PLAN_FUNCTIONAL.name()) ? x.getRefId() : x.getResourceId())\n .collect(Collectors.toList());", " List<TestCaseDTO> notInTrashCase = testCaseService.getTestCaseByIds(caseIds);", " if (CollectionUtils.isNotEmpty(notInTrashCase)) {\n Set<String> notInTrashCaseSet = notInTrashCase.stream()\n .map(TestCaseDTO::getId)\n .collect(Collectors.toSet());", " testCaseIssues.forEach(i -> {\n Set<String> caseIdSet = new HashSet<>();\n String caseId = i.getRefType().equals(IssueRefType.PLAN_FUNCTIONAL.name()) ? i.getRefId() : i.getResourceId();\n if (notInTrashCaseSet.contains(caseId)) {\n caseIdSet.add(caseId);\n }\n if (map.get(i.getIssuesId()) != null) {\n map.get(i.getIssuesId()).addAll(caseIdSet);\n } else {\n map.put(i.getIssuesId(), caseIdSet);\n }\n });\n }\n return map;\n }", " public Map<String, List<IssuesDao>> getIssueMap(List<IssuesDao> issues) {\n Map<String, List<IssuesDao>> issueMap = new HashMap<>();\n issues.forEach(item -> {\n String platForm = item.getPlatform();\n if (StringUtils.equalsIgnoreCase(IssuesManagePlatform.Local.toString(), item.getPlatform())) {\n // 可能有大小写的问题\n platForm = IssuesManagePlatform.Local.toString();\n }\n List<IssuesDao> issuesDao = issueMap.get(platForm);\n if (issuesDao == null) {\n issuesDao = new ArrayList<>();\n }\n issuesDao.add(item);\n issueMap.put(platForm, issuesDao);\n });\n return issueMap;\n }", " public void syncThirdPartyIssues() {\n List<String> projectIds = trackProjectService.getThirdPartProjectIds();\n projectIds.forEach(id -> {\n try {\n syncThirdPartyIssues(id);\n } catch (Exception e) {\n LogUtil.error(e.getMessage(), e);\n }\n });\n }", " public void issuesCount() {\n LogUtil.info(\"测试计划-测试用例同步缺陷信息开始\");\n int pageSize = 100;\n int pages = 1;\n for (int i = 0; i < pages; i++) {\n Page<List<TestPlanTestCase>> page = PageHelper.startPage(i, pageSize, true);\n List<TestPlanTestCaseWithBLOBs> list = testPlanTestCaseService.listAll();\n pages = page.getPages();// 替换成真实的值\n list.forEach(l -> {\n testCaseIssueService.updateIssuesCount(l.getCaseId());\n });\n }\n LogUtil.info(\"测试计划-测试用例同步缺陷信息结束\");\n }", " public boolean checkSync(String projectId) {\n String syncValue = getSyncKey(projectId);\n if (StringUtils.isNotEmpty(syncValue)) {\n return false;\n }\n return true;\n }", " public String getSyncKey(String projectId) {\n return stringRedisTemplate.opsForValue().get(SYNC_THIRD_PARTY_ISSUES_KEY + \":\" + projectId);\n }", " public void setSyncKey(String projectId) {\n stringRedisTemplate.opsForValue().set(SYNC_THIRD_PARTY_ISSUES_KEY + \":\" + projectId,\n UUID.randomUUID().toString(), 60 * 10, TimeUnit.SECONDS);\n }", " public void deleteSyncKey(String projectId) {\n stringRedisTemplate.delete(SYNC_THIRD_PARTY_ISSUES_KEY + \":\" + projectId);\n }", " public boolean syncThirdPartyIssues(String projectId) {\n if (StringUtils.isNotBlank(projectId)) {\n String syncValue = getSyncKey(projectId);\n if (StringUtils.isNotEmpty(syncValue)) {\n return false;\n }", " setSyncKey(projectId);", " Project project = baseProjectService.getProjectById(projectId);\n List<IssuesDao> issues = extIssuesMapper.getIssueForSync(projectId, project.getPlatform());", " if (CollectionUtils.isEmpty(issues)) {\n deleteSyncKey(projectId);\n return true;\n }", " IssuesRequest issuesRequest = new IssuesRequest();\n issuesRequest.setProjectId(projectId);\n issuesRequest.setWorkspaceId(project.getWorkspaceId());", " try {\n if (!trackProjectService.isThirdPartTemplate(project)) {\n String defaultCustomFields = getDefaultCustomFields(projectId);\n issuesRequest.setDefaultCustomFields(defaultCustomFields);\n }\n if (PlatformPluginService.isPluginPlatform(project.getPlatform())) {\n // 分批处理\n SubListUtil.dealForSubList(issues, 500, (subIssue) ->\n syncPluginThirdPartyIssues(subIssue, project, issuesRequest.getDefaultCustomFields()));\n } else {\n IssuesPlatform platform = IssueFactory.createPlatform(project.getPlatform(), issuesRequest);\n syncThirdPartyIssues(platform::syncIssues, project, issues);\n }\n } catch (Exception e) {\n throw e;\n } finally {\n deleteSyncKey(projectId);\n }\n }\n return true;\n }", " public void syncPluginThirdPartyIssues(List<IssuesDao> issues, Project project, String defaultCustomFields) {\n List<PlatformIssuesDTO> platformIssues = JSON.parseArray(JSON.toJSONString(issues), PlatformIssuesDTO.class);\n platformIssues.stream().forEach(item -> {\n // 给缺陷添加自定义字段\n List<PlatformCustomFieldItemDTO> platformCustomFieldList = extIssuesMapper.getIssueCustomField(item.getId()).stream()\n .map(field -> {\n PlatformCustomFieldItemDTO platformCustomFieldItemDTO = new PlatformCustomFieldItemDTO();\n BeanUtils.copyBean(platformCustomFieldItemDTO, field);\n return platformCustomFieldItemDTO;\n })\n .collect(Collectors.toList());\n item.setCustomFieldList(platformCustomFieldList);\n });\n SyncIssuesRequest request = new SyncIssuesRequest();\n request.setIssues(platformIssues);\n request.setDefaultCustomFields(defaultCustomFields);\n request.setProjectConfig(PlatformPluginService.getCompatibleProjectConfig(project));\n Platform platform = platformPluginService.getPlatform(project.getPlatform(), project.getWorkspaceId());", " // 获取需要变更的缺陷\n SyncIssuesResult syncIssuesResult = platform.syncIssues(request);\n List<IssuesWithBLOBs> updateIssues = syncIssuesResult.getUpdateIssues();", " SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);\n try {\n IssuesMapper issueBatchMapper = sqlSession.getMapper(IssuesMapper.class);\n AttachmentModuleRelationMapper batchAttachmentModuleRelationMapper = sqlSession.getMapper(AttachmentModuleRelationMapper.class);", " // 批量更新\n updateIssues.forEach(issueBatchMapper::updateByPrimaryKeySelective);", " // 批量删除\n syncIssuesResult.getDeleteIssuesIds()\n .stream()\n .forEach(issueBatchMapper::deleteByPrimaryKey);", " try {\n // 同步附件\n syncPluginIssueAttachment(platform, syncIssuesResult, batchAttachmentModuleRelationMapper);\n } catch (Exception e) {\n LogUtil.error(e);\n }", " HashMap<String, List<CustomFieldResourceDTO>> customFieldMap = new HashMap<>();\n updateIssues.forEach(item -> {\n List<CustomFieldResourceDTO> customFieldResource = baseCustomFieldService.getCustomFieldResourceDTO(item.getCustomFields());\n customFieldMap.put(item.getId(), customFieldResource);\n });", " // 修改自定义字段\n customFieldIssuesService.batchEditFields(customFieldMap);", " sqlSession.commit();\n } catch (Exception e) {\n sqlSession.close();\n MSException.throwException(e);\n }\n }", " private void syncPluginIssueAttachment(Platform platform, SyncIssuesResult syncIssuesResult,\n AttachmentModuleRelationMapper batchAttachmentModuleRelationMapper) {\n Map<String, List<PlatformAttachment>> attachmentMap = syncIssuesResult.getAttachmentMap();\n if (MapUtils.isNotEmpty(attachmentMap)) {\n for (String issueId : attachmentMap.keySet()) {\n // 查询我们平台的附件\n Set<String> jiraAttachmentSet = new HashSet<>();\n List<FileAttachmentMetadata> allMsAttachments = getIssueFileAttachmentMetadata(issueId);\n Set<String> attachmentsNameSet = allMsAttachments.stream()\n .map(FileAttachmentMetadata::getName)\n .collect(Collectors.toSet());", " List<PlatformAttachment> syncAttachments = attachmentMap.get(issueId);\n for (PlatformAttachment syncAttachment : syncAttachments) {\n String fileName = syncAttachment.getFileName();\n String fileKey = syncAttachment.getFileKey();\n if (!attachmentsNameSet.contains(fileName)) {\n jiraAttachmentSet.add(fileName);\n saveAttachmentModuleRelation(platform, issueId, fileName, fileKey, batchAttachmentModuleRelationMapper);\n }", " }", " // 删除Jira中不存在的附件\n deleteSyncAttachment(batchAttachmentModuleRelationMapper, jiraAttachmentSet, allMsAttachments);\n }\n }\n }", " private void syncAllPluginIssueAttachment(Project project, IssueSyncRequest syncIssuesResult) {\n // todo 所有平台改造完之后删除\n if (!StringUtils.equals(project.getPlatform(), IssuesManagePlatform.Jira.name())) {\n return;\n }\n SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);\n try {\n AttachmentModuleRelationMapper batchAttachmentModuleRelationMapper = sqlSession.getMapper(AttachmentModuleRelationMapper.class);\n Platform platform = platformPluginService.getPlatform(project.getPlatform(), project.getWorkspaceId());\n Map<String, List<io.metersphere.xpack.track.dto.PlatformAttachment>> attachmentMap = syncIssuesResult.getAttachmentMap();\n if (MapUtils.isNotEmpty(attachmentMap)) {\n for (String issueId : attachmentMap.keySet()) {\n // 查询我们平台的附件\n Set<String> jiraAttachmentSet = new HashSet<>();\n List<FileAttachmentMetadata> allMsAttachments = getIssueFileAttachmentMetadata(issueId);\n Set<String> attachmentsNameSet = allMsAttachments.stream()\n .map(FileAttachmentMetadata::getName)\n .collect(Collectors.toSet());", " List<io.metersphere.xpack.track.dto.PlatformAttachment> syncAttachments = attachmentMap.get(issueId);\n for (io.metersphere.xpack.track.dto.PlatformAttachment syncAttachment : syncAttachments) {\n String fileName = syncAttachment.getFileName();\n String fileKey = syncAttachment.getFileKey();\n if (!attachmentsNameSet.contains(fileName)) {\n jiraAttachmentSet.add(fileName);\n saveAttachmentModuleRelation(platform, issueId, fileName, fileKey, batchAttachmentModuleRelationMapper);\n }", " }", " // 删除Jira中不存在的附件\n deleteSyncAttachment(batchAttachmentModuleRelationMapper, jiraAttachmentSet, allMsAttachments);\n }\n }\n } catch (Exception e) {\n LogUtil.error(e);\n } finally {\n SqlSessionUtils.closeSqlSession(sqlSession, sqlSessionFactory);\n }\n }", " private void deleteSyncAttachment(AttachmentModuleRelationMapper batchAttachmentModuleRelationMapper,\n Set<String> jiraAttachmentSet,\n List<FileAttachmentMetadata> allMsAttachments) {\n // 删除Jira中不存在的附件\n if (CollectionUtils.isNotEmpty(allMsAttachments)) {\n List<FileAttachmentMetadata> deleteMsAttachments = allMsAttachments.stream()\n .filter(msAttachment -> !jiraAttachmentSet.contains(msAttachment.getName()))\n .collect(Collectors.toList());\n deleteMsAttachments.forEach(fileAttachmentMetadata -> {\n List<String> ids = List.of(fileAttachmentMetadata.getId());\n AttachmentModuleRelationExample example = new AttachmentModuleRelationExample();\n example.createCriteria().andAttachmentIdIn(ids).andRelationTypeEqualTo(AttachmentType.ISSUE.type());\n // 删除MS附件及关联数据\n attachmentService.deleteAttachmentByIds(ids);\n attachmentService.deleteFileAttachmentByIds(ids);\n batchAttachmentModuleRelationMapper.deleteByExample(example);\n });\n }\n }", " private void saveAttachmentModuleRelation(Platform platform, String issueId,\n String fileName, String fileKey,\n AttachmentModuleRelationMapper batchAttachmentModuleRelationMapper) {\n try {\n byte[] content = platform.getAttachmentContent(fileKey);\n if (content == null) {\n return;\n }\n FileAttachmentMetadata fileAttachmentMetadata = attachmentService\n .saveAttachmentByBytes(content, AttachmentType.ISSUE.type(), issueId, fileName);\n AttachmentModuleRelation attachmentModuleRelation = new AttachmentModuleRelation();\n attachmentModuleRelation.setAttachmentId(fileAttachmentMetadata.getId());\n attachmentModuleRelation.setRelationId(issueId);\n attachmentModuleRelation.setRelationType(AttachmentType.ISSUE.type());\n batchAttachmentModuleRelationMapper.insert(attachmentModuleRelation);\n } catch (Exception e) {\n LogUtil.error(e);\n }", " }", " private List<FileAttachmentMetadata> getIssueFileAttachmentMetadata(String issueId) {\n AttachmentRequest attachmentRequest = new AttachmentRequest();\n attachmentRequest.setBelongType(AttachmentType.ISSUE.type());\n attachmentRequest.setBelongId(issueId);\n List<FileAttachmentMetadata> allMsAttachments = attachmentService.listMetadata(attachmentRequest);\n return allMsAttachments;\n }", "\n /**\n * 获取默认的自定义字段的取值,同步之后更新成第三方平台的值\n *\n * @param projectId\n * @return\n */\n public String getDefaultCustomFields(String projectId) {\n IssueTemplateDao template = trackIssueTemplateService.getTemplate(projectId);\n List<CustomFieldDao> customFields = trackCustomFieldTemplateService.getCustomFieldByTemplateId(template.getId());\n return getCustomFieldsValuesString(customFields);\n }", " public String getCustomFieldsValuesString(List<CustomFieldDao> customFields) {\n List fields = new ArrayList();\n customFields.forEach(item -> {\n Map<String, Object> field = new LinkedHashMap<>();\n field.put(\"customData\", item.getCustomData());\n field.put(\"id\", item.getId());\n field.put(\"name\", item.getName());\n field.put(\"type\", item.getType());\n String defaultValue = item.getDefaultValue();\n if (StringUtils.isNotBlank(defaultValue)) {\n field.put(\"value\", JSON.parseObject(defaultValue));\n }\n fields.add(field);\n });\n return JSON.toJSONString(fields);\n }", " public void syncThirdPartyIssues(BiConsumer<Project, List<IssuesDao>> syncFuc, Project project, List<IssuesDao> issues) {\n try {\n syncFuc.accept(project, issues);\n } catch (Exception e) {\n LogUtil.error(e.getMessage(), e);\n }\n }", " private String getConfig(String orgId, String platform) {\n IntegrationRequest request = new IntegrationRequest();\n if (StringUtils.isBlank(orgId)) {\n MSException.throwException(\"organization id is null\");\n }\n request.setWorkspaceId(orgId);\n request.setPlatform(platform);", " ServiceIntegration integration = baseIntegrationService.get(request);\n return integration.getConfiguration();\n }", " public String getLogDetails(String id) {\n IssuesWithBLOBs issuesWithBLOBs = issuesMapper.selectByPrimaryKey(id);\n if (issuesWithBLOBs != null) {\n List<DetailColumn> columns = ReflexObjectUtil.getColumns(issuesWithBLOBs, TestPlanReference.issuesColumns);\n OperatingLogDetails details = new OperatingLogDetails(JSON.toJSONString(issuesWithBLOBs.getId()), issuesWithBLOBs.getProjectId(), issuesWithBLOBs.getTitle(), issuesWithBLOBs.getCreator(), columns);\n return JSON.toJSONString(details);\n }\n return null;\n }", " public String getLogDetails(IssuesUpdateRequest issuesRequest) {\n if (issuesRequest != null) {\n issuesRequest.setCreator(SessionUtils.getUserId());\n List<DetailColumn> columns = ReflexObjectUtil.getColumns(issuesRequest, TestPlanReference.issuesColumns);\n OperatingLogDetails details = new OperatingLogDetails(null, issuesRequest.getProjectId(), issuesRequest.getTitle(), issuesRequest.getCreator(), columns);\n return JSON.toJSONString(details);\n }\n return null;\n }", " public List<IssuesDao> relateList(IssuesRequest request) {\n return extIssuesMapper.getIssues(request);\n }", " public void userAuth(AuthUserIssueRequest authUserIssueRequest) {\n IssuesRequest issuesRequest = new IssuesRequest();\n issuesRequest.setWorkspaceId(authUserIssueRequest.getWorkspaceId());\n IssuesPlatform abstractPlatform = IssueFactory.createPlatform(authUserIssueRequest.getPlatform(), issuesRequest);\n abstractPlatform.userAuth(authUserIssueRequest);\n }", " public void calculatePlanReport(String planId, TestPlanSimpleReportDTO report) {\n List<PlanReportIssueDTO> planReportIssueDTOS = extIssuesMapper.selectForPlanReport(planId);\n planReportIssueDTOS = DistinctKeyUtil.distinctByKey(planReportIssueDTOS, PlanReportIssueDTO::getId);\n TestPlanFunctionResultReportDTO functionResult = report.getFunctionResult();\n List<TestCaseReportStatusResultDTO> statusResult = new ArrayList<>();\n Map<String, TestCaseReportStatusResultDTO> statusResultMap = new HashMap<>();", " planReportIssueDTOS.forEach(item -> {\n String status;\n // 本地缺陷\n if (StringUtils.equalsIgnoreCase(item.getPlatform(), IssuesManagePlatform.Local.name())\n || StringUtils.isBlank(item.getPlatform())) {\n status = item.getStatus();\n } else {\n status = item.getPlatformStatus();\n }\n if (StringUtils.isBlank(status)) {\n status = IssuesStatus.NEW.toString();\n }\n TestPlanStatusCalculator.buildStatusResultMap(statusResultMap, status);\n });\n Set<String> status = statusResultMap.keySet();\n status.forEach(item -> {\n TestPlanStatusCalculator.addToReportStatusResultList(statusResultMap, statusResult, item);\n });\n functionResult.setIssueData(statusResult);\n }", " public List<IssuesDao> getIssuesByPlanId(String planId) {\n IssuesRequest issueRequest = new IssuesRequest();\n issueRequest.setPlanId(planId);\n List<IssuesDao> planIssues = extIssuesMapper.getPlanIssues(issueRequest);", " buildCustomField(planIssues);", " replaceStatus(planIssues, planId);\n return DistinctKeyUtil.distinctByKey(planIssues, IssuesDao::getId);\n }", " /**\n * 获取缺陷状态的自定义字段替换\n *\n * @param planIssues\n * @param planId\n */\n private void replaceStatus(List<IssuesDao> planIssues, String planId) {\n TestPlanWithBLOBs testPlan = testPlanService.get(planId);\n CustomField customField = baseCustomFieldService.getCustomFieldByName(testPlan.getProjectId(), SystemCustomField.ISSUE_STATUS);\n planIssues.forEach(issue -> {\n List<CustomFieldDao> fields = issue.getFields();\n if (CollectionUtils.isNotEmpty(fields)) {\n for (CustomFieldDao field : fields) {\n if (field.getId().equals(customField.getId())) {\n List<CustomFieldOptionDTO> options = JSON.parseArray(customField.getOptions(), CustomFieldOptionDTO.class);\n for (CustomFieldOptionDTO option : options) {\n String value = field.getValue();\n if (StringUtils.isNotBlank(value)) {\n value = (String) JSON.parseObject(value);\n }\n if (StringUtils.equals(option.getValue(), value)) {\n if (option.getSystem()) {\n issue.setStatus(option.getValue());\n } else {\n issue.setStatus(option.getText());\n }\n }\n }\n break;\n }\n }\n }\n });\n }", " public void changeStatus(IssuesRequest request) {\n String issuesId = request.getId();\n String status = request.getStatus();\n if (StringUtils.isBlank(issuesId) || StringUtils.isBlank(status)) {\n return;\n }\n IssuesWithBLOBs issue = issuesMapper.selectByPrimaryKey(issuesId);\n Project project = projectMapper.selectByPrimaryKey(issue.getProjectId());\n if (project == null) {\n return;\n }\n String templateId = project.getIssueTemplateId();\n if (StringUtils.isNotBlank(templateId)) {\n // 模版对于同一个系统字段应该只关联一次\n CustomField customField = baseCustomFieldService.getCustomFieldByName(issue.getProjectId(), SystemCustomField.ISSUE_STATUS);\n if (customField != null) {\n String fieldId = customField.getId();\n CustomFieldResourceDTO resource = new CustomFieldResourceDTO();\n resource.setFieldId(fieldId);\n resource.setResourceId(issue.getId());\n resource.setValue(JSON.toJSONString(status));\n customFieldIssuesService.editFields(issue.getId(), Collections.singletonList(resource));\n }\n }\n }", " public List<IssuesStatusCountDao> getCountByStatus(IssuesCountRequest request) {\n request.setCreator(SessionUtils.getUserId());\n List<IssuesStatusCountDao> countByStatus = extIssuesMapper.getCountByStatus(request);\n countByStatus.forEach(item -> {\n if (StringUtils.isBlank(item.getStatusValue())) {\n item.setStatusValue(IssuesStatus.NEW.toString());\n } else {\n item.setStatusValue(item.getStatusValue().replace(\"\\\"\", StringUtils.EMPTY));\n }\n });\n return countByStatus;\n }", " public List<String> getFollows(String issueId) {\n List<String> result = new ArrayList<>();\n if (StringUtils.isBlank(issueId)) {\n return result;\n }\n IssueFollowExample example = new IssueFollowExample();\n example.createCriteria().andIssueIdEqualTo(issueId);\n List<IssueFollow> follows = issueFollowMapper.selectByExample(example);\n if (follows == null || follows.size() == 0) {\n return result;\n }\n result = follows.stream().map(IssueFollow::getFollowId).distinct().collect(Collectors.toList());\n return result;\n }", " public List<IssuesWithBLOBs> getIssuesByPlatformIds(List<String> platformIds, String projectId) {", " if (CollectionUtils.isEmpty(platformIds)) return new ArrayList<>();\n IssuesExample example = new IssuesExample();\n example.createCriteria()\n .andPlatformIdIn(platformIds)\n .andProjectIdEqualTo(projectId);\n return issuesMapper.selectByExampleWithBLOBs(example);\n }", " public IssueTemplateDao getThirdPartTemplate(String projectId) {\n IssueTemplateDao issueTemplateDao = new IssueTemplateDao();\n if (StringUtils.isNotBlank(projectId)) {\n Project project = baseProjectService.getProjectById(projectId);\n List<PlatformCustomFieldItemDTO> thirdPartCustomField = platformPluginService.getPlatform(project.getPlatform(), project.getWorkspaceId())\n .getThirdPartCustomField(PlatformPluginService.getCompatibleProjectConfig(project));\n List<CustomFieldDao> customFieldDaoList = JSON.parseArray(JSON.toJSONString(thirdPartCustomField), CustomFieldDao.class);\n issueTemplateDao.setCustomFields(customFieldDaoList);\n issueTemplateDao.setPlatform(project.getPlatform());\n }\n return issueTemplateDao;\n }", " public IssuesRequest getDefaultIssueRequest(String projectId, String workspaceId) {\n IssuesRequest issuesRequest = new IssuesRequest();\n issuesRequest.setProjectId(projectId);\n issuesRequest.setWorkspaceId(workspaceId);\n return issuesRequest;\n }", " public List getDemandList(String projectId) {\n Project project = baseProjectService.getProjectById(projectId);\n String workspaceId = project.getWorkspaceId();", " if (PlatformPluginService.isPluginPlatform(project.getPlatform())) {\n return platformPluginService.getPlatform(project.getPlatform())\n .getDemands(PlatformPluginService.getCompatibleProjectConfig(project));\n } else {\n IssuesRequest issueRequest = new IssuesRequest();\n issueRequest.setWorkspaceId(workspaceId);\n issueRequest.setProjectId(projectId);\n IssuesPlatform platform = IssueFactory.createPlatform(project.getPlatform(), issueRequest);\n return platform.getDemandList(projectId);\n }\n }", " public List<IssuesDao> listByWorkspaceId(IssuesRequest request) {\n request.setOrders(ServiceUtils.getDefaultOrderByField(request.getOrders(), \"create_time\"));\n return extIssuesMapper.getIssues(request);\n }", " public List<PlatformStatusDTO> getPlatformTransitions(PlatformIssueTypeRequest request) {\n List<PlatformStatusDTO> platformStatusDTOS = new ArrayList<>();", " if (!StringUtils.isBlank(request.getPlatformKey())) {\n Project project = baseProjectService.getProjectById(request.getProjectId());\n String platform = project.getPlatform();\n if (PlatformPluginService.isPluginPlatform(platform)) {\n return platformPluginService.getPlatform(platform)\n .getStatusList(request.getPlatformKey())\n .stream().map(item -> {\n PlatformStatusDTO platformStatusDTO = new PlatformStatusDTO();\n platformStatusDTO.setLabel(item.getLabel());\n platformStatusDTO.setValue(item.getValue());\n return platformStatusDTO;\n })\n .collect(Collectors.toList());\n } else {\n List<String> platforms = getPlatforms(project);\n if (CollectionUtils.isEmpty(platforms)) {\n return platformStatusDTOS;\n }", " IssuesRequest issuesRequest = getDefaultIssueRequest(request.getProjectId(), request.getWorkspaceId());\n return IssueFactory.createPlatform(platform, issuesRequest).getTransitions(request.getPlatformKey());\n }\n }\n return platformStatusDTOS;\n }", " public boolean isThirdPartTemplate(Project project) {\n return project.getThirdPartTemplate() != null\n && project.getThirdPartTemplate()\n && PlatformPluginService.isPluginPlatform(project.getPlatform());\n }", " public void checkThirdProjectExist(Project project) {\n IssuesRequest issuesRequest = new IssuesRequest();\n if (StringUtils.isBlank(project.getId())) {\n MSException.throwException(\"project ID cannot be empty\");\n }\n issuesRequest.setProjectId(project.getId());\n issuesRequest.setWorkspaceId(project.getWorkspaceId());\n if (StringUtils.equalsIgnoreCase(project.getPlatform(), IssuesManagePlatform.Tapd.name())) {\n TapdPlatform tapd = new TapdPlatform(issuesRequest);\n this.doCheckThirdProjectExist(tapd, project.getTapdId());\n } else if (StringUtils.equalsIgnoreCase(project.getPlatform(), IssuesManagePlatform.Zentao.name())) {\n ZentaoPlatform zentao = new ZentaoPlatform(issuesRequest);\n this.doCheckThirdProjectExist(zentao, project.getZentaoId());\n }\n }", " public void issueImportTemplate(String projectId, HttpServletResponse response) {\n Map<String, String> userMap = baseUserService.getProjectMemberOption(projectId).stream().collect(Collectors.toMap(User::getId, User::getName));\n // 获取缺陷模板及自定义字段\n IssueTemplateDao issueTemplate = getIssueTemplateByProjectId(projectId);\n List<CustomFieldDao> customFields = Optional.ofNullable(issueTemplate.getCustomFields()).orElse(new ArrayList<>());\n // 根据自定义字段获取表头\n List<List<String>> heads = new IssueExcelDataFactory().getIssueExcelDataLocal().getHead(issueTemplate.getIsThirdTemplate(), customFields, null);\n // 导出空模板, heads->表头, headHandler->表头处理\n IssueTemplateHeadWriteHandler headHandler = new IssueTemplateHeadWriteHandler(userMap, heads, issueTemplate.getCustomFields());\n new EasyExcelExporter(new IssueExcelDataFactory().getExcelDataByLocal())\n .exportByCustomWriteHandler(response, heads, null, Translator.get(\"issue_import_template_name\"),\n Translator.get(\"issue_import_template_sheet\"), headHandler);\n }", " public ExcelResponse issueImport(IssueImportRequest request, MultipartFile importFile) {\n if (importFile == null) {\n MSException.throwException(Translator.get(\"upload_fail\"));\n }\n Map<String, String> userMap = baseUserService.getProjectMemberOption(request.getProjectId()).stream().collect(Collectors.toMap(User::getId, User::getName));\n // 获取缺陷模板及自定义字段\n IssueTemplateDao issueTemplate = getIssueTemplateByProjectId(request.getProjectId());\n List<CustomFieldDao> customFields = Optional.ofNullable(issueTemplate.getCustomFields()).orElse(new ArrayList<>());\n // 获取本地EXCEL数据对象\n Class clazz = new IssueExcelDataFactory().getExcelDataByLocal();\n // IssueExcelListener读取file内容\n IssueExcelListener issueExcelListener = new IssueExcelListener(request, clazz, issueTemplate.getIsThirdTemplate(), customFields, userMap);\n try {\n EasyExcelFactory.read(importFile.getInputStream(), issueExcelListener).sheet().doRead();\n } catch (IOException e) {\n LogUtil.error(e.getMessage(), e);\n e.printStackTrace();\n }\n // 获取错误信息并返回\n List<ExcelErrData<IssueExcelData>> errList = issueExcelListener.getErrList();\n ExcelResponse excelResponse = new ExcelResponse();\n if (CollectionUtils.isNotEmpty(errList)) {\n excelResponse.setErrList(errList);\n excelResponse.setSuccess(Boolean.FALSE);\n } else {\n excelResponse.setSuccess(Boolean.TRUE);\n }\n return excelResponse;\n }", " public void issueExport(IssueExportRequest request, HttpServletResponse response) {\n EasyExcelExporter.resetCellMaxTextLength();\n Map<String, String> userMap = baseUserService.getProjectMemberOption(request.getProjectId()).stream().collect(Collectors.toMap(User::getId, User::getName));\n // 获取缺陷模板及自定义字段\n IssueTemplateDao issueTemplate = getIssueTemplateByProjectId(request.getProjectId());\n List<CustomFieldDao> customFields = Optional.ofNullable(issueTemplate.getCustomFields()).orElse(new ArrayList<>());\n // 根据自定义字段获取表头内容\n List<List<String>> heads = new IssueExcelDataFactory().getIssueExcelDataLocal().getHead(issueTemplate.getIsThirdTemplate(), customFields, request);\n // 获取导出缺陷列表\n List<IssuesDao> exportIssues = getExportIssues(request, issueTemplate.getIsThirdTemplate(), customFields);\n // 解析issue对象数据->excel对象数据\n List<IssueExcelData> excelDataList = parseIssueDataToExcelData(exportIssues);\n // 解析excel对象数据->excel列表数据\n List<List<Object>> data = parseExcelDataToList(heads, excelDataList);\n // 导出EXCEL\n IssueTemplateHeadWriteHandler headHandler = new IssueTemplateHeadWriteHandler(userMap, heads, issueTemplate.getCustomFields());\n // heads-> 表头内容, data -> 导出EXCEL列表数据, headHandler -> 表头处理\n new EasyExcelExporter(new IssueExcelDataFactory().getExcelDataByLocal())\n .exportByCustomWriteHandler(response, heads, data, Translator.get(\"issue_list_export_excel\"),\n Translator.get(\"issue_list_export_excel_sheet\"), headHandler);\n }", " public List<IssuesDao> getExportIssues(IssueExportRequest exportRequest, Boolean isThirdTemplate, List<CustomFieldDao> customFields) {\n // 根据列表条件获取符合缺陷集合\n IssuesRequest request = new IssuesRequest();\n request.setProjectId(exportRequest.getProjectId());\n request.setWorkspaceId(exportRequest.getWorkspaceId());\n request.setSelectAll(exportRequest.getIsSelectAll());\n request.setExportIds(exportRequest.getExportIds());\n // 列表排序\n request.setOrders(exportRequest.getOrders());\n request.setOrders(ServiceUtils.getDefaultOrderByField(request.getOrders(), \"create_time\"));\n request.getOrders().forEach(order -> {\n if (StringUtils.isNotEmpty(order.getName()) && order.getName().startsWith(\"custom\")) {\n request.setIsCustomSorted(true);\n request.setCustomFieldId(order.getName().replace(\"custom_\", StringUtils.EMPTY));\n order.setPrefix(\"cfi\");\n order.setName(\"value\");\n }\n });\n ServiceUtils.setBaseQueryRequestCustomMultipleFields(request);\n List<IssuesDao> issues = extIssuesMapper.getIssues(request);", " Map<String, Set<String>> caseSetMap = getCaseSetMap(issues);\n Map<String, User> userMap = getUserMap(issues);\n Map<String, String> planMap = getPlanMap(issues);\n Map<String, List<IssueCommentDTO>> commentMap = getCommentMap(issues);", " // 设置creator, caseCount, commnet\n issues.forEach(item -> {\n User createUser = userMap.get(item.getCreator());\n if (createUser != null) {\n item.setCreatorName(createUser.getName());\n }\n String resourceName = planMap.get(item.getResourceId());\n if (StringUtils.isNotBlank(resourceName)) {\n item.setResourceName(resourceName);\n }", " Set<String> caseIdSet = caseSetMap.get(item.getId());\n if (caseIdSet == null) {\n caseIdSet = new HashSet<>();\n }\n item.setCaseIds(new ArrayList<>(caseIdSet));\n item.setCaseCount(caseIdSet.size());\n List<IssueCommentDTO> commentDTOList = commentMap.get(item.getId());\n if (CollectionUtils.isNotEmpty(commentDTOList) && commentDTOList.size() > 0) {\n List<String> comments = commentDTOList.stream().map(IssueCommentDTO::getDescription).collect(Collectors.toList());\n item.setComment(StringUtils.join(comments, \";\"));\n }\n });\n // 解析自定义字段\n buildCustomField(issues, isThirdTemplate, customFields);\n return issues;\n }", " private List<IssueExcelData> parseIssueDataToExcelData(List<IssuesDao> exportIssues) {\n List<IssueExcelData> excelDataList = new ArrayList<>();\n for (int i = 0; i < exportIssues.size(); i++) {\n IssuesDao issuesDao = exportIssues.get(i);\n IssueExcelData excelData = new IssueExcelData();\n BeanUtils.copyBean(excelData, issuesDao);\n buildCustomData(issuesDao, excelData);\n excelDataList.add(excelData);\n }\n return excelDataList;\n }", " private void buildCustomData(IssuesDao issuesDao, IssueExcelData excelData) {\n if (CollectionUtils.isNotEmpty(issuesDao.getFields())) {\n Map<String, Object> customData = new LinkedHashMap<>();\n issuesDao.getFields().forEach(field -> {\n customData.put(field.getName(), field.getValue());\n });\n excelData.setCustomData(customData);\n }\n }", " private List<List<Object>> parseExcelDataToList(List<List<String>> heads, List<IssueExcelData> excelDataList) {\n List<List<Object>> result = new ArrayList<>();\n IssueExportHeadField[] exportHeadFields = IssueExportHeadField.values();\n //转化excel头\n List<String> headList = new ArrayList<>();\n for (List<String> list : heads) {\n for (String head : list) {\n headList.add(head);\n }\n }", " for (IssueExcelData data : excelDataList) {\n List<Object> rowData = new ArrayList<>();\n Map<String, Object> customData = data.getCustomData();\n for (String head : headList) {\n boolean isSystemField = false;\n for (IssueExportHeadField exportHeadField : exportHeadFields) {\n if (StringUtils.equals(head, exportHeadField.getName())) {\n rowData.add(exportHeadField.parseExcelDataValue(data));\n isSystemField = true;\n break;\n }\n }\n if (!isSystemField) {\n // 自定义字段\n Object value = customData.get(head);\n if (value == null || StringUtils.equals(value.toString(), \"null\")) {\n value = StringUtils.EMPTY;\n }\n rowData.add(parseCustomFieldValue(value.toString()));\n }\n }\n result.add(rowData);\n }\n return result;\n }", " private IssueTemplateDao getIssueTemplateByProjectId(String projectId) {\n IssueTemplateDao issueTemplateDao;\n Project project = baseProjectService.getProjectById(projectId);\n if (PlatformPluginService.isPluginPlatform(project.getPlatform())\n && project.getThirdPartTemplate()) {\n // 第三方Jira平台\n issueTemplateDao = getThirdPartTemplate(project.getId());\n issueTemplateDao.setIsThirdTemplate(Boolean.TRUE);\n } else {\n issueTemplateDao = trackIssueTemplateService.getTemplate(projectId);\n issueTemplateDao.setIsThirdTemplate(Boolean.FALSE);\n }\n return issueTemplateDao;\n }", " private void doCheckThirdProjectExist(AbstractIssuePlatform platform, String relateId) {\n if (StringUtils.isBlank(relateId)) {\n MSException.throwException(Translator.get(\"issue_project_not_exist\"));\n }\n Boolean exist = platform.checkProjectExist(relateId);\n if (BooleanUtils.isFalse(exist)) {\n MSException.throwException(Translator.get(\"issue_project_not_exist\"));\n }\n }", " private List<IssuesDao> filterSyncIssuesByCreated(List<IssuesDao> issues, IssueSyncRequest syncRequest) {\n List<IssuesDao> filterIssues = issues.stream().filter(issue -> {\n if (syncRequest.isPre()) {\n return issue.getCreateTime() <= syncRequest.getCreateTime();\n } else {\n return issue.getCreateTime() >= syncRequest.getCreateTime();\n }\n }).collect(Collectors.toList());\n return filterIssues;\n }", " private void uploadAzureCopyAttachment(AttachmentRequest attachmentRequest, String platform, String platformId) {\n List<String> attachmentIds = attachmentService.getAttachmentIdsByParam(attachmentRequest);\n if (CollectionUtils.isNotEmpty(attachmentIds)) {\n attachmentIds.forEach(attachmentId -> {\n FileAttachmentMetadata fileAttachmentMetadata = attachmentService.getFileAttachmentMetadataByFileId(attachmentId);\n File file = new File(fileAttachmentMetadata.getFilePath() + \"/\" + fileAttachmentMetadata.getName());\n IssuesRequest createRequest = new IssuesRequest();\n createRequest.setWorkspaceId(SessionUtils.getCurrentWorkspaceId());\n createRequest.setProjectId(SessionUtils.getCurrentProjectId());\n IssuesPlatform azurePlatform = Objects.requireNonNull(IssueFactory.createPlatform(platform, createRequest));\n IssuesUpdateRequest uploadRequest = new IssuesUpdateRequest();\n uploadRequest.setPlatformId(platformId);\n azurePlatform.syncIssuesAttachment(uploadRequest, file, AttachmentSyncType.UPLOAD);\n });\n }\n }", " private String parseCustomFieldValue(String value) {\n if (value.contains(\",\")) {\n value = value.replaceAll(\",\", \";\");\n }\n if (value.contains(\"\\\"\")) {\n value = value.replaceAll(\"\\\"\", StringUtils.EMPTY);\n }\n if (value.contains(\"[\") || value.contains(\"]\")) {\n value = value.replaceAll(\"]\", StringUtils.EMPTY).replaceAll(\"\\\\[\", StringUtils.EMPTY);\n }\n return value;\n }", " private String parseOptionValue(String options, String tarVal) {\n if (StringUtils.isEmpty(options) || StringUtils.isEmpty(tarVal)) {\n return StringUtils.EMPTY;\n }\n List<Map> optionList = JSON.parseArray(options, Map.class);\n for (Map option : optionList) {\n String text = option.get(\"text\").toString();\n String value = option.get(\"value\").toString();\n if (StringUtils.containsIgnoreCase(tarVal, value)) {\n tarVal = tarVal.replaceAll(value, text);\n }\n }\n return tarVal;\n }", " public Issues checkIssueExist(Integer num, String projectId) {\n IssuesExample example = new IssuesExample();\n example.createCriteria().andNumEqualTo(num).andProjectIdEqualTo(projectId);\n List<Issues> issues = issuesMapper.selectByExample(example);\n return CollectionUtils.isNotEmpty(issues) && issues.size() > 0 ? issues.get(0) : null;\n }", " public void saveImportData(List<IssuesUpdateRequest> issues) {\n issues.parallelStream().forEach(issue -> {\n addIssues(issue, null);\n });\n }", " public void updateImportData(List<IssuesUpdateRequest> issues) {\n issues.parallelStream().forEach(issue -> {\n updateIssues(issue);\n });\n }", " public void setFilterIds(IssuesRequest request) {\n List<String> issueIds = new ArrayList<>();\n if (request.getThisWeekUnClosedTestPlanIssue()) {\n issueIds = extIssuesMapper.getTestPlanThisWeekIssue(request.getProjectId());\n } else if (request.getAllTestPlanIssue() || request.getUnClosedTestPlanIssue()) {\n issueIds = extIssuesMapper.getTestPlanIssue(request.getProjectId());\n } else {\n issueIds = Collections.EMPTY_LIST;\n }", " Map<String, String> statusMap = customFieldIssuesService.getIssueStatusMap(issueIds, request.getProjectId());\n if (MapUtils.isEmpty(statusMap) && CollectionUtils.isNotEmpty(issueIds)) {\n // 未找到自定义字段状态, 则获取平台状态\n IssuesRequest issuesRequest = new IssuesRequest();\n issuesRequest.setProjectId(SessionUtils.getCurrentProjectId());\n issuesRequest.setFilterIds(issueIds);\n List<IssuesDao> issues = extIssuesMapper.getIssues(issuesRequest);\n statusMap = issues.stream().collect(Collectors.toMap(IssuesDao::getId, i -> Optional.ofNullable(i.getPlatformStatus()).orElse(\"new\")));\n }", " if (MapUtils.isEmpty(statusMap)) {\n request.setFilterIds(issueIds);\n } else {\n if (request.getThisWeekUnClosedTestPlanIssue() || request.getUnClosedTestPlanIssue()) {\n CustomField customField = baseCustomFieldService.getCustomFieldByName(SessionUtils.getCurrentProjectId(), SystemCustomField.ISSUE_STATUS);\n JSONArray statusArray = JSONArray.parseArray(customField.getOptions());\n Map<String, String> tmpStatusMap = statusMap;\n List<String> unClosedIds = issueIds.stream()\n .filter(id -> !StringUtils.equals(tmpStatusMap.getOrDefault(id, StringUtils.EMPTY).replaceAll(\"\\\"\", StringUtils.EMPTY), \"closed\"))\n .collect(Collectors.toList());\n Iterator<String> iterator = unClosedIds.iterator();\n while (iterator.hasNext()) {\n String unClosedId = iterator.next();\n String status = statusMap.getOrDefault(unClosedId, StringUtils.EMPTY).replaceAll(\"\\\"\", StringUtils.EMPTY);\n IssueStatus statusEnum = IssueStatus.getEnumByName(status);\n if (statusEnum == null) {\n boolean exist = false;\n for (int i = 0; i < statusArray.size(); i++) {\n JSONObject statusObj = (JSONObject) statusArray.get(i);\n if (StringUtils.equals(status, statusObj.get(\"value\").toString())) {\n exist = true;\n }\n }\n if (!exist) {\n iterator.remove();\n }\n }\n }\n request.setFilterIds(unClosedIds);\n } else {\n request.setFilterIds(issueIds);\n }\n }\n }", " public boolean thirdPartTemplateEnable(String projectId) {\n Project project = baseProjectService.getProjectById(projectId);\n return BooleanUtils.isTrue(project.getThirdPartTemplate())\n && platformPluginService.isThirdPartTemplateSupport(project.getPlatform());\n }", " public boolean syncThirdPartyAllIssues(IssueSyncRequest syncRequest) {\n syncRequest.setProjectId(syncRequest.getProjectId());\n XpackIssueService xpackIssueService = CommonBeanFactory.getBean(XpackIssueService.class);\n if (StringUtils.isNotBlank(syncRequest.getProjectId())) {\n // 获取当前项目执行同步缺陷Key\n String syncValue = getSyncKey(syncRequest.getProjectId());\n // 存在即正在同步中\n if (StringUtils.isNotEmpty(syncValue)) {\n return false;\n }\n // 不存在则设置Key, 设置过期时间, 执行完成后delete掉\n setSyncKey(syncRequest.getProjectId());", " try {\n Project project = baseProjectService.getProjectById(syncRequest.getProjectId());", " if (!isThirdPartTemplate(project)) {\n syncRequest.setDefaultCustomFields(getDefaultCustomFields(syncRequest.getProjectId()));\n }", " xpackIssueService.syncThirdPartyIssues(project, syncRequest);", " syncAllPluginIssueAttachment(project, syncRequest);\n } catch (Exception e) {\n LogUtil.error(e);\n MSException.throwException(e);\n } finally {\n deleteSyncKey(syncRequest.getProjectId());\n }\n }\n return true;\n }\n}" ]
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 113, 27, 22, 821, 90, 246, 337, 684, 42], "buggy_code_start_loc": [24, 109, 26, 18, 62, 90, 7, 9, 495, 3], "filenames": ["framework/gateway/src/main/java/io/metersphere/gateway/filter/SessionFilter.java", "framework/sdk-parent/xpack-interface/src/main/java/io/metersphere/xpack/track/issue/IssuesPlatform.java", "pom.xml", "test-track/backend/src/main/java/io/metersphere/controller/IssueProxyResourceController.java", "test-track/backend/src/main/java/io/metersphere/service/IssuesService.java", "test-track/backend/src/main/java/io/metersphere/service/PlatformPluginService.java", "test-track/backend/src/main/java/io/metersphere/service/issue/client/ZentaoClient.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/AbstractIssuePlatform.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/ZentaoPlatform.java", "test-track/backend/src/main/java/io/metersphere/service/wapper/IssueProxyResourceService.java"], "fixing_code_end_loc": [25, 113, 27, 23, 788, 92, 263, 343, 692, 42], "fixing_code_start_loc": [24, 109, 26, 18, 61, 91, 6, 8, 495, 3], "message": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:metersphere:metersphere:*:*:*:*:*:*:*:*", "matchCriteriaId": "218B4FEB-FDBE-46DB-A728-3CB89E37D5BA", "versionEndExcluding": "2.5.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds."}], "evaluatorComment": null, "id": "CVE-2022-23544", "lastModified": "2023-01-05T04:52:16.033", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.2, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 2.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-12-28T00:15:13.567", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/security/advisories/GHSA-vrv6-cg45-rmjj"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}, {"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, "type": "CWE-918"}
329
Determine whether the {function_name} code is vulnerable or not.
[ "package io.metersphere.service;", "import com.alibaba.excel.EasyExcelFactory;\nimport com.alibaba.excel.util.DateUtils;\nimport com.alibaba.fastjson.JSONArray;\nimport com.alibaba.fastjson.JSONObject;\nimport com.github.pagehelper.Page;\nimport com.github.pagehelper.PageHelper;\nimport io.metersphere.base.domain.*;\nimport io.metersphere.base.mapper.*;\nimport io.metersphere.base.mapper.ext.ExtIssueCommentMapper;\nimport io.metersphere.base.mapper.ext.ExtIssuesMapper;\nimport io.metersphere.commons.constants.*;\nimport io.metersphere.commons.exception.MSException;\nimport io.metersphere.commons.utils.*;\nimport io.metersphere.constants.AttachmentType;\nimport io.metersphere.constants.IssueStatus;\nimport io.metersphere.constants.SystemCustomField;\nimport io.metersphere.dto.*;\nimport io.metersphere.excel.constants.IssueExportHeadField;\nimport io.metersphere.excel.domain.ExcelErrData;\nimport io.metersphere.excel.domain.ExcelResponse;\nimport io.metersphere.excel.domain.IssueExcelData;\nimport io.metersphere.excel.domain.IssueExcelDataFactory;\nimport io.metersphere.excel.handler.IssueTemplateHeadWriteHandler;\nimport io.metersphere.excel.listener.IssueExcelListener;\nimport io.metersphere.excel.utils.EasyExcelExporter;\nimport io.metersphere.i18n.Translator;\nimport io.metersphere.log.utils.ReflexObjectUtil;\nimport io.metersphere.log.vo.DetailColumn;\nimport io.metersphere.log.vo.OperatingLogDetails;\nimport io.metersphere.log.vo.track.TestPlanReference;\nimport io.metersphere.plan.dto.PlanReportIssueDTO;\nimport io.metersphere.plan.dto.TestCaseReportStatusResultDTO;\nimport io.metersphere.plan.dto.TestPlanSimpleReportDTO;\nimport io.metersphere.plan.service.TestPlanService;\nimport io.metersphere.plan.service.TestPlanTestCaseService;\nimport io.metersphere.plan.utils.TestPlanStatusCalculator;\nimport io.metersphere.platform.api.Platform;\nimport io.metersphere.platform.domain.*;\nimport io.metersphere.platform.domain.PlatformAttachment;\nimport io.metersphere.request.IntegrationRequest;\nimport io.metersphere.xpack.track.dto.AttachmentRequest;\nimport io.metersphere.request.issues.IssueExportRequest;\nimport io.metersphere.request.issues.IssueImportRequest;\nimport io.metersphere.request.issues.PlatformIssueTypeRequest;\nimport io.metersphere.request.testcase.AuthUserIssueRequest;\nimport io.metersphere.request.testcase.IssuesCountRequest;\nimport io.metersphere.service.issue.domain.zentao.ZentaoBuild;\nimport io.metersphere.service.issue.platform.*;\nimport io.metersphere.service.remote.project.TrackCustomFieldTemplateService;\nimport io.metersphere.service.remote.project.TrackIssueTemplateService;\nimport io.metersphere.service.wapper.TrackProjectService;\nimport io.metersphere.service.wapper.UserService;\nimport io.metersphere.utils.DistinctKeyUtil;\nimport io.metersphere.xpack.track.dto.PlatformStatusDTO;\nimport io.metersphere.xpack.track.dto.PlatformUser;\nimport io.metersphere.xpack.track.dto.*;\nimport io.metersphere.xpack.track.dto.request.IssuesRequest;\nimport io.metersphere.xpack.track.dto.request.IssuesUpdateRequest;\nimport io.metersphere.xpack.track.issue.IssuesPlatform;", "", "import io.metersphere.xpack.track.service.XpackIssueService;\nimport org.apache.commons.collections.CollectionUtils;\nimport org.apache.commons.collections.MapUtils;\nimport org.apache.commons.lang3.BooleanUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.ibatis.session.ExecutorType;\nimport org.apache.ibatis.session.SqlSession;\nimport org.apache.ibatis.session.SqlSessionFactory;\nimport org.mybatis.spring.SqlSessionUtils;\nimport org.springframework.context.annotation.Lazy;\nimport org.springframework.data.redis.core.StringRedisTemplate;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\nimport org.springframework.web.multipart.MultipartFile;", "import javax.annotation.Resource;\nimport javax.servlet.http.HttpServletResponse;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.*;\nimport java.util.concurrent.TimeUnit;\nimport java.util.function.BiConsumer;\nimport java.util.stream.Collectors;", "@Service\n@Transactional(rollbackFor = Exception.class)\npublic class IssuesService {", " @Resource\n private BaseIntegrationService baseIntegrationService;\n @Resource\n private TrackProjectService trackProjectService;\n @Resource\n private BaseUserService baseUserService;\n @Resource\n private BaseProjectService baseProjectService;\n @Resource\n private TestPlanService testPlanService;\n @Lazy\n @Resource\n private io.metersphere.service.TestCaseService testCaseService;\n @Resource\n private IssuesMapper issuesMapper;\n @Resource\n private TestCaseIssuesMapper testCaseIssuesMapper;\n @Resource\n private ExtIssuesMapper extIssuesMapper;\n @Resource\n private TrackCustomFieldTemplateService trackCustomFieldTemplateService;\n @Resource\n private BaseCustomFieldService baseCustomFieldService;\n @Resource\n private TrackIssueTemplateService trackIssueTemplateService;\n @Resource\n private TestCaseIssueService testCaseIssueService;\n @Lazy\n @Resource\n private TestPlanTestCaseService testPlanTestCaseService;\n @Resource\n private IssueFollowMapper issueFollowMapper;\n @Resource\n private TestPlanTestCaseMapper testPlanTestCaseMapper;\n @Resource\n private CustomFieldIssuesService customFieldIssuesService;\n @Resource\n private CustomFieldIssuesMapper customFieldIssuesMapper;\n @Resource\n StringRedisTemplate stringRedisTemplate;\n @Resource\n private AttachmentService attachmentService;\n @Resource\n private ProjectMapper projectMapper;\n @Resource\n SqlSessionFactory sqlSessionFactory;\n @Resource\n private FileMetadataMapper fileMetadataMapper;\n @Resource\n private ExtIssueCommentMapper extIssueCommentMapper;\n @Resource\n private PlatformPluginService platformPluginService;\n @Resource\n private UserService userService;", " private static final String SYNC_THIRD_PARTY_ISSUES_KEY = \"ISSUE:SYNC\";", " public void testAuth(String workspaceId, String platform) {\n IssuesRequest issuesRequest = new IssuesRequest();\n issuesRequest.setWorkspaceId(workspaceId);\n IssuesPlatform abstractPlatform = IssueFactory.createPlatform(platform, issuesRequest);\n abstractPlatform.testAuth();\n }", "\n public IssuesWithBLOBs addIssues(IssuesUpdateRequest issuesRequest, List<MultipartFile> files) {\n Project project = baseProjectService.getProjectById(issuesRequest.getProjectId());\n IssuesWithBLOBs issues = null;\n if (PlatformPluginService.isPluginPlatform(project.getPlatform())) {\n PlatformIssuesUpdateRequest platformIssuesUpdateRequest =\n JSON.parseObject(JSON.toJSONString(issuesRequest), PlatformIssuesUpdateRequest.class);\n List<PlatformCustomFieldItemDTO> customFieldItemDTOS =\n JSON.parseArray(JSON.toJSONString(issuesRequest.getRequestFields()), PlatformCustomFieldItemDTO.class);\n platformIssuesUpdateRequest.setCustomFieldList(customFieldItemDTOS); // todo 全部插件化后去掉\n platformIssuesUpdateRequest.setUserPlatformUserConfig(userService.getCurrentPlatformInfoStr(SessionUtils.getCurrentWorkspaceId()));\n platformIssuesUpdateRequest.setProjectConfig(PlatformPluginService.getCompatibleProjectConfig(project));", " issues = platformPluginService.getPlatform(project.getPlatform())\n .addIssue(platformIssuesUpdateRequest);", " insertIssues(issues);\n issuesRequest.setId(issues.getId());\n issues.setPlatform(project.getPlatform());\n // 用例与第三方缺陷平台中的缺陷关联\n handleTestCaseIssues(issuesRequest);", " // 如果是复制新增, 同步MS附件到Jira\n if (StringUtils.isNotEmpty(issuesRequest.getCopyIssueId())) {\n AttachmentRequest attachmentRequest = new AttachmentRequest();\n attachmentRequest.setBelongId(issuesRequest.getCopyIssueId());\n attachmentRequest.setBelongType(AttachmentType.ISSUE.type());\n List<String> attachmentIds = attachmentService.getAttachmentIdsByParam(attachmentRequest);\n if (CollectionUtils.isNotEmpty(attachmentIds)) {\n for (String attachmentId : attachmentIds) {\n FileAttachmentMetadata fileAttachmentMetadata = attachmentService.getFileAttachmentMetadataByFileId(attachmentId);\n File file = new File(fileAttachmentMetadata.getFilePath() + \"/\" + fileAttachmentMetadata.getName());\n attachmentService.syncIssuesAttachment(issues, file, AttachmentSyncType.UPLOAD);\n }\n }\n }\n } else {\n List<IssuesPlatform> platformList = getAddPlatforms(issuesRequest);\n for (IssuesPlatform platform : platformList) {\n issues = platform.addIssue(issuesRequest);\n }\n }", " if (issuesRequest.getIsPlanEdit()) {\n issuesRequest.getAddResourceIds().forEach(l -> {\n testCaseIssueService.updateIssuesCount(l);\n });\n }\n String issuesId = issues.getId();\n saveFollows(issuesId, issuesRequest.getFollows());\n customFieldIssuesService.addFields(issuesId, issuesRequest.getAddFields());\n customFieldIssuesService.editFields(issuesId, issuesRequest.getEditFields());\n if (StringUtils.isNotEmpty(issuesRequest.getCopyIssueId())) {\n final String platformId = issues.getPlatformId();\n // 复制新增, 同步缺陷的MS附件\n AttachmentRequest attachmentRequest = new AttachmentRequest();\n attachmentRequest.setCopyBelongId(issuesRequest.getCopyIssueId());\n attachmentRequest.setBelongId(issues.getId());\n attachmentRequest.setBelongType(AttachmentType.ISSUE.type());\n attachmentService.copyAttachment(attachmentRequest);", " // MS附件同步到其他平台, Jira, Zentao已经在创建缺陷时处理, AzureDevops单独处理\n if (StringUtils.equals(issuesRequest.getPlatform(), IssuesManagePlatform.AzureDevops.toString())) {\n AttachmentRequest request = new AttachmentRequest();\n request.setBelongId(issuesRequest.getCopyIssueId());\n request.setBelongType(AttachmentType.ISSUE.type());\n uploadAzureCopyAttachment(request, issuesRequest.getPlatform(), platformId);\n }\n } else {\n final String issueId = issues.getId();\n final String platform = issues.getPlatform();\n // 新增, 需保存并同步所有待上传的附件\n if (CollectionUtils.isNotEmpty(files)) {\n files.forEach(file -> {\n AttachmentRequest attachmentRequest = new AttachmentRequest();\n attachmentRequest.setBelongId(issueId);\n attachmentRequest.setBelongType(AttachmentType.ISSUE.type());\n attachmentService.uploadAttachment(attachmentRequest, file);\n });\n }\n // 处理待关联的文件附件, 生成关联记录, 并同步至第三方平台\n if (CollectionUtils.isNotEmpty(issuesRequest.getRelateFileMetaIds())) {\n SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);\n FileAssociationMapper associationBatchMapper = sqlSession.getMapper(FileAssociationMapper.class);\n AttachmentModuleRelationMapper attachmentModuleRelationBatchMapper = sqlSession.getMapper(AttachmentModuleRelationMapper.class);\n FileAttachmentMetadataMapper fileAttachmentMetadataBatchMapper = sqlSession.getMapper(FileAttachmentMetadataMapper.class);\n issuesRequest.getRelateFileMetaIds().forEach(filemetaId -> {\n FileMetadata fileMetadata = fileMetadataMapper.selectByPrimaryKey(filemetaId);\n FileAssociation fileAssociation = new FileAssociation();\n fileAssociation.setId(UUID.randomUUID().toString());\n fileAssociation.setFileMetadataId(filemetaId);\n fileAssociation.setFileType(fileMetadata.getType());\n fileAssociation.setType(FileAssociationType.ISSUE.name());\n fileAssociation.setProjectId(fileMetadata.getProjectId());\n fileAssociation.setSourceItemId(filemetaId);\n fileAssociation.setSourceId(issueId);\n associationBatchMapper.insert(fileAssociation);\n AttachmentModuleRelation relation = new AttachmentModuleRelation();\n relation.setRelationId(issueId);\n relation.setRelationType(AttachmentType.ISSUE.type());\n relation.setFileMetadataRefId(fileAssociation.getId());\n relation.setAttachmentId(UUID.randomUUID().toString());\n attachmentModuleRelationBatchMapper.insert(relation);\n FileAttachmentMetadata fileAttachmentMetadata = new FileAttachmentMetadata();\n BeanUtils.copyBean(fileAttachmentMetadata, fileMetadata);\n fileAttachmentMetadata.setId(relation.getAttachmentId());\n fileAttachmentMetadata.setCreator(fileMetadata.getCreateUser() == null ? StringUtils.EMPTY : fileMetadata.getCreateUser());\n fileAttachmentMetadata.setFilePath(fileMetadata.getPath() == null ? StringUtils.EMPTY : fileMetadata.getPath());\n fileAttachmentMetadataBatchMapper.insert(fileAttachmentMetadata);\n // 下载文件管理文件, 同步到第三方平台\n File refFile = attachmentService.downloadMetadataFile(filemetaId, fileMetadata.getName());\n if (PlatformPluginService.isPluginPlatform(platform)) {\n issuesRequest.setPlatform(platform);\n attachmentService.syncIssuesAttachment(issuesRequest, refFile, AttachmentSyncType.UPLOAD);\n } else {\n IssuesRequest addIssueRequest = new IssuesRequest();\n addIssueRequest.setWorkspaceId(SessionUtils.getCurrentWorkspaceId());\n addIssueRequest.setProjectId(SessionUtils.getCurrentProjectId());\n Objects.requireNonNull(IssueFactory.createPlatform(platform, addIssueRequest))\n .syncIssuesAttachment(issuesRequest, refFile, AttachmentSyncType.UPLOAD);\n }\n FileUtils.deleteFile(FileUtils.ATTACHMENT_TMP_DIR + File.separator + fileMetadata.getName());\n });\n sqlSession.flushStatements();\n if (sqlSession != null && sqlSessionFactory != null) {\n SqlSessionUtils.closeSqlSession(sqlSession, sqlSessionFactory);\n }\n }\n }\n return getIssue(issues.getId());\n }", " protected IssuesWithBLOBs insertIssues(IssuesWithBLOBs issues) {\n if (StringUtils.isBlank(issues.getId())) {\n issues.setId(UUID.randomUUID().toString());\n }\n issues.setCreateTime(System.currentTimeMillis());\n issues.setUpdateTime(System.currentTimeMillis());\n issues.setNum(getNextNum(issues.getProjectId()));\n issues.setCreator(SessionUtils.getUserId());\n issuesMapper.insert(issues);\n return issues;\n }", " protected int getNextNum(String projectId) {\n Issues issue = extIssuesMapper.getNextNum(projectId);\n if (issue == null || issue.getNum() == null) {\n return 100001;\n } else {\n return Optional.of(issue.getNum() + 1).orElse(100001);\n }\n }", " public void handleTestCaseIssues(IssuesUpdateRequest issuesRequest) {\n String issuesId = issuesRequest.getId();\n List<String> deleteCaseIds = issuesRequest.getDeleteResourceIds();", " if (!org.springframework.util.CollectionUtils.isEmpty(deleteCaseIds)) {\n TestCaseIssuesExample example = new TestCaseIssuesExample();\n example.createCriteria()\n .andResourceIdIn(deleteCaseIds)\n .andIssuesIdEqualTo(issuesId);\n // 测试计划的用例 deleteCaseIds 是空的, 不会进到这里\n example.or(\n example.createCriteria()\n .andRefIdIn(deleteCaseIds)\n .andIssuesIdEqualTo(issuesId)\n );\n testCaseIssuesMapper.deleteByExample(example);\n }", " List<String> addCaseIds = issuesRequest.getAddResourceIds();", " if (!org.springframework.util.CollectionUtils.isEmpty(addCaseIds)) {\n if (issuesRequest.getIsPlanEdit()) {\n addCaseIds.forEach(caseId -> {\n testCaseIssueService.add(issuesId, caseId, issuesRequest.getRefId(), IssueRefType.PLAN_FUNCTIONAL.name());\n testCaseIssueService.updateIssuesCount(caseId);\n });\n } else {\n addCaseIds.forEach(caseId -> testCaseIssueService.add(issuesId, caseId, null, IssueRefType.FUNCTIONAL.name()));\n }\n }\n }", " public IssuesWithBLOBs updateIssues(IssuesUpdateRequest issuesRequest) {\n PlatformIssuesUpdateRequest platformIssuesUpdateRequest = JSON.parseObject(JSON.toJSONString(issuesRequest), PlatformIssuesUpdateRequest.class);\n Project project = baseProjectService.getProjectById(issuesRequest.getProjectId());\n if (PlatformPluginService.isPluginPlatform(project.getPlatform())) {", " Platform platform = platformPluginService.getPlatform(project.getPlatform());", " if (platform.isAttachmentUploadSupport()) {\n AttachmentRequest attachmentRequest = new AttachmentRequest();\n attachmentRequest.setBelongId(issuesRequest.getId());\n attachmentRequest.setBelongType(AttachmentType.ISSUE.type());\n List<FileAttachmentMetadata> fileAttachmentMetadata = attachmentService.listMetadata(attachmentRequest);\n Set<String> msAttachmentNames = fileAttachmentMetadata.stream()\n .map(FileAttachmentMetadata::getName)\n .collect(Collectors.toSet());\n // 获得缺陷MS附件名称\n platformIssuesUpdateRequest.setMsAttachmentNames(msAttachmentNames);\n }", " List<PlatformCustomFieldItemDTO> customFieldItemDTOS = JSON.parseArray(JSON.toJSONString(issuesRequest.getRequestFields()), PlatformCustomFieldItemDTO.class);\n platformIssuesUpdateRequest.setCustomFieldList(customFieldItemDTOS); // todo 全部插件化后去掉\n platformIssuesUpdateRequest.setUserPlatformUserConfig(userService.getCurrentPlatformInfoStr(SessionUtils.getCurrentWorkspaceId()));\n platformIssuesUpdateRequest.setProjectConfig(PlatformPluginService.getCompatibleProjectConfig(project));\n IssuesWithBLOBs issue = platformPluginService.getPlatform(project.getPlatform())\n .updateIssue(platformIssuesUpdateRequest);", " issue.setUpdateTime(System.currentTimeMillis());\n issuesMapper.updateByPrimaryKeySelective(issue);\n handleTestCaseIssues(issuesRequest);\n } else {\n List<IssuesPlatform> platformList = getUpdatePlatforms(issuesRequest);\n platformList.forEach(platform -> {\n platform.updateIssue(issuesRequest);\n });\n }", " customFieldIssuesService.editFields(issuesRequest.getId(), issuesRequest.getEditFields());\n customFieldIssuesService.addFields(issuesRequest.getId(), issuesRequest.getAddFields());", " return getIssue(issuesRequest.getId());\n }", " public void saveFollows(String issueId, List<String> follows) {\n IssueFollowExample example = new IssueFollowExample();\n example.createCriteria().andIssueIdEqualTo(issueId);\n issueFollowMapper.deleteByExample(example);\n if (!CollectionUtils.isEmpty(follows)) {\n for (String follow : follows) {\n IssueFollow issueFollow = new IssueFollow();\n issueFollow.setIssueId(issueId);\n issueFollow.setFollowId(follow);\n issueFollowMapper.insert(issueFollow);\n }\n }\n }", " public List<IssuesPlatform> getAddPlatforms(IssuesUpdateRequest updateRequest) {\n List<String> platforms = new ArrayList<>();\n // 缺陷管理关联\n platforms.add(getPlatform(updateRequest.getProjectId()));", " if (CollectionUtils.isEmpty(platforms)) {\n platforms.add(IssuesManagePlatform.Local.toString());\n }\n IssuesRequest issuesRequest = new IssuesRequest();\n BeanUtils.copyBean(issuesRequest, updateRequest);\n return IssueFactory.createPlatforms(platforms, issuesRequest);\n }", " public List<IssuesPlatform> getUpdatePlatforms(IssuesUpdateRequest updateRequest) {\n String id = updateRequest.getId();\n IssuesWithBLOBs issuesWithBLOBs = issuesMapper.selectByPrimaryKey(id);\n String platform = issuesWithBLOBs.getPlatform();\n List<String> platforms = new ArrayList<>();\n if (StringUtils.isBlank(platform)) {\n platforms.add(IssuesManagePlatform.Local.toString());\n } else {\n platforms.add(platform);\n }\n IssuesRequest issuesRequest = new IssuesRequest();\n BeanUtils.copyBean(issuesRequest, updateRequest);\n return IssueFactory.createPlatforms(platforms, issuesRequest);\n }", " public List<IssuesDao> getIssues(String caseResourceId, String refType) {\n IssuesRequest issueRequest = new IssuesRequest();\n issueRequest.setCaseResourceId(caseResourceId);\n ServiceUtils.getDefaultOrder(issueRequest.getOrders());\n issueRequest.setRefType(refType);\n List<IssuesDao> issues = extIssuesMapper.getIssuesByCaseId(issueRequest);\n handleCustomFieldStatus(issues);\n return DistinctKeyUtil.distinctByKey(issues, IssuesDao::getId);\n }", " private void handleCustomFieldStatus(List<IssuesDao> issues) {\n if (CollectionUtils.isEmpty(issues)) {\n return;\n }\n List<String> issueIds = issues.stream().map(Issues::getId).collect(Collectors.toList());\n String projectId = issues.get(0).getProjectId();\n Project project = projectMapper.selectByPrimaryKey(projectId);\n if (project == null) {\n return;\n }\n String templateId = project.getIssueTemplateId();\n if (StringUtils.isBlank(templateId)) {\n return;\n }\n // 模版对于同一个系统字段应该只关联一次\n List<CustomFieldDao> customFields = trackCustomFieldTemplateService.getCustomFieldByTemplateId(templateId);\n List<String> fieldIds = customFields.stream()\n .filter(customField -> StringUtils.equals(SystemCustomField.ISSUE_STATUS, customField.getName()))\n .map(CustomFieldDao::getId).collect(Collectors.toList());\n if (CollectionUtils.isEmpty(fieldIds)) {\n return;\n }\n // 该系统字段的自定义ID\n String customFieldId = fieldIds.get(0);\n CustomFieldIssuesExample example = new CustomFieldIssuesExample();\n example.createCriteria().andFieldIdEqualTo(customFieldId).andResourceIdIn(issueIds);\n List<CustomFieldIssues> customFieldIssues = customFieldIssuesMapper.selectByExample(example);\n Map<String, String> statusMap = customFieldIssues.stream().collect(Collectors.toMap(CustomFieldIssues::getResourceId, CustomFieldIssues::getValue));\n if (MapUtils.isEmpty(statusMap)) {\n return;\n }\n for (IssuesDao issue : issues) {\n issue.setStatus(statusMap.getOrDefault(issue.getId(), StringUtils.EMPTY).replaceAll(\"\\\"\", StringUtils.EMPTY));\n }\n }", " public IssuesWithBLOBs getIssue(String id) {\n IssuesDao issuesWithBLOBs = extIssuesMapper.selectByPrimaryKey(id);\n if (issuesWithBLOBs == null) {\n return null;\n }\n IssuesRequest issuesRequest = new IssuesRequest();\n Project project = baseProjectService.getProjectById(issuesWithBLOBs.getProjectId());\n issuesRequest.setWorkspaceId(project.getWorkspaceId());\n issuesRequest.setProjectId(issuesWithBLOBs.getProjectId());\n issuesRequest.setUserId(issuesWithBLOBs.getCreator());\n if (StringUtils.equals(issuesWithBLOBs.getPlatform(), IssuesManagePlatform.Tapd.name())) {\n TapdPlatform tapdPlatform = (TapdPlatform) IssueFactory.createPlatform(IssuesManagePlatform.Tapd.name(), issuesRequest);\n List<String> tapdUsers = tapdPlatform.getTapdUsers(issuesWithBLOBs.getProjectId(), issuesWithBLOBs.getPlatformId());\n issuesWithBLOBs.setTapdUsers(tapdUsers);\n }\n if (StringUtils.equals(issuesWithBLOBs.getPlatform(), IssuesManagePlatform.Zentao.name())) {\n ZentaoPlatform zentaoPlatform = (ZentaoPlatform) IssueFactory.createPlatform(IssuesManagePlatform.Zentao.name(), issuesRequest);\n zentaoPlatform.getZentaoAssignedAndBuilds(issuesWithBLOBs);\n }\n buildCustomField(issuesWithBLOBs);\n return issuesWithBLOBs;\n }", " public String getPlatform(String projectId) {\n Project project = baseProjectService.getProjectById(projectId);\n return project.getPlatform();\n }", " public List<String> getPlatforms(Project project) {\n String workspaceId = project.getWorkspaceId();\n boolean tapd = isIntegratedPlatform(workspaceId, IssuesManagePlatform.Tapd.toString());\n boolean jira = isIntegratedPlatform(workspaceId, IssuesManagePlatform.Jira.toString());\n boolean zentao = isIntegratedPlatform(workspaceId, IssuesManagePlatform.Zentao.toString());\n boolean azure = isIntegratedPlatform(workspaceId, IssuesManagePlatform.AzureDevops.toString());", " List<String> platforms = new ArrayList<>();\n if (tapd) {\n // 是否关联了项目\n String tapdId = project.getTapdId();\n if (StringUtils.isNotBlank(tapdId) && StringUtils.equals(project.getPlatform(), IssuesManagePlatform.Tapd.toString())) {\n platforms.add(IssuesManagePlatform.Tapd.name());\n }", " }", " if (jira) {\n String jiraKey = project.getJiraKey();\n if (StringUtils.isNotBlank(jiraKey) && PlatformPluginService.isPluginPlatform(project.getPlatform())) {\n platforms.add(IssuesManagePlatform.Jira.name());\n }\n }", " if (zentao) {\n String zentaoId = project.getZentaoId();\n if (StringUtils.isNotBlank(zentaoId) && StringUtils.equals(project.getPlatform(), IssuesManagePlatform.Zentao.toString())) {\n platforms.add(IssuesManagePlatform.Zentao.name());\n }\n }", " if (azure) {\n String azureDevopsId = project.getAzureDevopsId();\n if (StringUtils.isNotBlank(azureDevopsId) && StringUtils.equals(project.getPlatform(), IssuesManagePlatform.AzureDevops.toString())) {\n platforms.add(IssuesManagePlatform.AzureDevops.name());\n }\n }", " return platforms;\n }", "\n /**\n * 是否关联平台\n */\n public boolean isIntegratedPlatform(String workspaceId, String platform) {\n IntegrationRequest request = new IntegrationRequest();\n request.setPlatform(platform);\n request.setWorkspaceId(workspaceId);\n ServiceIntegration integration = baseIntegrationService.get(request);\n return StringUtils.isNotBlank(integration.getId());\n }", " public void closeLocalIssue(String issueId) {\n IssuesWithBLOBs issues = new IssuesWithBLOBs();\n issues.setId(issueId);\n issues.setStatus(\"closed\");\n issuesMapper.updateByPrimaryKeySelective(issues);\n }", " public List<PlatformUser> getTapdProjectUsers(IssuesRequest request) {\n IssuesPlatform platform = IssueFactory.createPlatform(IssuesManagePlatform.Tapd.name(), request);\n return platform.getPlatformUser();\n }", " public List<PlatformUser> getZentaoUsers(IssuesRequest request) {\n IssuesPlatform platform = IssueFactory.createPlatform(IssuesManagePlatform.Zentao.name(), request);\n return platform.getPlatformUser();\n }", " public void deleteIssue(String id) {\n issuesMapper.deleteByPrimaryKey(id);\n TestCaseIssuesExample example = new TestCaseIssuesExample();\n example.createCriteria().andIssuesIdEqualTo(id);\n List<TestCaseIssues> testCaseIssues = testCaseIssuesMapper.selectByExample(example);\n testCaseIssues.forEach(i -> {\n if (i.getRefType().equals(IssueRefType.PLAN_FUNCTIONAL.name())) {\n testCaseIssueService.updateIssuesCount(i.getResourceId());\n }\n });\n customFieldIssuesService.deleteByResourceId(id);\n testCaseIssuesMapper.deleteByExample(example);\n }", " public void deleteIssueRelate(IssuesRequest request) {\n String caseResourceId = request.getCaseResourceId();\n String id = request.getId();\n TestCaseIssuesExample example = new TestCaseIssuesExample();\n if (request.getIsPlanEdit() == true) {\n example.createCriteria().andResourceIdEqualTo(caseResourceId).andIssuesIdEqualTo(id);\n testCaseIssuesMapper.deleteByExample(example);\n testCaseIssueService.updateIssuesCount(caseResourceId);\n } else {\n IssuesUpdateRequest updateRequest = new IssuesUpdateRequest();\n updateRequest.setId(request.getId());\n updateRequest.setResourceId(request.getCaseResourceId());\n updateRequest.setProjectId(request.getProjectId());\n updateRequest.setWorkspaceId(request.getWorkspaceId());\n List<IssuesPlatform> platformList = getUpdatePlatforms(updateRequest);\n platformList.forEach(platform -> {\n platform.removeIssueParentLink(updateRequest);\n });", " extIssuesMapper.deleteIssues(id, caseResourceId);\n TestPlanTestCaseExample testPlanTestCaseExample = new TestPlanTestCaseExample();\n testPlanTestCaseExample.createCriteria().andCaseIdEqualTo(caseResourceId);\n List<TestPlanTestCase> list = testPlanTestCaseMapper.selectByExample(testPlanTestCaseExample);\n list.forEach(item -> {\n testCaseIssueService.updateIssuesCount(item.getId());\n });\n }\n }", " public void delete(String id) {\n IssuesWithBLOBs issuesWithBLOBs = issuesMapper.selectByPrimaryKey(id);\n List platforms = new ArrayList<>();\n platforms.add(issuesWithBLOBs.getPlatform());\n String projectId = issuesWithBLOBs.getProjectId();\n Project project = baseProjectService.getProjectById(projectId);\n IssuesRequest issuesRequest = new IssuesRequest();\n issuesRequest.setWorkspaceId(project.getWorkspaceId());\n if (PlatformPluginService.isPluginPlatform(issuesWithBLOBs.getPlatform())) {\n platformPluginService.getPlatform(issuesWithBLOBs.getPlatform())\n .deleteIssue(issuesWithBLOBs.getPlatformId());\n deleteIssue(id);\n } else {\n IssuesPlatform platform = IssueFactory.createPlatform(issuesWithBLOBs.getPlatform(), issuesRequest);\n platform.deleteIssue(id);\n }", " // 删除缺陷对应的附件\n AttachmentRequest request = new AttachmentRequest();\n request.setBelongId(id);\n request.setBelongType(AttachmentType.ISSUE.type());\n attachmentService.deleteAttachment(request);\n }", " public void batchDelete(IssuesUpdateRequest request) {\n if (request.getBatchDeleteAll()) {\n IssuesRequest issuesRequest = new IssuesRequest();\n issuesRequest.setWorkspaceId(SessionUtils.getCurrentWorkspaceId());\n issuesRequest.setProjectId(SessionUtils.getCurrentProjectId());\n List<IssuesDao> issuesDaos = listByWorkspaceId(issuesRequest);\n if (CollectionUtils.isNotEmpty(issuesDaos)) {\n issuesDaos.parallelStream().forEach(issuesDao -> {\n delete(issuesDao.getId());\n });\n }\n } else {\n if (CollectionUtils.isNotEmpty(request.getBatchDeleteIds())) {\n request.getBatchDeleteIds().parallelStream().forEach(id -> delete(id));\n }\n }\n }", " public List<ZentaoBuild> getZentaoBuilds(IssuesRequest request) {\n try {\n ZentaoPlatform platform = (ZentaoPlatform) IssueFactory.createPlatform(IssuesManagePlatform.Zentao.name(), request);\n return platform.getBuilds();\n } catch (Exception e) {\n LogUtil.error(\"get zentao builds fail.\");\n LogUtil.error(e.getMessage(), e);\n MSException.throwException(Translator.get(\"zentao_get_project_builds_fail\"));\n }\n return null;\n }", " public List<IssuesDao> list(IssuesRequest request) {\n request.setOrders(ServiceUtils.getDefaultOrderByField(request.getOrders(), \"create_time\"));\n request.getOrders().forEach(order -> {\n if (StringUtils.isNotEmpty(order.getName()) && order.getName().startsWith(\"custom\")) {\n request.setIsCustomSorted(true);\n request.setCustomFieldId(order.getName().replace(\"custom_\", StringUtils.EMPTY));\n order.setPrefix(\"cfi\");\n order.setName(\"value\");\n }\n });\n ServiceUtils.setBaseQueryRequestCustomMultipleFields(request);\n List<IssuesDao> issues = extIssuesMapper.getIssues(request);", " Map<String, Set<String>> caseSetMap = getCaseSetMap(issues);\n Map<String, User> userMap = getUserMap(issues);\n Map<String, String> planMap = getPlanMap(issues);", " issues.forEach(item -> {\n User createUser = userMap.get(item.getCreator());\n if (createUser != null) {\n item.setCreatorName(createUser.getName());\n }\n String resourceName = planMap.get(item.getResourceId());\n if (StringUtils.isNotBlank(resourceName)) {\n item.setResourceName(resourceName);\n }", " Set<String> caseIdSet = caseSetMap.get(item.getId());\n if (caseIdSet == null) {\n caseIdSet = new HashSet<>();\n }\n item.setCaseIds(new ArrayList<>(caseIdSet));\n item.setCaseCount(caseIdSet.size());\n });\n buildCustomField(issues);", "", " return issues;\n }", " private void buildCustomField(List<IssuesDao> data) {\n if (CollectionUtils.isEmpty(data)) {\n return;\n }\n Map<String, List<CustomFieldDao>> fieldMap =\n customFieldIssuesService.getMapByResourceIds(data.stream().map(IssuesDao::getId).collect(Collectors.toList()));\n data.forEach(i -> i.setFields(fieldMap.get(i.getId())));\n }", " private void buildCustomField(IssuesDao data) {\n CustomFieldIssuesExample example = new CustomFieldIssuesExample();\n example.createCriteria().andResourceIdEqualTo(data.getId());\n List<CustomFieldIssues> customFieldTestCases = customFieldIssuesMapper.selectByExample(example);\n List<CustomFieldDao> fields = new ArrayList<>();\n customFieldTestCases.forEach(i -> {\n CustomFieldDao customFieldDao = new CustomFieldDao();\n customFieldDao.setId(i.getFieldId());\n customFieldDao.setValue(i.getValue());\n customFieldDao.setTextValue(i.getTextValue());\n fields.add(customFieldDao);\n });\n data.setFields(fields);\n }", " private void buildCustomField(List<IssuesDao> data, Boolean isThirdTemplate, List<CustomFieldDao> customFields) {\n if (CollectionUtils.isEmpty(data)) {\n return;\n }", " Map<String, List<CustomFieldDao>> fieldMap =\n customFieldIssuesService.getMapByResourceIds(data.stream().map(IssuesDao::getId).collect(Collectors.toList()));\n try {\n Map<String, CustomField> fieldMaps = new HashMap<>();\n if (isThirdTemplate) {\n fieldMaps = customFields.stream().collect(Collectors.toMap(CustomFieldDao::getId, field -> (CustomField) field));\n } else {\n List<CustomFieldDao> customfields = fieldMap.get(data.get(0).getId());\n if (CollectionUtils.isNotEmpty(customfields) && customfields.size() > 0) {\n List<String> ids = customfields.stream().map(CustomFieldDao::getId).collect(Collectors.toList());\n List<CustomField> issueFields = baseCustomFieldService.getFieldByIds(ids);\n fieldMaps = issueFields.stream().collect(Collectors.toMap(CustomField::getId, field -> field));\n }\n }", " for (Map.Entry<String, List<CustomFieldDao>> entry : fieldMap.entrySet()) {\n for (CustomFieldDao fieldDao : entry.getValue()) {\n CustomField customField = fieldMaps.get(fieldDao.getId());\n if (customField != null) {\n fieldDao.setName(customField.getName());\n if (StringUtils.equalsAnyIgnoreCase(customField.getType(), CustomFieldType.RICH_TEXT.getValue(), CustomFieldType.TEXTAREA.getValue())) {\n fieldDao.setValue(fieldDao.getTextValue());\n }\n if (StringUtils.equalsAnyIgnoreCase(customField.getType(), CustomFieldType.DATE.getValue()) && StringUtils.isNotEmpty(fieldDao.getValue()) && !StringUtils.equals(fieldDao.getValue(), \"null\")) {\n Date date = DateUtils.parseDate(fieldDao.getValue().replaceAll(\"\\\"\", StringUtils.EMPTY), \"yyyy-MM-dd\");\n String format = DateUtils.format(date, \"yyyy/MM/dd\");\n fieldDao.setValue(\"\\\"\" + format + \"\\\"\");\n }\n if (StringUtils.equalsAnyIgnoreCase(customField.getType(), CustomFieldType.DATETIME.getValue()) && StringUtils.isNotEmpty(fieldDao.getValue()) && !StringUtils.equals(fieldDao.getValue(), \"null\")) {\n Date date = null;\n if (fieldDao.getValue().contains(\"T\") && fieldDao.getValue().length() == 18) {\n date = DateUtils.parseDate(fieldDao.getValue().replaceAll(\"\\\"\", StringUtils.EMPTY), \"yyyy-MM-dd'T'HH:mm\");\n } else if (fieldDao.getValue().contains(\"T\") && fieldDao.getValue().length() == 21) {\n date = DateUtils.parseDate(fieldDao.getValue().replaceAll(\"\\\"\", StringUtils.EMPTY), \"yyyy-MM-dd'T'HH:mm:ss\");\n } else if (fieldDao.getValue().contains(\"T\") && fieldDao.getValue().length() > 21) {\n date = DateUtils.parseDate(fieldDao.getValue().replaceAll(\"\\\"\", StringUtils.EMPTY).substring(0, 19), \"yyyy-MM-dd'T'HH:mm:ss\");\n } else {\n date = DateUtils.parseDate(fieldDao.getValue().replaceAll(\"\\\"\", StringUtils.EMPTY));\n }\n String format = DateUtils.format(date, \"yyyy/MM/dd HH:mm:ss\");\n fieldDao.setValue(\"\\\"\" + format + \"\\\"\");\n }\n if (StringUtils.equalsAnyIgnoreCase(customField.getType(), CustomFieldType.SELECT.getValue(),\n CustomFieldType.MULTIPLE_SELECT.getValue(), CustomFieldType.CHECKBOX.getValue(), CustomFieldType.RADIO.getValue())\n && !StringUtils.equalsAnyIgnoreCase(customField.getName(), SystemCustomField.ISSUE_STATUS)) {\n fieldDao.setValue(parseOptionValue(customField.getOptions(), fieldDao.getValue()));\n }\n }\n }\n }", " data.forEach(i -> i.setFields(fieldMap.get(i.getId())));\n } catch (Exception e) {\n MSException.throwException(e.getMessage());\n }", " }\n", "", " private Map<String, List<IssueCommentDTO>> getCommentMap(List<IssuesDao> issues) {\n List<String> issueIds = issues.stream().map(IssuesDao::getId).collect(Collectors.toList());\n List<IssueCommentDTO> comments = extIssueCommentMapper.getCommentsByIssueIds(issueIds);\n Map<String, List<IssueCommentDTO>> commentMap = comments.stream().collect(Collectors.groupingBy(IssueCommentDTO::getIssueId));\n return commentMap;\n }", " private Map<String, String> getPlanMap(List<IssuesDao> issues) {\n List<String> resourceIds = issues.stream().map(IssuesDao::getResourceId)\n .filter(Objects::nonNull)\n .collect(Collectors.toList());", " List<TestPlan> testPlans = testPlanService.getTestPlanByIds(resourceIds);\n Map<String, String> planMap = new HashMap<>();\n if (testPlans != null) {\n planMap = testPlans.stream()\n .collect(Collectors.toMap(TestPlan::getId, TestPlan::getName));\n }\n return planMap;\n }", " private Map<String, User> getUserMap(List<IssuesDao> issues) {\n List<String> userIds = issues.stream()\n .map(IssuesDao::getCreator)\n .collect(Collectors.toList());\n return ServiceUtils.getUserMap(userIds);\n }", " private Map<String, Set<String>> getCaseSetMap(List<IssuesDao> issues) {\n List<String> ids = issues.stream().map(Issues::getId).collect(Collectors.toList());\n Map<String, Set<String>> map = new HashMap<>();\n if (ids.size() == 0) {\n return map;\n }\n TestCaseIssuesExample example = new TestCaseIssuesExample();\n example.createCriteria()\n .andIssuesIdIn(ids);\n List<TestCaseIssues> testCaseIssues = testCaseIssuesMapper.selectByExample(example);", " List<String> caseIds = testCaseIssues.stream().map(x ->\n x.getRefType().equals(IssueRefType.PLAN_FUNCTIONAL.name()) ? x.getRefId() : x.getResourceId())\n .collect(Collectors.toList());", " List<TestCaseDTO> notInTrashCase = testCaseService.getTestCaseByIds(caseIds);", " if (CollectionUtils.isNotEmpty(notInTrashCase)) {\n Set<String> notInTrashCaseSet = notInTrashCase.stream()\n .map(TestCaseDTO::getId)\n .collect(Collectors.toSet());", " testCaseIssues.forEach(i -> {\n Set<String> caseIdSet = new HashSet<>();\n String caseId = i.getRefType().equals(IssueRefType.PLAN_FUNCTIONAL.name()) ? i.getRefId() : i.getResourceId();\n if (notInTrashCaseSet.contains(caseId)) {\n caseIdSet.add(caseId);\n }\n if (map.get(i.getIssuesId()) != null) {\n map.get(i.getIssuesId()).addAll(caseIdSet);\n } else {\n map.put(i.getIssuesId(), caseIdSet);\n }\n });\n }\n return map;\n }", " public Map<String, List<IssuesDao>> getIssueMap(List<IssuesDao> issues) {\n Map<String, List<IssuesDao>> issueMap = new HashMap<>();\n issues.forEach(item -> {\n String platForm = item.getPlatform();\n if (StringUtils.equalsIgnoreCase(IssuesManagePlatform.Local.toString(), item.getPlatform())) {\n // 可能有大小写的问题\n platForm = IssuesManagePlatform.Local.toString();\n }\n List<IssuesDao> issuesDao = issueMap.get(platForm);\n if (issuesDao == null) {\n issuesDao = new ArrayList<>();\n }\n issuesDao.add(item);\n issueMap.put(platForm, issuesDao);\n });\n return issueMap;\n }", " public void syncThirdPartyIssues() {\n List<String> projectIds = trackProjectService.getThirdPartProjectIds();\n projectIds.forEach(id -> {\n try {\n syncThirdPartyIssues(id);\n } catch (Exception e) {\n LogUtil.error(e.getMessage(), e);\n }\n });\n }", " public void issuesCount() {\n LogUtil.info(\"测试计划-测试用例同步缺陷信息开始\");\n int pageSize = 100;\n int pages = 1;\n for (int i = 0; i < pages; i++) {\n Page<List<TestPlanTestCase>> page = PageHelper.startPage(i, pageSize, true);\n List<TestPlanTestCaseWithBLOBs> list = testPlanTestCaseService.listAll();\n pages = page.getPages();// 替换成真实的值\n list.forEach(l -> {\n testCaseIssueService.updateIssuesCount(l.getCaseId());\n });\n }\n LogUtil.info(\"测试计划-测试用例同步缺陷信息结束\");\n }", " public boolean checkSync(String projectId) {\n String syncValue = getSyncKey(projectId);\n if (StringUtils.isNotEmpty(syncValue)) {\n return false;\n }\n return true;\n }", " public String getSyncKey(String projectId) {\n return stringRedisTemplate.opsForValue().get(SYNC_THIRD_PARTY_ISSUES_KEY + \":\" + projectId);\n }", " public void setSyncKey(String projectId) {\n stringRedisTemplate.opsForValue().set(SYNC_THIRD_PARTY_ISSUES_KEY + \":\" + projectId,\n UUID.randomUUID().toString(), 60 * 10, TimeUnit.SECONDS);\n }", " public void deleteSyncKey(String projectId) {\n stringRedisTemplate.delete(SYNC_THIRD_PARTY_ISSUES_KEY + \":\" + projectId);\n }", " public boolean syncThirdPartyIssues(String projectId) {\n if (StringUtils.isNotBlank(projectId)) {\n String syncValue = getSyncKey(projectId);\n if (StringUtils.isNotEmpty(syncValue)) {\n return false;\n }", " setSyncKey(projectId);", " Project project = baseProjectService.getProjectById(projectId);\n List<IssuesDao> issues = extIssuesMapper.getIssueForSync(projectId, project.getPlatform());", " if (CollectionUtils.isEmpty(issues)) {\n deleteSyncKey(projectId);\n return true;\n }", " IssuesRequest issuesRequest = new IssuesRequest();\n issuesRequest.setProjectId(projectId);\n issuesRequest.setWorkspaceId(project.getWorkspaceId());", " try {\n if (!trackProjectService.isThirdPartTemplate(project)) {\n String defaultCustomFields = getDefaultCustomFields(projectId);\n issuesRequest.setDefaultCustomFields(defaultCustomFields);\n }\n if (PlatformPluginService.isPluginPlatform(project.getPlatform())) {\n // 分批处理\n SubListUtil.dealForSubList(issues, 500, (subIssue) ->\n syncPluginThirdPartyIssues(subIssue, project, issuesRequest.getDefaultCustomFields()));\n } else {\n IssuesPlatform platform = IssueFactory.createPlatform(project.getPlatform(), issuesRequest);\n syncThirdPartyIssues(platform::syncIssues, project, issues);\n }\n } catch (Exception e) {\n throw e;\n } finally {\n deleteSyncKey(projectId);\n }\n }\n return true;\n }", " public void syncPluginThirdPartyIssues(List<IssuesDao> issues, Project project, String defaultCustomFields) {\n List<PlatformIssuesDTO> platformIssues = JSON.parseArray(JSON.toJSONString(issues), PlatformIssuesDTO.class);\n platformIssues.stream().forEach(item -> {\n // 给缺陷添加自定义字段\n List<PlatformCustomFieldItemDTO> platformCustomFieldList = extIssuesMapper.getIssueCustomField(item.getId()).stream()\n .map(field -> {\n PlatformCustomFieldItemDTO platformCustomFieldItemDTO = new PlatformCustomFieldItemDTO();\n BeanUtils.copyBean(platformCustomFieldItemDTO, field);\n return platformCustomFieldItemDTO;\n })\n .collect(Collectors.toList());\n item.setCustomFieldList(platformCustomFieldList);\n });\n SyncIssuesRequest request = new SyncIssuesRequest();\n request.setIssues(platformIssues);\n request.setDefaultCustomFields(defaultCustomFields);\n request.setProjectConfig(PlatformPluginService.getCompatibleProjectConfig(project));\n Platform platform = platformPluginService.getPlatform(project.getPlatform(), project.getWorkspaceId());", " // 获取需要变更的缺陷\n SyncIssuesResult syncIssuesResult = platform.syncIssues(request);\n List<IssuesWithBLOBs> updateIssues = syncIssuesResult.getUpdateIssues();", " SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);\n try {\n IssuesMapper issueBatchMapper = sqlSession.getMapper(IssuesMapper.class);\n AttachmentModuleRelationMapper batchAttachmentModuleRelationMapper = sqlSession.getMapper(AttachmentModuleRelationMapper.class);", " // 批量更新\n updateIssues.forEach(issueBatchMapper::updateByPrimaryKeySelective);", " // 批量删除\n syncIssuesResult.getDeleteIssuesIds()\n .stream()\n .forEach(issueBatchMapper::deleteByPrimaryKey);", " try {\n // 同步附件\n syncPluginIssueAttachment(platform, syncIssuesResult, batchAttachmentModuleRelationMapper);\n } catch (Exception e) {\n LogUtil.error(e);\n }", " HashMap<String, List<CustomFieldResourceDTO>> customFieldMap = new HashMap<>();\n updateIssues.forEach(item -> {\n List<CustomFieldResourceDTO> customFieldResource = baseCustomFieldService.getCustomFieldResourceDTO(item.getCustomFields());\n customFieldMap.put(item.getId(), customFieldResource);\n });", " // 修改自定义字段\n customFieldIssuesService.batchEditFields(customFieldMap);", " sqlSession.commit();\n } catch (Exception e) {\n sqlSession.close();\n MSException.throwException(e);\n }\n }", " private void syncPluginIssueAttachment(Platform platform, SyncIssuesResult syncIssuesResult,\n AttachmentModuleRelationMapper batchAttachmentModuleRelationMapper) {\n Map<String, List<PlatformAttachment>> attachmentMap = syncIssuesResult.getAttachmentMap();\n if (MapUtils.isNotEmpty(attachmentMap)) {\n for (String issueId : attachmentMap.keySet()) {\n // 查询我们平台的附件\n Set<String> jiraAttachmentSet = new HashSet<>();\n List<FileAttachmentMetadata> allMsAttachments = getIssueFileAttachmentMetadata(issueId);\n Set<String> attachmentsNameSet = allMsAttachments.stream()\n .map(FileAttachmentMetadata::getName)\n .collect(Collectors.toSet());", " List<PlatformAttachment> syncAttachments = attachmentMap.get(issueId);\n for (PlatformAttachment syncAttachment : syncAttachments) {\n String fileName = syncAttachment.getFileName();\n String fileKey = syncAttachment.getFileKey();\n if (!attachmentsNameSet.contains(fileName)) {\n jiraAttachmentSet.add(fileName);\n saveAttachmentModuleRelation(platform, issueId, fileName, fileKey, batchAttachmentModuleRelationMapper);\n }", " }", " // 删除Jira中不存在的附件\n deleteSyncAttachment(batchAttachmentModuleRelationMapper, jiraAttachmentSet, allMsAttachments);\n }\n }\n }", " private void syncAllPluginIssueAttachment(Project project, IssueSyncRequest syncIssuesResult) {\n // todo 所有平台改造完之后删除\n if (!StringUtils.equals(project.getPlatform(), IssuesManagePlatform.Jira.name())) {\n return;\n }\n SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);\n try {\n AttachmentModuleRelationMapper batchAttachmentModuleRelationMapper = sqlSession.getMapper(AttachmentModuleRelationMapper.class);\n Platform platform = platformPluginService.getPlatform(project.getPlatform(), project.getWorkspaceId());\n Map<String, List<io.metersphere.xpack.track.dto.PlatformAttachment>> attachmentMap = syncIssuesResult.getAttachmentMap();\n if (MapUtils.isNotEmpty(attachmentMap)) {\n for (String issueId : attachmentMap.keySet()) {\n // 查询我们平台的附件\n Set<String> jiraAttachmentSet = new HashSet<>();\n List<FileAttachmentMetadata> allMsAttachments = getIssueFileAttachmentMetadata(issueId);\n Set<String> attachmentsNameSet = allMsAttachments.stream()\n .map(FileAttachmentMetadata::getName)\n .collect(Collectors.toSet());", " List<io.metersphere.xpack.track.dto.PlatformAttachment> syncAttachments = attachmentMap.get(issueId);\n for (io.metersphere.xpack.track.dto.PlatformAttachment syncAttachment : syncAttachments) {\n String fileName = syncAttachment.getFileName();\n String fileKey = syncAttachment.getFileKey();\n if (!attachmentsNameSet.contains(fileName)) {\n jiraAttachmentSet.add(fileName);\n saveAttachmentModuleRelation(platform, issueId, fileName, fileKey, batchAttachmentModuleRelationMapper);\n }", " }", " // 删除Jira中不存在的附件\n deleteSyncAttachment(batchAttachmentModuleRelationMapper, jiraAttachmentSet, allMsAttachments);\n }\n }\n } catch (Exception e) {\n LogUtil.error(e);\n } finally {\n SqlSessionUtils.closeSqlSession(sqlSession, sqlSessionFactory);\n }\n }", " private void deleteSyncAttachment(AttachmentModuleRelationMapper batchAttachmentModuleRelationMapper,\n Set<String> jiraAttachmentSet,\n List<FileAttachmentMetadata> allMsAttachments) {\n // 删除Jira中不存在的附件\n if (CollectionUtils.isNotEmpty(allMsAttachments)) {\n List<FileAttachmentMetadata> deleteMsAttachments = allMsAttachments.stream()\n .filter(msAttachment -> !jiraAttachmentSet.contains(msAttachment.getName()))\n .collect(Collectors.toList());\n deleteMsAttachments.forEach(fileAttachmentMetadata -> {\n List<String> ids = List.of(fileAttachmentMetadata.getId());\n AttachmentModuleRelationExample example = new AttachmentModuleRelationExample();\n example.createCriteria().andAttachmentIdIn(ids).andRelationTypeEqualTo(AttachmentType.ISSUE.type());\n // 删除MS附件及关联数据\n attachmentService.deleteAttachmentByIds(ids);\n attachmentService.deleteFileAttachmentByIds(ids);\n batchAttachmentModuleRelationMapper.deleteByExample(example);\n });\n }\n }", " private void saveAttachmentModuleRelation(Platform platform, String issueId,\n String fileName, String fileKey,\n AttachmentModuleRelationMapper batchAttachmentModuleRelationMapper) {\n try {\n byte[] content = platform.getAttachmentContent(fileKey);\n if (content == null) {\n return;\n }\n FileAttachmentMetadata fileAttachmentMetadata = attachmentService\n .saveAttachmentByBytes(content, AttachmentType.ISSUE.type(), issueId, fileName);\n AttachmentModuleRelation attachmentModuleRelation = new AttachmentModuleRelation();\n attachmentModuleRelation.setAttachmentId(fileAttachmentMetadata.getId());\n attachmentModuleRelation.setRelationId(issueId);\n attachmentModuleRelation.setRelationType(AttachmentType.ISSUE.type());\n batchAttachmentModuleRelationMapper.insert(attachmentModuleRelation);\n } catch (Exception e) {\n LogUtil.error(e);\n }", " }", " private List<FileAttachmentMetadata> getIssueFileAttachmentMetadata(String issueId) {\n AttachmentRequest attachmentRequest = new AttachmentRequest();\n attachmentRequest.setBelongType(AttachmentType.ISSUE.type());\n attachmentRequest.setBelongId(issueId);\n List<FileAttachmentMetadata> allMsAttachments = attachmentService.listMetadata(attachmentRequest);\n return allMsAttachments;\n }", "\n /**\n * 获取默认的自定义字段的取值,同步之后更新成第三方平台的值\n *\n * @param projectId\n * @return\n */\n public String getDefaultCustomFields(String projectId) {\n IssueTemplateDao template = trackIssueTemplateService.getTemplate(projectId);\n List<CustomFieldDao> customFields = trackCustomFieldTemplateService.getCustomFieldByTemplateId(template.getId());\n return getCustomFieldsValuesString(customFields);\n }", " public String getCustomFieldsValuesString(List<CustomFieldDao> customFields) {\n List fields = new ArrayList();\n customFields.forEach(item -> {\n Map<String, Object> field = new LinkedHashMap<>();\n field.put(\"customData\", item.getCustomData());\n field.put(\"id\", item.getId());\n field.put(\"name\", item.getName());\n field.put(\"type\", item.getType());\n String defaultValue = item.getDefaultValue();\n if (StringUtils.isNotBlank(defaultValue)) {\n field.put(\"value\", JSON.parseObject(defaultValue));\n }\n fields.add(field);\n });\n return JSON.toJSONString(fields);\n }", " public void syncThirdPartyIssues(BiConsumer<Project, List<IssuesDao>> syncFuc, Project project, List<IssuesDao> issues) {\n try {\n syncFuc.accept(project, issues);\n } catch (Exception e) {\n LogUtil.error(e.getMessage(), e);\n }\n }", " private String getConfig(String orgId, String platform) {\n IntegrationRequest request = new IntegrationRequest();\n if (StringUtils.isBlank(orgId)) {\n MSException.throwException(\"organization id is null\");\n }\n request.setWorkspaceId(orgId);\n request.setPlatform(platform);", " ServiceIntegration integration = baseIntegrationService.get(request);\n return integration.getConfiguration();\n }", " public String getLogDetails(String id) {\n IssuesWithBLOBs issuesWithBLOBs = issuesMapper.selectByPrimaryKey(id);\n if (issuesWithBLOBs != null) {\n List<DetailColumn> columns = ReflexObjectUtil.getColumns(issuesWithBLOBs, TestPlanReference.issuesColumns);\n OperatingLogDetails details = new OperatingLogDetails(JSON.toJSONString(issuesWithBLOBs.getId()), issuesWithBLOBs.getProjectId(), issuesWithBLOBs.getTitle(), issuesWithBLOBs.getCreator(), columns);\n return JSON.toJSONString(details);\n }\n return null;\n }", " public String getLogDetails(IssuesUpdateRequest issuesRequest) {\n if (issuesRequest != null) {\n issuesRequest.setCreator(SessionUtils.getUserId());\n List<DetailColumn> columns = ReflexObjectUtil.getColumns(issuesRequest, TestPlanReference.issuesColumns);\n OperatingLogDetails details = new OperatingLogDetails(null, issuesRequest.getProjectId(), issuesRequest.getTitle(), issuesRequest.getCreator(), columns);\n return JSON.toJSONString(details);\n }\n return null;\n }", " public List<IssuesDao> relateList(IssuesRequest request) {\n return extIssuesMapper.getIssues(request);\n }", " public void userAuth(AuthUserIssueRequest authUserIssueRequest) {\n IssuesRequest issuesRequest = new IssuesRequest();\n issuesRequest.setWorkspaceId(authUserIssueRequest.getWorkspaceId());\n IssuesPlatform abstractPlatform = IssueFactory.createPlatform(authUserIssueRequest.getPlatform(), issuesRequest);\n abstractPlatform.userAuth(authUserIssueRequest);\n }", " public void calculatePlanReport(String planId, TestPlanSimpleReportDTO report) {\n List<PlanReportIssueDTO> planReportIssueDTOS = extIssuesMapper.selectForPlanReport(planId);\n planReportIssueDTOS = DistinctKeyUtil.distinctByKey(planReportIssueDTOS, PlanReportIssueDTO::getId);\n TestPlanFunctionResultReportDTO functionResult = report.getFunctionResult();\n List<TestCaseReportStatusResultDTO> statusResult = new ArrayList<>();\n Map<String, TestCaseReportStatusResultDTO> statusResultMap = new HashMap<>();", " planReportIssueDTOS.forEach(item -> {\n String status;\n // 本地缺陷\n if (StringUtils.equalsIgnoreCase(item.getPlatform(), IssuesManagePlatform.Local.name())\n || StringUtils.isBlank(item.getPlatform())) {\n status = item.getStatus();\n } else {\n status = item.getPlatformStatus();\n }\n if (StringUtils.isBlank(status)) {\n status = IssuesStatus.NEW.toString();\n }\n TestPlanStatusCalculator.buildStatusResultMap(statusResultMap, status);\n });\n Set<String> status = statusResultMap.keySet();\n status.forEach(item -> {\n TestPlanStatusCalculator.addToReportStatusResultList(statusResultMap, statusResult, item);\n });\n functionResult.setIssueData(statusResult);\n }", " public List<IssuesDao> getIssuesByPlanId(String planId) {\n IssuesRequest issueRequest = new IssuesRequest();\n issueRequest.setPlanId(planId);\n List<IssuesDao> planIssues = extIssuesMapper.getPlanIssues(issueRequest);", " buildCustomField(planIssues);", " replaceStatus(planIssues, planId);\n return DistinctKeyUtil.distinctByKey(planIssues, IssuesDao::getId);\n }", " /**\n * 获取缺陷状态的自定义字段替换\n *\n * @param planIssues\n * @param planId\n */\n private void replaceStatus(List<IssuesDao> planIssues, String planId) {\n TestPlanWithBLOBs testPlan = testPlanService.get(planId);\n CustomField customField = baseCustomFieldService.getCustomFieldByName(testPlan.getProjectId(), SystemCustomField.ISSUE_STATUS);\n planIssues.forEach(issue -> {\n List<CustomFieldDao> fields = issue.getFields();\n if (CollectionUtils.isNotEmpty(fields)) {\n for (CustomFieldDao field : fields) {\n if (field.getId().equals(customField.getId())) {\n List<CustomFieldOptionDTO> options = JSON.parseArray(customField.getOptions(), CustomFieldOptionDTO.class);\n for (CustomFieldOptionDTO option : options) {\n String value = field.getValue();\n if (StringUtils.isNotBlank(value)) {\n value = (String) JSON.parseObject(value);\n }\n if (StringUtils.equals(option.getValue(), value)) {\n if (option.getSystem()) {\n issue.setStatus(option.getValue());\n } else {\n issue.setStatus(option.getText());\n }\n }\n }\n break;\n }\n }\n }\n });\n }", " public void changeStatus(IssuesRequest request) {\n String issuesId = request.getId();\n String status = request.getStatus();\n if (StringUtils.isBlank(issuesId) || StringUtils.isBlank(status)) {\n return;\n }\n IssuesWithBLOBs issue = issuesMapper.selectByPrimaryKey(issuesId);\n Project project = projectMapper.selectByPrimaryKey(issue.getProjectId());\n if (project == null) {\n return;\n }\n String templateId = project.getIssueTemplateId();\n if (StringUtils.isNotBlank(templateId)) {\n // 模版对于同一个系统字段应该只关联一次\n CustomField customField = baseCustomFieldService.getCustomFieldByName(issue.getProjectId(), SystemCustomField.ISSUE_STATUS);\n if (customField != null) {\n String fieldId = customField.getId();\n CustomFieldResourceDTO resource = new CustomFieldResourceDTO();\n resource.setFieldId(fieldId);\n resource.setResourceId(issue.getId());\n resource.setValue(JSON.toJSONString(status));\n customFieldIssuesService.editFields(issue.getId(), Collections.singletonList(resource));\n }\n }\n }", " public List<IssuesStatusCountDao> getCountByStatus(IssuesCountRequest request) {\n request.setCreator(SessionUtils.getUserId());\n List<IssuesStatusCountDao> countByStatus = extIssuesMapper.getCountByStatus(request);\n countByStatus.forEach(item -> {\n if (StringUtils.isBlank(item.getStatusValue())) {\n item.setStatusValue(IssuesStatus.NEW.toString());\n } else {\n item.setStatusValue(item.getStatusValue().replace(\"\\\"\", StringUtils.EMPTY));\n }\n });\n return countByStatus;\n }", " public List<String> getFollows(String issueId) {\n List<String> result = new ArrayList<>();\n if (StringUtils.isBlank(issueId)) {\n return result;\n }\n IssueFollowExample example = new IssueFollowExample();\n example.createCriteria().andIssueIdEqualTo(issueId);\n List<IssueFollow> follows = issueFollowMapper.selectByExample(example);\n if (follows == null || follows.size() == 0) {\n return result;\n }\n result = follows.stream().map(IssueFollow::getFollowId).distinct().collect(Collectors.toList());\n return result;\n }", " public List<IssuesWithBLOBs> getIssuesByPlatformIds(List<String> platformIds, String projectId) {", " if (CollectionUtils.isEmpty(platformIds)) return new ArrayList<>();\n IssuesExample example = new IssuesExample();\n example.createCriteria()\n .andPlatformIdIn(platformIds)\n .andProjectIdEqualTo(projectId);\n return issuesMapper.selectByExampleWithBLOBs(example);\n }", " public IssueTemplateDao getThirdPartTemplate(String projectId) {\n IssueTemplateDao issueTemplateDao = new IssueTemplateDao();\n if (StringUtils.isNotBlank(projectId)) {\n Project project = baseProjectService.getProjectById(projectId);\n List<PlatformCustomFieldItemDTO> thirdPartCustomField = platformPluginService.getPlatform(project.getPlatform(), project.getWorkspaceId())\n .getThirdPartCustomField(PlatformPluginService.getCompatibleProjectConfig(project));\n List<CustomFieldDao> customFieldDaoList = JSON.parseArray(JSON.toJSONString(thirdPartCustomField), CustomFieldDao.class);\n issueTemplateDao.setCustomFields(customFieldDaoList);\n issueTemplateDao.setPlatform(project.getPlatform());\n }\n return issueTemplateDao;\n }", " public IssuesRequest getDefaultIssueRequest(String projectId, String workspaceId) {\n IssuesRequest issuesRequest = new IssuesRequest();\n issuesRequest.setProjectId(projectId);\n issuesRequest.setWorkspaceId(workspaceId);\n return issuesRequest;\n }", " public List getDemandList(String projectId) {\n Project project = baseProjectService.getProjectById(projectId);\n String workspaceId = project.getWorkspaceId();", " if (PlatformPluginService.isPluginPlatform(project.getPlatform())) {\n return platformPluginService.getPlatform(project.getPlatform())\n .getDemands(PlatformPluginService.getCompatibleProjectConfig(project));\n } else {\n IssuesRequest issueRequest = new IssuesRequest();\n issueRequest.setWorkspaceId(workspaceId);\n issueRequest.setProjectId(projectId);\n IssuesPlatform platform = IssueFactory.createPlatform(project.getPlatform(), issueRequest);\n return platform.getDemandList(projectId);\n }\n }", " public List<IssuesDao> listByWorkspaceId(IssuesRequest request) {\n request.setOrders(ServiceUtils.getDefaultOrderByField(request.getOrders(), \"create_time\"));\n return extIssuesMapper.getIssues(request);\n }", " public List<PlatformStatusDTO> getPlatformTransitions(PlatformIssueTypeRequest request) {\n List<PlatformStatusDTO> platformStatusDTOS = new ArrayList<>();", " if (!StringUtils.isBlank(request.getPlatformKey())) {\n Project project = baseProjectService.getProjectById(request.getProjectId());\n String platform = project.getPlatform();\n if (PlatformPluginService.isPluginPlatform(platform)) {\n return platformPluginService.getPlatform(platform)\n .getStatusList(request.getPlatformKey())\n .stream().map(item -> {\n PlatformStatusDTO platformStatusDTO = new PlatformStatusDTO();\n platformStatusDTO.setLabel(item.getLabel());\n platformStatusDTO.setValue(item.getValue());\n return platformStatusDTO;\n })\n .collect(Collectors.toList());\n } else {\n List<String> platforms = getPlatforms(project);\n if (CollectionUtils.isEmpty(platforms)) {\n return platformStatusDTOS;\n }", " IssuesRequest issuesRequest = getDefaultIssueRequest(request.getProjectId(), request.getWorkspaceId());\n return IssueFactory.createPlatform(platform, issuesRequest).getTransitions(request.getPlatformKey());\n }\n }\n return platformStatusDTOS;\n }", " public boolean isThirdPartTemplate(Project project) {\n return project.getThirdPartTemplate() != null\n && project.getThirdPartTemplate()\n && PlatformPluginService.isPluginPlatform(project.getPlatform());\n }", " public void checkThirdProjectExist(Project project) {\n IssuesRequest issuesRequest = new IssuesRequest();\n if (StringUtils.isBlank(project.getId())) {\n MSException.throwException(\"project ID cannot be empty\");\n }\n issuesRequest.setProjectId(project.getId());\n issuesRequest.setWorkspaceId(project.getWorkspaceId());\n if (StringUtils.equalsIgnoreCase(project.getPlatform(), IssuesManagePlatform.Tapd.name())) {\n TapdPlatform tapd = new TapdPlatform(issuesRequest);\n this.doCheckThirdProjectExist(tapd, project.getTapdId());\n } else if (StringUtils.equalsIgnoreCase(project.getPlatform(), IssuesManagePlatform.Zentao.name())) {\n ZentaoPlatform zentao = new ZentaoPlatform(issuesRequest);\n this.doCheckThirdProjectExist(zentao, project.getZentaoId());\n }\n }", " public void issueImportTemplate(String projectId, HttpServletResponse response) {\n Map<String, String> userMap = baseUserService.getProjectMemberOption(projectId).stream().collect(Collectors.toMap(User::getId, User::getName));\n // 获取缺陷模板及自定义字段\n IssueTemplateDao issueTemplate = getIssueTemplateByProjectId(projectId);\n List<CustomFieldDao> customFields = Optional.ofNullable(issueTemplate.getCustomFields()).orElse(new ArrayList<>());\n // 根据自定义字段获取表头\n List<List<String>> heads = new IssueExcelDataFactory().getIssueExcelDataLocal().getHead(issueTemplate.getIsThirdTemplate(), customFields, null);\n // 导出空模板, heads->表头, headHandler->表头处理\n IssueTemplateHeadWriteHandler headHandler = new IssueTemplateHeadWriteHandler(userMap, heads, issueTemplate.getCustomFields());\n new EasyExcelExporter(new IssueExcelDataFactory().getExcelDataByLocal())\n .exportByCustomWriteHandler(response, heads, null, Translator.get(\"issue_import_template_name\"),\n Translator.get(\"issue_import_template_sheet\"), headHandler);\n }", " public ExcelResponse issueImport(IssueImportRequest request, MultipartFile importFile) {\n if (importFile == null) {\n MSException.throwException(Translator.get(\"upload_fail\"));\n }\n Map<String, String> userMap = baseUserService.getProjectMemberOption(request.getProjectId()).stream().collect(Collectors.toMap(User::getId, User::getName));\n // 获取缺陷模板及自定义字段\n IssueTemplateDao issueTemplate = getIssueTemplateByProjectId(request.getProjectId());\n List<CustomFieldDao> customFields = Optional.ofNullable(issueTemplate.getCustomFields()).orElse(new ArrayList<>());\n // 获取本地EXCEL数据对象\n Class clazz = new IssueExcelDataFactory().getExcelDataByLocal();\n // IssueExcelListener读取file内容\n IssueExcelListener issueExcelListener = new IssueExcelListener(request, clazz, issueTemplate.getIsThirdTemplate(), customFields, userMap);\n try {\n EasyExcelFactory.read(importFile.getInputStream(), issueExcelListener).sheet().doRead();\n } catch (IOException e) {\n LogUtil.error(e.getMessage(), e);\n e.printStackTrace();\n }\n // 获取错误信息并返回\n List<ExcelErrData<IssueExcelData>> errList = issueExcelListener.getErrList();\n ExcelResponse excelResponse = new ExcelResponse();\n if (CollectionUtils.isNotEmpty(errList)) {\n excelResponse.setErrList(errList);\n excelResponse.setSuccess(Boolean.FALSE);\n } else {\n excelResponse.setSuccess(Boolean.TRUE);\n }\n return excelResponse;\n }", " public void issueExport(IssueExportRequest request, HttpServletResponse response) {\n EasyExcelExporter.resetCellMaxTextLength();\n Map<String, String> userMap = baseUserService.getProjectMemberOption(request.getProjectId()).stream().collect(Collectors.toMap(User::getId, User::getName));\n // 获取缺陷模板及自定义字段\n IssueTemplateDao issueTemplate = getIssueTemplateByProjectId(request.getProjectId());\n List<CustomFieldDao> customFields = Optional.ofNullable(issueTemplate.getCustomFields()).orElse(new ArrayList<>());\n // 根据自定义字段获取表头内容\n List<List<String>> heads = new IssueExcelDataFactory().getIssueExcelDataLocal().getHead(issueTemplate.getIsThirdTemplate(), customFields, request);\n // 获取导出缺陷列表\n List<IssuesDao> exportIssues = getExportIssues(request, issueTemplate.getIsThirdTemplate(), customFields);\n // 解析issue对象数据->excel对象数据\n List<IssueExcelData> excelDataList = parseIssueDataToExcelData(exportIssues);\n // 解析excel对象数据->excel列表数据\n List<List<Object>> data = parseExcelDataToList(heads, excelDataList);\n // 导出EXCEL\n IssueTemplateHeadWriteHandler headHandler = new IssueTemplateHeadWriteHandler(userMap, heads, issueTemplate.getCustomFields());\n // heads-> 表头内容, data -> 导出EXCEL列表数据, headHandler -> 表头处理\n new EasyExcelExporter(new IssueExcelDataFactory().getExcelDataByLocal())\n .exportByCustomWriteHandler(response, heads, data, Translator.get(\"issue_list_export_excel\"),\n Translator.get(\"issue_list_export_excel_sheet\"), headHandler);\n }", " public List<IssuesDao> getExportIssues(IssueExportRequest exportRequest, Boolean isThirdTemplate, List<CustomFieldDao> customFields) {\n // 根据列表条件获取符合缺陷集合\n IssuesRequest request = new IssuesRequest();\n request.setProjectId(exportRequest.getProjectId());\n request.setWorkspaceId(exportRequest.getWorkspaceId());\n request.setSelectAll(exportRequest.getIsSelectAll());\n request.setExportIds(exportRequest.getExportIds());\n // 列表排序\n request.setOrders(exportRequest.getOrders());\n request.setOrders(ServiceUtils.getDefaultOrderByField(request.getOrders(), \"create_time\"));\n request.getOrders().forEach(order -> {\n if (StringUtils.isNotEmpty(order.getName()) && order.getName().startsWith(\"custom\")) {\n request.setIsCustomSorted(true);\n request.setCustomFieldId(order.getName().replace(\"custom_\", StringUtils.EMPTY));\n order.setPrefix(\"cfi\");\n order.setName(\"value\");\n }\n });\n ServiceUtils.setBaseQueryRequestCustomMultipleFields(request);\n List<IssuesDao> issues = extIssuesMapper.getIssues(request);", " Map<String, Set<String>> caseSetMap = getCaseSetMap(issues);\n Map<String, User> userMap = getUserMap(issues);\n Map<String, String> planMap = getPlanMap(issues);\n Map<String, List<IssueCommentDTO>> commentMap = getCommentMap(issues);", " // 设置creator, caseCount, commnet\n issues.forEach(item -> {\n User createUser = userMap.get(item.getCreator());\n if (createUser != null) {\n item.setCreatorName(createUser.getName());\n }\n String resourceName = planMap.get(item.getResourceId());\n if (StringUtils.isNotBlank(resourceName)) {\n item.setResourceName(resourceName);\n }", " Set<String> caseIdSet = caseSetMap.get(item.getId());\n if (caseIdSet == null) {\n caseIdSet = new HashSet<>();\n }\n item.setCaseIds(new ArrayList<>(caseIdSet));\n item.setCaseCount(caseIdSet.size());\n List<IssueCommentDTO> commentDTOList = commentMap.get(item.getId());\n if (CollectionUtils.isNotEmpty(commentDTOList) && commentDTOList.size() > 0) {\n List<String> comments = commentDTOList.stream().map(IssueCommentDTO::getDescription).collect(Collectors.toList());\n item.setComment(StringUtils.join(comments, \";\"));\n }\n });\n // 解析自定义字段\n buildCustomField(issues, isThirdTemplate, customFields);\n return issues;\n }", " private List<IssueExcelData> parseIssueDataToExcelData(List<IssuesDao> exportIssues) {\n List<IssueExcelData> excelDataList = new ArrayList<>();\n for (int i = 0; i < exportIssues.size(); i++) {\n IssuesDao issuesDao = exportIssues.get(i);\n IssueExcelData excelData = new IssueExcelData();\n BeanUtils.copyBean(excelData, issuesDao);\n buildCustomData(issuesDao, excelData);\n excelDataList.add(excelData);\n }\n return excelDataList;\n }", " private void buildCustomData(IssuesDao issuesDao, IssueExcelData excelData) {\n if (CollectionUtils.isNotEmpty(issuesDao.getFields())) {\n Map<String, Object> customData = new LinkedHashMap<>();\n issuesDao.getFields().forEach(field -> {\n customData.put(field.getName(), field.getValue());\n });\n excelData.setCustomData(customData);\n }\n }", " private List<List<Object>> parseExcelDataToList(List<List<String>> heads, List<IssueExcelData> excelDataList) {\n List<List<Object>> result = new ArrayList<>();\n IssueExportHeadField[] exportHeadFields = IssueExportHeadField.values();\n //转化excel头\n List<String> headList = new ArrayList<>();\n for (List<String> list : heads) {\n for (String head : list) {\n headList.add(head);\n }\n }", " for (IssueExcelData data : excelDataList) {\n List<Object> rowData = new ArrayList<>();\n Map<String, Object> customData = data.getCustomData();\n for (String head : headList) {\n boolean isSystemField = false;\n for (IssueExportHeadField exportHeadField : exportHeadFields) {\n if (StringUtils.equals(head, exportHeadField.getName())) {\n rowData.add(exportHeadField.parseExcelDataValue(data));\n isSystemField = true;\n break;\n }\n }\n if (!isSystemField) {\n // 自定义字段\n Object value = customData.get(head);\n if (value == null || StringUtils.equals(value.toString(), \"null\")) {\n value = StringUtils.EMPTY;\n }\n rowData.add(parseCustomFieldValue(value.toString()));\n }\n }\n result.add(rowData);\n }\n return result;\n }", " private IssueTemplateDao getIssueTemplateByProjectId(String projectId) {\n IssueTemplateDao issueTemplateDao;\n Project project = baseProjectService.getProjectById(projectId);\n if (PlatformPluginService.isPluginPlatform(project.getPlatform())\n && project.getThirdPartTemplate()) {\n // 第三方Jira平台\n issueTemplateDao = getThirdPartTemplate(project.getId());\n issueTemplateDao.setIsThirdTemplate(Boolean.TRUE);\n } else {\n issueTemplateDao = trackIssueTemplateService.getTemplate(projectId);\n issueTemplateDao.setIsThirdTemplate(Boolean.FALSE);\n }\n return issueTemplateDao;\n }", " private void doCheckThirdProjectExist(AbstractIssuePlatform platform, String relateId) {\n if (StringUtils.isBlank(relateId)) {\n MSException.throwException(Translator.get(\"issue_project_not_exist\"));\n }\n Boolean exist = platform.checkProjectExist(relateId);\n if (BooleanUtils.isFalse(exist)) {\n MSException.throwException(Translator.get(\"issue_project_not_exist\"));\n }\n }", " private List<IssuesDao> filterSyncIssuesByCreated(List<IssuesDao> issues, IssueSyncRequest syncRequest) {\n List<IssuesDao> filterIssues = issues.stream().filter(issue -> {\n if (syncRequest.isPre()) {\n return issue.getCreateTime() <= syncRequest.getCreateTime();\n } else {\n return issue.getCreateTime() >= syncRequest.getCreateTime();\n }\n }).collect(Collectors.toList());\n return filterIssues;\n }", " private void uploadAzureCopyAttachment(AttachmentRequest attachmentRequest, String platform, String platformId) {\n List<String> attachmentIds = attachmentService.getAttachmentIdsByParam(attachmentRequest);\n if (CollectionUtils.isNotEmpty(attachmentIds)) {\n attachmentIds.forEach(attachmentId -> {\n FileAttachmentMetadata fileAttachmentMetadata = attachmentService.getFileAttachmentMetadataByFileId(attachmentId);\n File file = new File(fileAttachmentMetadata.getFilePath() + \"/\" + fileAttachmentMetadata.getName());\n IssuesRequest createRequest = new IssuesRequest();\n createRequest.setWorkspaceId(SessionUtils.getCurrentWorkspaceId());\n createRequest.setProjectId(SessionUtils.getCurrentProjectId());\n IssuesPlatform azurePlatform = Objects.requireNonNull(IssueFactory.createPlatform(platform, createRequest));\n IssuesUpdateRequest uploadRequest = new IssuesUpdateRequest();\n uploadRequest.setPlatformId(platformId);\n azurePlatform.syncIssuesAttachment(uploadRequest, file, AttachmentSyncType.UPLOAD);\n });\n }\n }", " private String parseCustomFieldValue(String value) {\n if (value.contains(\",\")) {\n value = value.replaceAll(\",\", \";\");\n }\n if (value.contains(\"\\\"\")) {\n value = value.replaceAll(\"\\\"\", StringUtils.EMPTY);\n }\n if (value.contains(\"[\") || value.contains(\"]\")) {\n value = value.replaceAll(\"]\", StringUtils.EMPTY).replaceAll(\"\\\\[\", StringUtils.EMPTY);\n }\n return value;\n }", " private String parseOptionValue(String options, String tarVal) {\n if (StringUtils.isEmpty(options) || StringUtils.isEmpty(tarVal)) {\n return StringUtils.EMPTY;\n }\n List<Map> optionList = JSON.parseArray(options, Map.class);\n for (Map option : optionList) {\n String text = option.get(\"text\").toString();\n String value = option.get(\"value\").toString();\n if (StringUtils.containsIgnoreCase(tarVal, value)) {\n tarVal = tarVal.replaceAll(value, text);\n }\n }\n return tarVal;\n }", " public Issues checkIssueExist(Integer num, String projectId) {\n IssuesExample example = new IssuesExample();\n example.createCriteria().andNumEqualTo(num).andProjectIdEqualTo(projectId);\n List<Issues> issues = issuesMapper.selectByExample(example);\n return CollectionUtils.isNotEmpty(issues) && issues.size() > 0 ? issues.get(0) : null;\n }", " public void saveImportData(List<IssuesUpdateRequest> issues) {\n issues.parallelStream().forEach(issue -> {\n addIssues(issue, null);\n });\n }", " public void updateImportData(List<IssuesUpdateRequest> issues) {\n issues.parallelStream().forEach(issue -> {\n updateIssues(issue);\n });\n }", " public void setFilterIds(IssuesRequest request) {\n List<String> issueIds = new ArrayList<>();\n if (request.getThisWeekUnClosedTestPlanIssue()) {\n issueIds = extIssuesMapper.getTestPlanThisWeekIssue(request.getProjectId());\n } else if (request.getAllTestPlanIssue() || request.getUnClosedTestPlanIssue()) {\n issueIds = extIssuesMapper.getTestPlanIssue(request.getProjectId());\n } else {\n issueIds = Collections.EMPTY_LIST;\n }", " Map<String, String> statusMap = customFieldIssuesService.getIssueStatusMap(issueIds, request.getProjectId());\n if (MapUtils.isEmpty(statusMap) && CollectionUtils.isNotEmpty(issueIds)) {\n // 未找到自定义字段状态, 则获取平台状态\n IssuesRequest issuesRequest = new IssuesRequest();\n issuesRequest.setProjectId(SessionUtils.getCurrentProjectId());\n issuesRequest.setFilterIds(issueIds);\n List<IssuesDao> issues = extIssuesMapper.getIssues(issuesRequest);\n statusMap = issues.stream().collect(Collectors.toMap(IssuesDao::getId, i -> Optional.ofNullable(i.getPlatformStatus()).orElse(\"new\")));\n }", " if (MapUtils.isEmpty(statusMap)) {\n request.setFilterIds(issueIds);\n } else {\n if (request.getThisWeekUnClosedTestPlanIssue() || request.getUnClosedTestPlanIssue()) {\n CustomField customField = baseCustomFieldService.getCustomFieldByName(SessionUtils.getCurrentProjectId(), SystemCustomField.ISSUE_STATUS);\n JSONArray statusArray = JSONArray.parseArray(customField.getOptions());\n Map<String, String> tmpStatusMap = statusMap;\n List<String> unClosedIds = issueIds.stream()\n .filter(id -> !StringUtils.equals(tmpStatusMap.getOrDefault(id, StringUtils.EMPTY).replaceAll(\"\\\"\", StringUtils.EMPTY), \"closed\"))\n .collect(Collectors.toList());\n Iterator<String> iterator = unClosedIds.iterator();\n while (iterator.hasNext()) {\n String unClosedId = iterator.next();\n String status = statusMap.getOrDefault(unClosedId, StringUtils.EMPTY).replaceAll(\"\\\"\", StringUtils.EMPTY);\n IssueStatus statusEnum = IssueStatus.getEnumByName(status);\n if (statusEnum == null) {\n boolean exist = false;\n for (int i = 0; i < statusArray.size(); i++) {\n JSONObject statusObj = (JSONObject) statusArray.get(i);\n if (StringUtils.equals(status, statusObj.get(\"value\").toString())) {\n exist = true;\n }\n }\n if (!exist) {\n iterator.remove();\n }\n }\n }\n request.setFilterIds(unClosedIds);\n } else {\n request.setFilterIds(issueIds);\n }\n }\n }", " public boolean thirdPartTemplateEnable(String projectId) {\n Project project = baseProjectService.getProjectById(projectId);\n return BooleanUtils.isTrue(project.getThirdPartTemplate())\n && platformPluginService.isThirdPartTemplateSupport(project.getPlatform());\n }", " public boolean syncThirdPartyAllIssues(IssueSyncRequest syncRequest) {\n syncRequest.setProjectId(syncRequest.getProjectId());\n XpackIssueService xpackIssueService = CommonBeanFactory.getBean(XpackIssueService.class);\n if (StringUtils.isNotBlank(syncRequest.getProjectId())) {\n // 获取当前项目执行同步缺陷Key\n String syncValue = getSyncKey(syncRequest.getProjectId());\n // 存在即正在同步中\n if (StringUtils.isNotEmpty(syncValue)) {\n return false;\n }\n // 不存在则设置Key, 设置过期时间, 执行完成后delete掉\n setSyncKey(syncRequest.getProjectId());", " try {\n Project project = baseProjectService.getProjectById(syncRequest.getProjectId());", " if (!isThirdPartTemplate(project)) {\n syncRequest.setDefaultCustomFields(getDefaultCustomFields(syncRequest.getProjectId()));\n }", " xpackIssueService.syncThirdPartyIssues(project, syncRequest);", " syncAllPluginIssueAttachment(project, syncRequest);\n } catch (Exception e) {\n LogUtil.error(e);\n MSException.throwException(e);\n } finally {\n deleteSyncKey(syncRequest.getProjectId());\n }\n }\n return true;\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 113, 27, 22, 821, 90, 246, 337, 684, 42], "buggy_code_start_loc": [24, 109, 26, 18, 62, 90, 7, 9, 495, 3], "filenames": ["framework/gateway/src/main/java/io/metersphere/gateway/filter/SessionFilter.java", "framework/sdk-parent/xpack-interface/src/main/java/io/metersphere/xpack/track/issue/IssuesPlatform.java", "pom.xml", "test-track/backend/src/main/java/io/metersphere/controller/IssueProxyResourceController.java", "test-track/backend/src/main/java/io/metersphere/service/IssuesService.java", "test-track/backend/src/main/java/io/metersphere/service/PlatformPluginService.java", "test-track/backend/src/main/java/io/metersphere/service/issue/client/ZentaoClient.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/AbstractIssuePlatform.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/ZentaoPlatform.java", "test-track/backend/src/main/java/io/metersphere/service/wapper/IssueProxyResourceService.java"], "fixing_code_end_loc": [25, 113, 27, 23, 788, 92, 263, 343, 692, 42], "fixing_code_start_loc": [24, 109, 26, 18, 61, 91, 6, 8, 495, 3], "message": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:metersphere:metersphere:*:*:*:*:*:*:*:*", "matchCriteriaId": "218B4FEB-FDBE-46DB-A728-3CB89E37D5BA", "versionEndExcluding": "2.5.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds."}], "evaluatorComment": null, "id": "CVE-2022-23544", "lastModified": "2023-01-05T04:52:16.033", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.2, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 2.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-12-28T00:15:13.567", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/security/advisories/GHSA-vrv6-cg45-rmjj"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}, {"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, "type": "CWE-918"}
329
Determine whether the {function_name} code is vulnerable or not.
[ "package io.metersphere.service;", "import io.metersphere.commons.constants.IssuesManagePlatform;\nimport io.metersphere.commons.exception.MSException;\nimport io.metersphere.commons.utils.JSON;\nimport io.metersphere.i18n.Translator;\nimport io.metersphere.platform.api.Platform;\nimport io.metersphere.platform.api.PluginMetaInfo;\nimport io.metersphere.base.domain.PluginWithBLOBs;\nimport io.metersphere.base.domain.Project;\nimport io.metersphere.base.domain.ServiceIntegration;\nimport io.metersphere.commons.constants.PluginScenario;\nimport io.metersphere.commons.utils.SessionUtils;\nimport io.metersphere.platform.domain.PlatformRequest;\nimport io.metersphere.platform.domain.SelectOption;\nimport io.metersphere.platform.loader.PlatformPluginManager;\nimport io.metersphere.request.IntegrationRequest;\nimport io.metersphere.utils.PluginManagerUtil;\nimport org.apache.commons.lang3.StringUtils;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;", "import javax.annotation.Resource;\nimport java.io.InputStream;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;", "@Service\n@Transactional(rollbackFor = Exception.class)\npublic class PlatformPluginService {", " @Resource\n private BasePluginService basePluginService;\n @Resource\n private BaseIntegrationService baseIntegrationService;", " public static final String PLUGIN_DOWNLOAD_URL = \"https://github.com/metersphere/metersphere-platform-plugin\";", " private PlatformPluginManager pluginManager;", " public synchronized PlatformPluginManager getPluginManager() {\n if (pluginManager == null) {\n pluginManager = new PlatformPluginManager();\n }\n return pluginManager;\n }", " /**\n * 查询所有平台插件并加载\n */\n public void loadPlatFormPlugins() {\n List<PluginWithBLOBs> plugins = basePluginService.getPlugins(PluginScenario.platform.name());\n PluginManagerUtil.loadPlugins(getPluginManager(), plugins);\n }", " public void loadPlugin(String pluginId) {\n if (getPluginManager().getClassLoader(pluginId) == null) {\n // 如果没有加载才加载\n InputStream pluginJar = basePluginService.getPluginJar(pluginId);\n PluginManagerUtil.loadPlugin(pluginId, getPluginManager(), pluginJar);\n }\n }", " /**\n * 卸载插件\n * @param pluginId\n */\n public void unloadPlugin(String pluginId) {\n getPluginManager().deletePlugin(pluginId);\n }", " public boolean isThirdPartTemplateSupport(String platform) {\n if (StringUtils.isBlank(platform)) {\n return false;\n }\n PluginMetaInfo pluginMetaInfo = pluginManager.getPluginMetaInfoByKey(platform);\n if (PlatformPluginService.isPluginPlatform(platform) && pluginMetaInfo == null) {\n MSException.throwException(Translator.get(\"platform_plugin_not_exit\") + PlatformPluginService.PLUGIN_DOWNLOAD_URL);\n }\n return pluginMetaInfo == null ? false : pluginMetaInfo.isThirdPartTemplateSupport();\n }", " public Platform getPlatform(String platformKey, String workspaceId) {\n IntegrationRequest integrationRequest = new IntegrationRequest();\n integrationRequest.setPlatform(platformKey);\n integrationRequest.setWorkspaceId(StringUtils.isBlank(workspaceId) ? SessionUtils.getCurrentWorkspaceId() : workspaceId);\n ServiceIntegration serviceIntegration = baseIntegrationService.get(integrationRequest);", " PlatformRequest pluginRequest = new PlatformRequest();", "", " pluginRequest.setIntegrationConfig(serviceIntegration.getConfiguration());\n Platform platform = getPluginManager().getPlatformByKey(platformKey, pluginRequest);\n if (platform == null) {\n MSException.throwException(Translator.get(\"platform_plugin_not_exit\") + PLUGIN_DOWNLOAD_URL);\n }\n return platform;\n }", " public Platform getPlatform(String platformKey) {\n return this.getPlatform(platformKey, null);\n }", "\n public static String getCompatibleProjectConfig(Project project) {\n String issueConfig = project.getIssueConfig();\n Map map = JSON.parseMap(issueConfig);\n compatibleProjectKey(map, \"jiraKey\", project.getJiraKey());\n compatibleProjectKey(map, \"tapdId\", project.getTapdId());\n compatibleProjectKey(map, \"azureDevopsId\", project.getAzureDevopsId());\n compatibleProjectKey(map, \"zentaoId\", project.getZentaoId());\n map.put(\"thirdPartTemplate\", project.getThirdPartTemplate());\n return JSON.toJSONString(map);\n }", " private static void compatibleProjectKey(Map map, String name, String compatibleValue) {\n if (map.get(name) == null || StringUtils.isBlank(map.get(name).toString())) {\n // 如果配置里面缺陷对应平台的项目ID则,即使用旧数据的项目ID\n map.put(name, compatibleValue);\n }\n }", " public static boolean isPluginPlatform(String platform) {\n if (StringUtils.equalsAnyIgnoreCase(platform,\n IssuesManagePlatform.Tapd.name(), IssuesManagePlatform.AzureDevops.name(),\n IssuesManagePlatform.Zentao.name(), IssuesManagePlatform.Local.name())) {\n return false;\n }\n return true;\n }", " public List<SelectOption> getPlatformOptions() {\n List<SelectOption> options = getPluginManager().getPluginMetaInfoList()\n .stream()\n .map(pluginMetaInfo -> new SelectOption(pluginMetaInfo.getLabel(), pluginMetaInfo.getKey()))\n .collect(Collectors.toList());\n List<ServiceIntegration> integrations = baseIntegrationService.getAll(SessionUtils.getCurrentWorkspaceId());\n // 过滤掉服务集成中没有的选项\n return options.stream()\n .filter(option ->\n integrations.stream()\n .filter(integration -> StringUtils.equals(integration.getPlatform(), option.getValue()))\n .collect(Collectors.toList()).size() > 0\n )\n .distinct()\n .collect(Collectors.toList());\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 113, 27, 22, 821, 90, 246, 337, 684, 42], "buggy_code_start_loc": [24, 109, 26, 18, 62, 90, 7, 9, 495, 3], "filenames": ["framework/gateway/src/main/java/io/metersphere/gateway/filter/SessionFilter.java", "framework/sdk-parent/xpack-interface/src/main/java/io/metersphere/xpack/track/issue/IssuesPlatform.java", "pom.xml", "test-track/backend/src/main/java/io/metersphere/controller/IssueProxyResourceController.java", "test-track/backend/src/main/java/io/metersphere/service/IssuesService.java", "test-track/backend/src/main/java/io/metersphere/service/PlatformPluginService.java", "test-track/backend/src/main/java/io/metersphere/service/issue/client/ZentaoClient.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/AbstractIssuePlatform.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/ZentaoPlatform.java", "test-track/backend/src/main/java/io/metersphere/service/wapper/IssueProxyResourceService.java"], "fixing_code_end_loc": [25, 113, 27, 23, 788, 92, 263, 343, 692, 42], "fixing_code_start_loc": [24, 109, 26, 18, 61, 91, 6, 8, 495, 3], "message": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:metersphere:metersphere:*:*:*:*:*:*:*:*", "matchCriteriaId": "218B4FEB-FDBE-46DB-A728-3CB89E37D5BA", "versionEndExcluding": "2.5.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds."}], "evaluatorComment": null, "id": "CVE-2022-23544", "lastModified": "2023-01-05T04:52:16.033", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.2, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 2.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-12-28T00:15:13.567", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/security/advisories/GHSA-vrv6-cg45-rmjj"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}, {"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, "type": "CWE-918"}
329
Determine whether the {function_name} code is vulnerable or not.
[ "package io.metersphere.service;", "import io.metersphere.commons.constants.IssuesManagePlatform;\nimport io.metersphere.commons.exception.MSException;\nimport io.metersphere.commons.utils.JSON;\nimport io.metersphere.i18n.Translator;\nimport io.metersphere.platform.api.Platform;\nimport io.metersphere.platform.api.PluginMetaInfo;\nimport io.metersphere.base.domain.PluginWithBLOBs;\nimport io.metersphere.base.domain.Project;\nimport io.metersphere.base.domain.ServiceIntegration;\nimport io.metersphere.commons.constants.PluginScenario;\nimport io.metersphere.commons.utils.SessionUtils;\nimport io.metersphere.platform.domain.PlatformRequest;\nimport io.metersphere.platform.domain.SelectOption;\nimport io.metersphere.platform.loader.PlatformPluginManager;\nimport io.metersphere.request.IntegrationRequest;\nimport io.metersphere.utils.PluginManagerUtil;\nimport org.apache.commons.lang3.StringUtils;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;", "import javax.annotation.Resource;\nimport java.io.InputStream;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;", "@Service\n@Transactional(rollbackFor = Exception.class)\npublic class PlatformPluginService {", " @Resource\n private BasePluginService basePluginService;\n @Resource\n private BaseIntegrationService baseIntegrationService;", " public static final String PLUGIN_DOWNLOAD_URL = \"https://github.com/metersphere/metersphere-platform-plugin\";", " private PlatformPluginManager pluginManager;", " public synchronized PlatformPluginManager getPluginManager() {\n if (pluginManager == null) {\n pluginManager = new PlatformPluginManager();\n }\n return pluginManager;\n }", " /**\n * 查询所有平台插件并加载\n */\n public void loadPlatFormPlugins() {\n List<PluginWithBLOBs> plugins = basePluginService.getPlugins(PluginScenario.platform.name());\n PluginManagerUtil.loadPlugins(getPluginManager(), plugins);\n }", " public void loadPlugin(String pluginId) {\n if (getPluginManager().getClassLoader(pluginId) == null) {\n // 如果没有加载才加载\n InputStream pluginJar = basePluginService.getPluginJar(pluginId);\n PluginManagerUtil.loadPlugin(pluginId, getPluginManager(), pluginJar);\n }\n }", " /**\n * 卸载插件\n * @param pluginId\n */\n public void unloadPlugin(String pluginId) {\n getPluginManager().deletePlugin(pluginId);\n }", " public boolean isThirdPartTemplateSupport(String platform) {\n if (StringUtils.isBlank(platform)) {\n return false;\n }\n PluginMetaInfo pluginMetaInfo = pluginManager.getPluginMetaInfoByKey(platform);\n if (PlatformPluginService.isPluginPlatform(platform) && pluginMetaInfo == null) {\n MSException.throwException(Translator.get(\"platform_plugin_not_exit\") + PlatformPluginService.PLUGIN_DOWNLOAD_URL);\n }\n return pluginMetaInfo == null ? false : pluginMetaInfo.isThirdPartTemplateSupport();\n }", " public Platform getPlatform(String platformKey, String workspaceId) {\n IntegrationRequest integrationRequest = new IntegrationRequest();\n integrationRequest.setPlatform(platformKey);\n integrationRequest.setWorkspaceId(StringUtils.isBlank(workspaceId) ? SessionUtils.getCurrentWorkspaceId() : workspaceId);\n ServiceIntegration serviceIntegration = baseIntegrationService.get(integrationRequest);", " PlatformRequest pluginRequest = new PlatformRequest();", " pluginRequest.setWorkspaceId(workspaceId);", " pluginRequest.setIntegrationConfig(serviceIntegration.getConfiguration());\n Platform platform = getPluginManager().getPlatformByKey(platformKey, pluginRequest);\n if (platform == null) {\n MSException.throwException(Translator.get(\"platform_plugin_not_exit\") + PLUGIN_DOWNLOAD_URL);\n }\n return platform;\n }", " public Platform getPlatform(String platformKey) {\n return this.getPlatform(platformKey, null);\n }", "\n public static String getCompatibleProjectConfig(Project project) {\n String issueConfig = project.getIssueConfig();\n Map map = JSON.parseMap(issueConfig);\n compatibleProjectKey(map, \"jiraKey\", project.getJiraKey());\n compatibleProjectKey(map, \"tapdId\", project.getTapdId());\n compatibleProjectKey(map, \"azureDevopsId\", project.getAzureDevopsId());\n compatibleProjectKey(map, \"zentaoId\", project.getZentaoId());\n map.put(\"thirdPartTemplate\", project.getThirdPartTemplate());\n return JSON.toJSONString(map);\n }", " private static void compatibleProjectKey(Map map, String name, String compatibleValue) {\n if (map.get(name) == null || StringUtils.isBlank(map.get(name).toString())) {\n // 如果配置里面缺陷对应平台的项目ID则,即使用旧数据的项目ID\n map.put(name, compatibleValue);\n }\n }", " public static boolean isPluginPlatform(String platform) {\n if (StringUtils.equalsAnyIgnoreCase(platform,\n IssuesManagePlatform.Tapd.name(), IssuesManagePlatform.AzureDevops.name(),\n IssuesManagePlatform.Zentao.name(), IssuesManagePlatform.Local.name())) {\n return false;\n }\n return true;\n }", " public List<SelectOption> getPlatformOptions() {\n List<SelectOption> options = getPluginManager().getPluginMetaInfoList()\n .stream()\n .map(pluginMetaInfo -> new SelectOption(pluginMetaInfo.getLabel(), pluginMetaInfo.getKey()))\n .collect(Collectors.toList());\n List<ServiceIntegration> integrations = baseIntegrationService.getAll(SessionUtils.getCurrentWorkspaceId());\n // 过滤掉服务集成中没有的选项\n return options.stream()\n .filter(option ->\n integrations.stream()\n .filter(integration -> StringUtils.equals(integration.getPlatform(), option.getValue()))\n .collect(Collectors.toList()).size() > 0\n )\n .distinct()\n .collect(Collectors.toList());\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 113, 27, 22, 821, 90, 246, 337, 684, 42], "buggy_code_start_loc": [24, 109, 26, 18, 62, 90, 7, 9, 495, 3], "filenames": ["framework/gateway/src/main/java/io/metersphere/gateway/filter/SessionFilter.java", "framework/sdk-parent/xpack-interface/src/main/java/io/metersphere/xpack/track/issue/IssuesPlatform.java", "pom.xml", "test-track/backend/src/main/java/io/metersphere/controller/IssueProxyResourceController.java", "test-track/backend/src/main/java/io/metersphere/service/IssuesService.java", "test-track/backend/src/main/java/io/metersphere/service/PlatformPluginService.java", "test-track/backend/src/main/java/io/metersphere/service/issue/client/ZentaoClient.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/AbstractIssuePlatform.java", "test-track/backend/src/main/java/io/metersphere/service/issue/platform/ZentaoPlatform.java", "test-track/backend/src/main/java/io/metersphere/service/wapper/IssueProxyResourceService.java"], "fixing_code_end_loc": [25, 113, 27, 23, 788, 92, 263, 343, 692, 42], "fixing_code_start_loc": [24, 109, 26, 18, 61, 91, 6, 8, 495, 3], "message": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:metersphere:metersphere:*:*:*:*:*:*:*:*", "matchCriteriaId": "218B4FEB-FDBE-46DB-A728-3CB89E37D5BA", "versionEndExcluding": "2.5.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "MeterSphere is a one-stop open source continuous testing platform, covering test management, interface testing, UI testing and performance testing. Versions prior to 2.5.0 are subject to a Server-Side Request Forgery that leads to Cross-Site Scripting. A Server-Side request forgery in `IssueProxyResourceService::getMdImageByUrl` allows an attacker to access internal resources, as well as executing JavaScript code in the context of Metersphere's origin by a victim of a reflected XSS. This vulnerability has been fixed in v2.5.0. There are no known workarounds."}], "evaluatorComment": null, "id": "CVE-2022-23544", "lastModified": "2023-01-05T04:52:16.033", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.2, "baseSeverity": "HIGH", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 2.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-12-28T00:15:13.567", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/metersphere/metersphere/security/advisories/GHSA-vrv6-cg45-rmjj"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-918"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}, {"lang": "en", "value": "CWE-918"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/metersphere/metersphere/commit/d0f95b50737c941b29d507a4cc3545f2dc6ab121"}, "type": "CWE-918"}
329