diff --git "a/validation.jsonl" "b/validation.jsonl" --- "a/validation.jsonl" +++ "b/validation.jsonl" @@ -42,7 +42,6 @@ {"code": " protected function tearDown()\n {\n Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, $this->originalTrustedHeaderName);\n }", "label_name": "Class", "label": 2} {"code": " function scan_page($parent_id) {\r\n global $db;\r\n\r\n $sections = $db->selectObjects('section','parent=' . $parent_id);\r\n $ret = '';\r\n foreach ($sections as $page) {\r\n $cLoc = serialize(expCore::makeLocation('container','@section' . $page->id));\r\n $ret .= scan_container($cLoc, $page->id);\r\n $ret .= scan_page($page->id);\r\n }\r\n return $ret;\r\n }\r", "label_name": "Base", "label": 1} {"code": " public static function hasChildren($i) {\r\n global $sections;\r\n\r\n if (($i + 1) >= count($sections)) return false;\r\n return ($sections[$i]->depth < $sections[$i + 1]->depth) ? true : false;\r\n }\r", "label_name": "Base", "label": 1} -{"code": " private function checkAuthenticationTag() {\n if ($this->authentication_tag === $this->calculateAuthenticationTag()) {\n return true;\n } else {\n throw new JOSE_Exception_UnexpectedAlgorithm('Invalid authentication tag');\n }\n }", "label_name": "CWE-310", "label": "CWE-310"} {"code": "function current_user_get_bug_filter( $p_project_id = null ) {\n\t$f_filter_string = gpc_get_string( 'filter', '' );\n\t$t_filter = '';\n\n\tif( !is_blank( $f_filter_string ) ) {\n\t\tif( is_numeric( $f_filter_string ) ) {\n\t\t\t$t_token = token_get_value( TOKEN_FILTER );\n\t\t\tif( null != $t_token ) {\n\t\t\t\t$t_filter = json_decode( $t_token, true );\n\t\t\t}\n\t\t} else {\n\t\t\t$t_filter = json_decode( $f_filter_string, true );\n\t\t}\n\t\t$t_filter = filter_ensure_valid_filter( $t_filter );\n\t} else if( !filter_is_cookie_valid() ) {\n\t\t$t_filter = filter_get_default();\n\t} else {\n\t\t$t_user_id = auth_get_current_user_id();\n\t\t$t_filter = user_get_bug_filter( $t_user_id, $p_project_id );\n\t}\n\n\treturn $t_filter;\n}", "label_name": "Class", "label": 2} {"code": " $section = new section($this->params);\r\n } else {\r\n notfoundController::handle_not_found();\r\n exit;\r\n }\r\n if (!empty($section->id)) {\r\n $check_id = $section->id;\r\n } else {\r\n $check_id = $section->parent;\r\n }\r\n if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $check_id))) {\r\n if (empty($section->id)) {\r\n $section->active = 1;\r\n $section->public = 1;\r\n if (!isset($section->parent)) {\r\n // This is another precaution. The parent attribute\r\n // should ALWAYS be set by the caller.\r\n //FJD - if that's the case, then we should die.\r\n notfoundController::handle_not_authorized();\r\n exit;\r\n //$section->parent = 0;\r\n }\r\n }\r\n assign_to_template(array(\r\n 'section' => $section,\r\n 'glyphs' => self::get_glyphs(),\r\n ));\r\n } else { // User does not have permission to manage sections. Throw a 403\r\n notfoundController::handle_not_authorized();\r\n }\r\n }\r", "label_name": "Class", "label": 2} {"code": " AND lang = '.protect($lang).'\r\n AND subtype IN ('.implode(\",\", array_map(function($k){ return protect($k);}, $subtypes)).')'\r\n );\r", "label_name": "Base", "label": 1} @@ -293,7 +292,6 @@ {"code": " foreach ($grpusers as $u) {\r\n $emails[$u->email] = trim(user::getUserAttribution($u->id));\r\n }\r", "label_name": "Base", "label": 1} {"code": " public function __construct(\n $status = 200,\n array $headers = [],\n $body = null,\n $version = '1.1',\n $reason = null\n ) {\n $this->statusCode = (int) $status;\n\n if ($body !== null) {\n $this->stream = stream_for($body);\n }\n\n $this->setHeaders($headers);\n if (!$reason && isset(self::$phrases[$this->statusCode])) {\n $this->reasonPhrase = self::$phrases[$status];\n } else {\n $this->reasonPhrase = (string) $reason;\n }\n\n $this->protocol = $version;\n }", "label_name": "Base", "label": 1} {"code": "function delete_bp($bp,$bdd){\n $sql = \"delete from bp where name = '\" . $bp . \"'\";\n $bdd->exec($sql);\n\n\t$sql = \"delete from bp_services where bp_name = '\" . $bp . \"'\";\n $bdd->exec($sql);\n\n\t$sql = \"delete from bp_links where bp_name = '\" . $bp . \"'\";\n\t$bdd->exec($sql);\n\t\n\t$sql = \"delete from bp_links where bp_link = '\" . $bp . \"'\";\n\t$bdd->exec($sql);\n}", "label_name": "Base", "label": 1} -{"code": " function checkHTTP($link, $get_body = false)\n {\n if (! function_exists('curl_init')) {\n return null;\n }\n $ch = curl_init($link);\n curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);\n curl_setopt($ch, CURLOPT_HEADER, 1);\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);\n curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);\n curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);\n curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);\n curl_setopt($ch, CURLOPT_USERAGENT, 'phpMyAdmin/' . PMA_VERSION);\n curl_setopt($ch, CURLOPT_TIMEOUT, 5);\n if (! defined('TESTSUITE')) {\n session_write_close();\n }\n $data = @curl_exec($ch);\n if (! defined('TESTSUITE')) {\n ini_set('session.use_only_cookies', '0');\n ini_set('session.use_cookies', '0');\n ini_set('session.use_trans_sid', '0');\n ini_set('session.cache_limiter', 'nocache');\n session_start();\n }\n if ($data === false) {\n return null;\n }\n $httpOk = 'HTTP/1.1 200 OK';\n $httpNotFound = 'HTTP/1.1 404 Not Found';\n\n if (substr($data, 0, strlen($httpOk)) === $httpOk) {\n return $get_body\n ? /*overload*/mb_substr(\n $data,\n /*overload*/mb_strpos($data, \"\\r\\n\\r\\n\") + 4\n )\n : true;\n }\n\n $httpNOK = substr(\n $data,\n 0,\n strlen($httpNotFound)\n );\n if ($httpNOK === $httpNotFound) {\n return false;\n }\n return null;\n }", "label_name": "CWE-310", "label": "CWE-310"} {"code": " private static function retrieveClosurePattern($pure, $closureName)\n {\n $pattern = '/';\n if (!$pure) {\n $pattern .= preg_quote(self::$registeredDelimiters[0]) . \"\\s*\";\n }\n $pattern .= \"$closureName\\(([a-z0-9,\\.\\s]+)\\)\";\n if (!$pure) {\n $pattern .= \"\\s*\" . preg_quote(self::$registeredDelimiters[1]);\n }\n return $pattern . \"/i\";\n }", "label_name": "Variant", "label": 0} {"code": "\tpublic function setHeadListAttributes( $attributes ) {\n\t\t$this->headListAttributes = \\Sanitizer::fixTagAttributes( $attributes, 'ul' );\n\t}", "label_name": "Class", "label": 2} {"code": " public function getFilePath($fileName = null)\n {\n if ($fileName === null) {\n $fileName = $this->fileName;\n }\n\n return $this->theme->getPath().'/'.$this->dirName.'/'.$fileName;\n }", "label_name": "Class", "label": 2} @@ -626,7 +624,6 @@ {"code": "PostgreSQL.prototype.buildExpression = function(columnName, operator,\n operatorValue, propertyDefinition) {\n switch (operator) {\n case 'like':\n return new ParameterizedSQL(columnName + \"::TEXT LIKE ? ESCAPE E'\\\\\\\\'\",\n [operatorValue]);\n case 'ilike':\n return new ParameterizedSQL(columnName + \"::TEXT ILIKE ? ESCAPE E'\\\\\\\\'\",\n [operatorValue]);\n case 'nlike':\n return new ParameterizedSQL(columnName + \"::TEXT NOT LIKE ? ESCAPE E'\\\\\\\\'\",\n [operatorValue]);\n case 'nilike':\n return new ParameterizedSQL(columnName + \"::TEXT NOT ILIKE ? ESCAPE E'\\\\\\\\'\",\n [operatorValue]);\n case 'regexp':\n if (operatorValue.global)\n g.warn('{{PostgreSQL}} regex syntax does not respect the {{`g`}} flag');\n\n if (operatorValue.multiline)\n g.warn('{{PostgreSQL}} regex syntax does not respect the {{`m`}} flag');\n\n const regexOperator = operatorValue.ignoreCase ? ' ~* ?' : ' ~ ?';\n return new ParameterizedSQL(columnName + regexOperator,\n [operatorValue.source]);\n case 'contains':\n return new ParameterizedSQL(columnName + ' @> array[' + operatorValue.map((v) => `'${v}'`) + ']::'\n + propertyDefinition.postgresql.dataType);\n case 'match':\n return new ParameterizedSQL(`to_tsvector(${columnName}) @@ to_tsquery('${operatorValue}')`);\n default:\n // invoke the base implementation of `buildExpression`\n return this.invokeSuper('buildExpression', columnName, operator,\n operatorValue, propertyDefinition);\n }\n};", "label_name": "Base", "label": 1} {"code": " fetch: function () {\n var data = Dep.prototype.fetch.call(this);\n data.translatedOptions = {};\n (data[this.name] || []).forEach(function (value) {\n data.translatedOptions[value] = this.$el.find('input[data-name=\"translatedValue\"][data-value=\"'+value+'\"]').val() || value;\n }, this);\n\n return data;\n }", "label_name": "Base", "label": 1} {"code": "1?0:Ua.y*ia);this.shape.bounds.height=ma.height-(Ta==Ma.length-1?0:(Ua.height+Ua.y)*ia)}this.shape.redraw()}};var Ya=!1;za.setPosition=function(Ua,eb,jb){La=Math.max(Graph.minTableColumnWidth-Ea.width,eb.x-Ua.x-Ea.width);Ya=mxEvent.isShiftDown(jb.getEvent());null==Da||Ya||(La=Math.min(La,Da.width-Graph.minTableColumnWidth))};za.execute=function(Ua){if(0!=La)T.setTableColumnWidth(this.state.cell,La,Ya);else if(!M.blockDelayedSelection){var eb=T.getCellAt(Ua.getGraphX(),Ua.getGraphY())||ma.cell;T.graphHandler.selectCellForEvent(eb,", "label_name": "Class", "label": 2} -{"code": "WebUtil.createCookie = function(name,value,days) {\n var date, expires;\n if (days) {\n date = new Date();\n date.setTime(date.getTime()+(days*24*60*60*1000));\n expires = \"; expires=\"+date.toGMTString();\n }\n else {\n expires = \"\";\n }\n document.cookie = name+\"=\"+value+expires+\"; path=/\";\n};", "label_name": "CWE-310", "label": "CWE-310"} {"code": "S&&S(M)}}))}catch(L){null!=S&&S(L)}}),N,sa)}catch(Pa){null!=S&&S(Pa)}};Editor.crcTable=[];for(var D=0;256>D;D++)for(var t=D,F=0;8>F;F++)t=1==(t&1)?3988292384^t>>>1:t>>>1,Editor.crcTable[D]=t;Editor.updateCRC=function(u,J,N,W){for(var S=0;S>>8;return u};Editor.crc32=function(u){for(var J=-1,N=0;N>>8^Editor.crcTable[(J^u.charCodeAt(N))&255];return(J^-1)>>>0};Editor.writeGraphModelToPng=function(u,J,N,W,S){function P(sa,Ba){var ta=", "label_name": "Base", "label": 1} {"code": "Client.prototype.openssh_noMoreSessions = function(cb) {\n if (!this._sock\n || !this._sock.writable\n || !this._sshstream\n || !this._sshstream.writable)\n throw new Error('Not connected');\n\n var wantReply = (typeof cb === 'function');\n\n if (!this.config.strictVendor\n || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {\n if (wantReply) {\n this._callbacks.push(function(had_err) {\n if (had_err) {\n return cb(had_err !== true\n ? had_err\n : new Error('Unable to disable future sessions'));\n }\n\n cb();\n });\n }\n\n return this._sshstream.openssh_noMoreSessions(wantReply);\n } else if (wantReply) {\n process.nextTick(function() {\n cb(new Error('strictVendor enabled and server is not OpenSSH or compatible version'));\n });\n }\n\n return true;\n};", "label_name": "Base", "label": 1} {"code": "A||\"snip\"==B||\"default\"==B&&\"snip\"==A?c.lineTo(p-K,ha+.5*K):(\"invRound\"==B||\"default\"==B&&\"invRound\"==A||\"fold\"==B||\"default\"==B&&\"fold\"==A)&&c.lineTo(p-K,ha+K):c.lineTo(p,K)};Ea.prototype.moveNWInner=function(c,l,x,p,v,A,B,ha,K,xa,na){xa||na?!xa&&na?c.moveTo(K,0):xa&&!na?c.moveTo(0,K):\"square\"==B||\"default\"==B&&\"square\"==A?c.moveTo(K,K):\"rounded\"==B||\"default\"==B&&\"rounded\"==A||\"snip\"==B||\"default\"==B&&\"snip\"==A?c.moveTo(K,ha+.5*K):(\"invRound\"==B||\"default\"==B&&\"invRound\"==A||\"fold\"==B||\"default\"==\nB&&\"fold\"==A)&&c.moveTo(K,ha+K):c.moveTo(0,0)};Ea.prototype.lineNWInner=function(c,l,x,p,v,A,B,ha,K,xa,na){xa||na?!xa&&na?c.lineTo(K,0):xa&&!na?c.lineTo(0,K):\"square\"==B||\"default\"==B&&\"square\"==A?c.lineTo(K,K):\"rounded\"==B||\"default\"==B&&\"rounded\"==A||\"snip\"==B||\"default\"==B&&\"snip\"==A?c.lineTo(K,ha+.5*K):(\"invRound\"==B||\"default\"==B&&\"invRound\"==A||\"fold\"==B||\"default\"==B&&\"fold\"==A)&&c.lineTo(K,ha+K):c.lineTo(0,0)};Ea.prototype.paintFolds=function(c,l,x,p,v,A,B,ha,K,xa,na,$a,ib,db,Ga){if(\"fold\"==", "label_name": "Class", "label": 2} @@ -950,7 +947,6 @@ {"code": "static int jas_iccgetuint16(jas_stream_t *in, jas_iccuint16_t *val)\n{\n\tulonglong tmp;\n\tif (jas_iccgetuint(in, 2, &tmp))\n\t\treturn -1;\n\t*val = tmp;\n\treturn 0;\n}", "label_name": "Base", "label": 1} {"code": "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);\n\n\tif (!s)\n\t\treturn NULL;\n\n\tif (!rdg_read_all(rdg->tlsOut, Stream_Buffer(s), header))\n\t{\n\t\tStream_Free(s, TRUE);\n\t\treturn NULL;\n\t}\n\n\tStream_Seek(s, 4);\n\tStream_Read_UINT32(s, packetLength);\n\n\tif ((packetLength > INT_MAX) || !Stream_EnsureCapacity(s, packetLength))\n\t{\n\t\tStream_Free(s, TRUE);\n\t\treturn NULL;\n\t}\n\n\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}\n\n\tStream_SetLength(s, packetLength);\n\treturn s;\n}", "label_name": "Base", "label": 1} {"code": "static int __vcpu_run(struct kvm_vcpu *vcpu)\n{\n\tint r;\n\tstruct kvm *kvm = vcpu->kvm;\n\n\tvcpu->srcu_idx = srcu_read_lock(&kvm->srcu);\n\tr = vapic_enter(vcpu);\n\tif (r) {\n\t\tsrcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);\n\t\treturn r;\n\t}\n\n\tr = 1;\n\twhile (r > 0) {\n\t\tif (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&\n\t\t !vcpu->arch.apf.halted)\n\t\t\tr = vcpu_enter_guest(vcpu);\n\t\telse {\n\t\t\tsrcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);\n\t\t\tkvm_vcpu_block(vcpu);\n\t\t\tvcpu->srcu_idx = srcu_read_lock(&kvm->srcu);\n\t\t\tif (kvm_check_request(KVM_REQ_UNHALT, vcpu)) {\n\t\t\t\tkvm_apic_accept_events(vcpu);\n\t\t\t\tswitch(vcpu->arch.mp_state) {\n\t\t\t\tcase KVM_MP_STATE_HALTED:\n\t\t\t\t\tvcpu->arch.pv.pv_unhalted = false;\n\t\t\t\t\tvcpu->arch.mp_state =\n\t\t\t\t\t\tKVM_MP_STATE_RUNNABLE;\n\t\t\t\tcase KVM_MP_STATE_RUNNABLE:\n\t\t\t\t\tvcpu->arch.apf.halted = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase KVM_MP_STATE_INIT_RECEIVED:\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tr = -EINTR;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (r <= 0)\n\t\t\tbreak;\n\n\t\tclear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);\n\t\tif (kvm_cpu_has_pending_timer(vcpu))\n\t\t\tkvm_inject_pending_timer_irqs(vcpu);\n\n\t\tif (dm_request_for_irq_injection(vcpu)) {\n\t\t\tr = -EINTR;\n\t\t\tvcpu->run->exit_reason = KVM_EXIT_INTR;\n\t\t\t++vcpu->stat.request_irq_exits;\n\t\t}\n\n\t\tkvm_check_async_pf_completion(vcpu);\n\n\t\tif (signal_pending(current)) {\n\t\t\tr = -EINTR;\n\t\t\tvcpu->run->exit_reason = KVM_EXIT_INTR;\n\t\t\t++vcpu->stat.signal_exits;\n\t\t}\n\t\tif (need_resched()) {\n\t\t\tsrcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);\n\t\t\tkvm_resched(vcpu);\n\t\t\tvcpu->srcu_idx = srcu_read_lock(&kvm->srcu);\n\t\t}\n\t}\n\n\tsrcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);\n\n\tvapic_exit(vcpu);\n\n\treturn r;\n}", "label_name": "Class", "label": 2} -{"code": "static inline void sem_putref(struct sem_array *sma)\n{\n\tipc_lock_by_ptr(&sma->sem_perm);\n\tipc_rcu_putref(sma);\n\tipc_unlock(&(sma)->sem_perm);\n}", "label_name": "CWE-189", "label": "CWE-189"} {"code": "int get_evtchn_to_irq(evtchn_port_t evtchn)\n{\n\tif (evtchn >= xen_evtchn_max_channels())\n\t\treturn -1;\n\tif (evtchn_to_irq[EVTCHN_ROW(evtchn)] == NULL)\n\t\treturn -1;\n\treturn evtchn_to_irq[EVTCHN_ROW(evtchn)][EVTCHN_COL(evtchn)];\n}", "label_name": "Class", "label": 2} {"code": "NOEXPORT void tray_update(const int num) {\n NOTIFYICONDATA nid;\n static ICON_TYPE previous_icon=ICON_NONE;\n ICON_TYPE current_icon;\n LPTSTR tip;\n\n if(!global_options.option.taskbar) { /* currently disabled */\n tray_delete(); /* remove the taskbark icon if exists */\n return;\n }\n if(!tray_menu_handle) /* initialize taskbar */\n tray_menu_handle=LoadMenu(ghInst, MAKEINTRESOURCE(IDM_TRAYMENU));\n if(!tray_menu_handle) {\n ioerror(\"LoadMenu\");\n return;\n }\n if(cmdline.service)\n EnableMenuItem(tray_menu_handle, IDM_EDIT_CONFIG, MF_GRAYED);\n\n ZeroMemory(&nid, sizeof nid);\n nid.cbSize=sizeof nid;\n nid.uID=1; /* application-defined icon ID */\n nid.uFlags=NIF_MESSAGE|NIF_TIP;\n nid.uCallbackMessage=WM_SYSTRAY; /* notification message */\n nid.hWnd=hwnd; /* window to receive notifications */\n if(num<0) {\n tip=str_tprintf(TEXT(\"Server is down\"));\n current_icon=ICON_ERROR;\n } else if(num>0) {\n tip=str_tprintf(TEXT(\"%d active session(s)\"), num);\n current_icon=ICON_ACTIVE;\n } else {\n tip=str_tprintf(TEXT(\"Server is idle\"));\n current_icon=ICON_IDLE;\n }\n _tcsncpy(nid.szTip, tip, 63);\n nid.szTip[63]=TEXT('\\0');\n str_free(tip);\n nid.hIcon=global_options.icon[current_icon];\n if(current_icon!=previous_icon) {\n nid.uFlags|=NIF_ICON;\n previous_icon=current_icon;\n }\n if(Shell_NotifyIcon(NIM_MODIFY, &nid)) /* modify tooltip */\n return; /* OK: taskbar icon exists */\n /* tooltip update failed - try to create the icon */\n nid.uFlags|=NIF_ICON;\n Shell_NotifyIcon(NIM_ADD, &nid);\n}", "label_name": "Base", "label": 1} {"code": "BOOL update_write_cache_bitmap_v3_order(wStream* s, CACHE_BITMAP_V3_ORDER* cache_bitmap_v3,\n UINT16* flags)\n{\n\tBYTE bitsPerPixelId;\n\tBITMAP_DATA_EX* bitmapData;\n\n\tif (!Stream_EnsureRemainingCapacity(\n\t s, update_approximate_cache_bitmap_v3_order(cache_bitmap_v3, flags)))\n\t\treturn FALSE;\n\n\tbitmapData = &cache_bitmap_v3->bitmapData;\n\tbitsPerPixelId = BPP_CBR23[cache_bitmap_v3->bpp];\n\t*flags = (cache_bitmap_v3->cacheId & 0x00000003) |\n\t ((cache_bitmap_v3->flags << 7) & 0x0000FF80) | ((bitsPerPixelId << 3) & 0x00000078);\n\tStream_Write_UINT16(s, cache_bitmap_v3->cacheIndex); /* cacheIndex (2 bytes) */\n\tStream_Write_UINT32(s, cache_bitmap_v3->key1); /* key1 (4 bytes) */\n\tStream_Write_UINT32(s, cache_bitmap_v3->key2); /* key2 (4 bytes) */\n\tStream_Write_UINT8(s, bitmapData->bpp);\n\tStream_Write_UINT8(s, 0); /* reserved1 (1 byte) */\n\tStream_Write_UINT8(s, 0); /* reserved2 (1 byte) */\n\tStream_Write_UINT8(s, bitmapData->codecID); /* codecID (1 byte) */\n\tStream_Write_UINT16(s, bitmapData->width); /* width (2 bytes) */\n\tStream_Write_UINT16(s, bitmapData->height); /* height (2 bytes) */\n\tStream_Write_UINT32(s, bitmapData->length); /* length (4 bytes) */\n\tStream_Write(s, bitmapData->data, bitmapData->length);\n\treturn TRUE;\n}", "label_name": "Base", "label": 1} @@ -972,7 +968,6 @@ {"code": "_archive_write_disk_close(struct archive *_a)\n{\n\tstruct archive_write_disk *a = (struct archive_write_disk *)_a;\n\tstruct fixup_entry *next, *p;\n\tint fd, ret;\n\n\tarchive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,\n\t ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,\n\t \"archive_write_disk_close\");\n\tret = _archive_write_disk_finish_entry(&a->archive);\n\n\t/* Sort dir list so directories are fixed up in depth-first order. */\n\tp = sort_dir_list(a->fixup_list);\n\n\twhile (p != NULL) {\n\t\tfd = -1;\n\t\ta->pst = NULL; /* Mark stat cache as out-of-date. */\n\t\tif (p->fixup &\n\t\t (TODO_TIMES | TODO_MODE_BASE | TODO_ACLS | TODO_FFLAGS)) {\n\t\t\tfd = open(p->name,\n\t\t\t O_WRONLY | O_BINARY | O_NOFOLLOW | O_CLOEXEC);\n\t\t}\n\t\tif (p->fixup & TODO_TIMES) {\n\t\t\tset_times(a, fd, p->mode, p->name,\n\t\t\t p->atime, p->atime_nanos,\n\t\t\t p->birthtime, p->birthtime_nanos,\n\t\t\t p->mtime, p->mtime_nanos,\n\t\t\t p->ctime, p->ctime_nanos);\n\t\t}\n\t\tif (p->fixup & TODO_MODE_BASE) {\n#ifdef HAVE_FCHMOD\n\t\t\tif (fd >= 0)\n\t\t\t\tfchmod(fd, p->mode);\n\t\t\telse\n#endif\n\t\t\tchmod(p->name, p->mode);\n\t\t}\n\t\tif (p->fixup & TODO_ACLS)\n\t\t\tarchive_write_disk_set_acls(&a->archive, fd,\n\t\t\t p->name, &p->acl, p->mode);\n\t\tif (p->fixup & TODO_FFLAGS)\n\t\t\tset_fflags_platform(a, fd, p->name,\n\t\t\t p->mode, p->fflags_set, 0);\n\t\tif (p->fixup & TODO_MAC_METADATA)\n\t\t\tset_mac_metadata(a, p->name, p->mac_metadata,\n\t\t\t\t\t p->mac_metadata_size);\n\t\tnext = p->next;\n\t\tarchive_acl_clear(&p->acl);\n\t\tfree(p->mac_metadata);\n\t\tfree(p->name);\n\t\tif (fd >= 0)\n\t\t\tclose(fd);\n\t\tfree(p);\n\t\tp = next;\n\t}\n\ta->fixup_list = NULL;\n\treturn (ret);\n}", "label_name": "Base", "label": 1} {"code": "static void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)\n{\n\tconst struct sched_class *class;\n\n\tif (p->sched_class == rq->curr->sched_class) {\n\t\trq->curr->sched_class->check_preempt_curr(rq, p, flags);\n\t} else {\n\t\tfor_each_class(class) {\n\t\t\tif (class == rq->curr->sched_class)\n\t\t\t\tbreak;\n\t\t\tif (class == p->sched_class) {\n\t\t\t\tresched_task(rq->curr);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\n\t * A queue event has occurred, and we're going to schedule. In\n\t * this case, we can save a useless back to back clock update.\n\t */\n\tif (test_tsk_need_resched(rq->curr))\n\t\trq->skip_clock_update = 1;\n}", "label_name": "Base", "label": 1} {"code": "struct lib_t* MACH0_(get_libs)(struct MACH0_(obj_t)* bin) {\n\tstruct lib_t *libs;\n\tint i;\n\n\tif (!bin->nlibs)\n\t\treturn NULL;\n\tif (!(libs = calloc ((bin->nlibs + 1), sizeof(struct lib_t))))\n\t\treturn NULL;\n\tfor (i = 0; i < bin->nlibs; i++) {\n\t\tstrncpy (libs[i].name, bin->libs[i], R_BIN_MACH0_STRING_LENGTH);\n\t\tlibs[i].name[R_BIN_MACH0_STRING_LENGTH-1] = '\\0';\n\t\tlibs[i].last = 0;\n\t}\n\tlibs[i].last = 1;\n\treturn libs;\n}", "label_name": "Variant", "label": 0} -{"code": "static void iov_fault_in_pages_read(struct iovec *iov, unsigned long len)\n{\n\twhile (!iov->iov_len)\n\t\tiov++;\n\n\twhile (len > 0) {\n\t\tunsigned long this_len;\n\n\t\tthis_len = min_t(unsigned long, len, iov->iov_len);\n\t\tfault_in_pages_readable(iov->iov_base, this_len);\n\t\tlen -= this_len;\n\t\tiov++;\n\t}\n}", "label_name": "CWE-17", "label": "CWE-17"} {"code": "void common_timer_get(struct k_itimer *timr, struct itimerspec64 *cur_setting)\n{\n\tconst struct k_clock *kc = timr->kclock;\n\tktime_t now, remaining, iv;\n\tstruct timespec64 ts64;\n\tbool sig_none;\n\n\tsig_none = timr->it_sigev_notify == SIGEV_NONE;\n\tiv = timr->it_interval;\n\n\t/* interval timer ? */\n\tif (iv) {\n\t\tcur_setting->it_interval = ktime_to_timespec64(iv);\n\t} else if (!timr->it_active) {\n\t\t/*\n\t\t * SIGEV_NONE oneshot timers are never queued. Check them\n\t\t * below.\n\t\t */\n\t\tif (!sig_none)\n\t\t\treturn;\n\t}\n\n\t/*\n\t * The timespec64 based conversion is suboptimal, but it's not\n\t * worth to implement yet another callback.\n\t */\n\tkc->clock_get(timr->it_clock, &ts64);\n\tnow = timespec64_to_ktime(ts64);\n\n\t/*\n\t * When a requeue is pending or this is a SIGEV_NONE timer move the\n\t * expiry time forward by intervals, so expiry is > now.\n\t */\n\tif (iv && (timr->it_requeue_pending & REQUEUE_PENDING || sig_none))\n\t\ttimr->it_overrun += (int)kc->timer_forward(timr, now);\n\n\tremaining = kc->timer_remaining(timr, now);\n\t/* Return 0 only, when the timer is expired and not pending */\n\tif (remaining <= 0) {\n\t\t/*\n\t\t * A single shot SIGEV_NONE timer must return 0, when\n\t\t * it is expired !\n\t\t */\n\t\tif (!sig_none)\n\t\t\tcur_setting->it_value.tv_nsec = 1;\n\t} else {\n\t\tcur_setting->it_value = ktime_to_timespec64(remaining);\n\t}\n}", "label_name": "Base", "label": 1} {"code": "static irqreturn_t snd_msnd_interrupt(int irq, void *dev_id)\n{\n\tstruct snd_msnd *chip = dev_id;\n\tvoid *pwDSPQData = chip->mappedbase + DSPQ_DATA_BUFF;\n\n\t/* Send ack to DSP */\n\t/* inb(chip->io + HP_RXL); */\n\n\t/* Evaluate queued DSP messages */\n\twhile (readw(chip->DSPQ + JQS_wTail) != readw(chip->DSPQ + JQS_wHead)) {\n\t\tu16 wTmp;\n\n\t\tsnd_msnd_eval_dsp_msg(chip,\n\t\t\treadw(pwDSPQData + 2 * readw(chip->DSPQ + JQS_wHead)));\n\n\t\twTmp = readw(chip->DSPQ + JQS_wHead) + 1;\n\t\tif (wTmp > readw(chip->DSPQ + JQS_wSize))\n\t\t\twritew(0, chip->DSPQ + JQS_wHead);\n\t\telse\n\t\t\twritew(wTmp, chip->DSPQ + JQS_wHead);\n\t}\n\t/* Send ack to DSP */\n\tinb(chip->io + HP_RXL);\n\treturn IRQ_HANDLED;\n}", "label_name": "Base", "label": 1} {"code": "static inline struct old_rng_alg *crypto_old_rng_alg(struct crypto_rng *tfm)\n{\n\treturn &crypto_rng_tfm(tfm)->__crt_alg->cra_rng;\n}", "label_name": "Base", "label": 1} @@ -995,24 +990,20 @@ {"code": "flatpak_proxy_client_init (FlatpakProxyClient *client)\n{\n init_side (client, &client->client_side);\n init_side (client, &client->bus_side);\n\n client->auth_end_offset = AUTH_END_INIT_OFFSET;\n client->rewrite_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_object_unref);\n client->get_owner_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_free);\n client->unique_id_policy = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);\n}", "label_name": "Class", "label": 2} {"code": "file_extension(const char *s)\t/* I - Filename or URL */\n{\n const char\t*extension;\t/* Pointer to directory separator */\n static char\tbuf[1024];\t/* Buffer for files with targets */\n\n\n if (s == NULL)\n return (NULL);\n else if (!strncmp(s, \"data:image/bmp;\", 15))\n return (\"bmp\");\n else if (!strncmp(s, \"data:image/gif;\", 15))\n return (\"gif\");\n else if (!strncmp(s, \"data:image/jpeg;\", 16))\n return (\"jpg\");\n else if (!strncmp(s, \"data:image/png;\", 15))\n return (\"png\");\n else if ((extension = strrchr(s, '/')) != NULL)\n extension ++;\n else if ((extension = strrchr(s, '\\\\')) != NULL)\n extension ++;\n else\n extension = s;\n\n if ((extension = strrchr(extension, '.')) == NULL)\n return (\"\");\n else\n extension ++;\n\n if (strchr(extension, '#') == NULL)\n return (extension);\n\n strlcpy(buf, extension, sizeof(buf));\n\n *(char *)strchr(buf, '#') = '\\0';\n\n return (buf);\n}", "label_name": "Base", "label": 1} {"code": "jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab)\n{\n\tjpc_streamlist_t *streams;\n\tuchar *dataptr;\n\tuint_fast32_t datacnt;\n\tuint_fast32_t tpcnt;\n\tjpc_ppxstabent_t *ent;\n\tint entno;\n\tjas_stream_t *stream;\n\tint n;\n\n\tif (!(streams = jpc_streamlist_create())) {\n\t\tgoto error;\n\t}\n\n\tif (!tab->numents) {\n\t\treturn streams;\n\t}\n\n\tentno = 0;\n\tent = tab->ents[entno];\n\tdataptr = ent->data;\n\tdatacnt = ent->len;\n\tfor (;;) {\n\n\t\t/* Get the length of the packet header data for the current\n\t\t tile-part. */\n\t\tif (datacnt < 4) {\n\t\t\tgoto error;\n\t\t}\n\t\tif (!(stream = jas_stream_memopen(0, 0))) {\n\t\t\tgoto error;\n\t\t}\n\t\tif (jpc_streamlist_insert(streams, jpc_streamlist_numstreams(streams),\n\t\t stream)) {\n\t\t\tgoto error;\n\t\t}\n\t\ttpcnt = (dataptr[0] << 24) | (dataptr[1] << 16) | (dataptr[2] << 8)\n\t\t | dataptr[3];\n\t\tdatacnt -= 4;\n\t\tdataptr += 4;\n\n\t\t/* Get the packet header data for the current tile-part. */\n\t\twhile (tpcnt) {\n\t\t\tif (!datacnt) {\n\t\t\t\tif (++entno >= tab->numents) {\n\t\t\t\t\tgoto error;\n\t\t\t\t}\n\t\t\t\tent = tab->ents[entno];\n\t\t\t\tdataptr = ent->data;\n\t\t\t\tdatacnt = ent->len;\n\t\t\t}\n\t\t\tn = JAS_MIN(tpcnt, datacnt);\n\t\t\tif (jas_stream_write(stream, dataptr, n) != n) {\n\t\t\t\tgoto error;\n\t\t\t}\n\t\t\ttpcnt -= n;\n\t\t\tdataptr += n;\n\t\t\tdatacnt -= n;\n\t\t}\n\t\tjas_stream_rewind(stream);\n\t\tif (!datacnt) {\n\t\t\tif (++entno >= tab->numents) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tent = tab->ents[entno];\n\t\t\tdataptr = ent->data;\n\t\t\tdatacnt = ent->len;\n\t\t}\n\t}\n\n\treturn streams;\n\nerror:\n\tif (streams) {\n\t\tjpc_streamlist_destroy(streams);\n\t}\n\treturn 0;\n}", "label_name": "Class", "label": 2} -{"code": "static void recalculate_apic_map(struct kvm *kvm)\n{\n\tstruct kvm_apic_map *new, *old = NULL;\n\tstruct kvm_vcpu *vcpu;\n\tint i;\n\n\tnew = kzalloc(sizeof(struct kvm_apic_map), GFP_KERNEL);\n\n\tmutex_lock(&kvm->arch.apic_map_lock);\n\n\tif (!new)\n\t\tgoto out;\n\n\tnew->ldr_bits = 8;\n\t/* flat mode is default */\n\tnew->cid_shift = 8;\n\tnew->cid_mask = 0;\n\tnew->lid_mask = 0xff;\n\n\tkvm_for_each_vcpu(i, vcpu, kvm) {\n\t\tstruct kvm_lapic *apic = vcpu->arch.apic;\n\t\tu16 cid, lid;\n\t\tu32 ldr;\n\n\t\tif (!kvm_apic_present(vcpu))\n\t\t\tcontinue;\n\n\t\t/*\n\t\t * All APICs have to be configured in the same mode by an OS.\n\t\t * We take advatage of this while building logical id loockup\n\t\t * table. After reset APICs are in xapic/flat mode, so if we\n\t\t * find apic with different setting we assume this is the mode\n\t\t * OS wants all apics to be in; build lookup table accordingly.\n\t\t */\n\t\tif (apic_x2apic_mode(apic)) {\n\t\t\tnew->ldr_bits = 32;\n\t\t\tnew->cid_shift = 16;\n\t\t\tnew->cid_mask = new->lid_mask = 0xffff;\n\t\t} else if (kvm_apic_sw_enabled(apic) &&\n\t\t\t\t!new->cid_mask /* flat mode */ &&\n\t\t\t\tkvm_apic_get_reg(apic, APIC_DFR) == APIC_DFR_CLUSTER) {\n\t\t\tnew->cid_shift = 4;\n\t\t\tnew->cid_mask = 0xf;\n\t\t\tnew->lid_mask = 0xf;\n\t\t}\n\n\t\tnew->phys_map[kvm_apic_id(apic)] = apic;\n\n\t\tldr = kvm_apic_get_reg(apic, APIC_LDR);\n\t\tcid = apic_cluster_id(new, ldr);\n\t\tlid = apic_logical_id(new, ldr);\n\n\t\tif (lid)\n\t\t\tnew->logical_map[cid][ffs(lid) - 1] = apic;\n\t}\nout:\n\told = rcu_dereference_protected(kvm->arch.apic_map,\n\t\t\tlockdep_is_held(&kvm->arch.apic_map_lock));\n\trcu_assign_pointer(kvm->arch.apic_map, new);\n\tmutex_unlock(&kvm->arch.apic_map_lock);\n\n\tif (old)\n\t\tkfree_rcu(old, rcu);\n\n\tkvm_vcpu_request_scan_ioapic(kvm);\n}", "label_name": "CWE-189", "label": "CWE-189"} {"code": "static int adts_decode_extradata(AVFormatContext *s, ADTSContext *adts, const uint8_t *buf, int size)\n{\n GetBitContext gb;\n PutBitContext pb;\n MPEG4AudioConfig m4ac;\n int off;\n\n init_get_bits(&gb, buf, size * 8);\n off = avpriv_mpeg4audio_get_config2(&m4ac, buf, size, 1, s);\n if (off < 0)\n return off;\n skip_bits_long(&gb, off);\n adts->objecttype = m4ac.object_type - 1;\n adts->sample_rate_index = m4ac.sampling_index;\n adts->channel_conf = m4ac.chan_config;\n\n if (adts->objecttype > 3U) {\n av_log(s, AV_LOG_ERROR, \"MPEG-4 AOT %d is not allowed in ADTS\\n\", adts->objecttype+1);\n return AVERROR_INVALIDDATA;\n }\n if (adts->sample_rate_index == 15) {\n av_log(s, AV_LOG_ERROR, \"Escape sample rate index illegal in ADTS\\n\");\n return AVERROR_INVALIDDATA;\n }\n if (get_bits(&gb, 1)) {\n av_log(s, AV_LOG_ERROR, \"960/120 MDCT window is not allowed in ADTS\\n\");\n return AVERROR_INVALIDDATA;\n }\n if (get_bits(&gb, 1)) {\n av_log(s, AV_LOG_ERROR, \"Scalable configurations are not allowed in ADTS\\n\");\n return AVERROR_INVALIDDATA;\n }\n if (get_bits(&gb, 1)) {\n av_log(s, AV_LOG_ERROR, \"Extension flag is not allowed in ADTS\\n\");\n return AVERROR_INVALIDDATA;\n }\n if (!adts->channel_conf) {\n init_put_bits(&pb, adts->pce_data, MAX_PCE_SIZE);\n\n put_bits(&pb, 3, 5); //ID_PCE\n adts->pce_size = (ff_copy_pce_data(&pb, &gb) + 3) / 8;\n flush_put_bits(&pb);\n }\n\n adts->write_adts = 1;\n\n return 0;\n}", "label_name": "Base", "label": 1} {"code": "void dhcpAddOption(DhcpMessage *message, uint8_t optionCode,\n const void *optionValue, size_t optionLen)\n{\n size_t n;\n DhcpOption *option;\n\n //Point to the very first option\n n = 0;\n\n //Parse DHCP options\n while(1)\n {\n //Point to the current option\n option = (DhcpOption *) (message->options + n);\n\n //End option detected?\n if(option->code == DHCP_OPT_END)\n break;\n\n //Jump to next the next option\n n += sizeof(DhcpOption) + option->length;\n }\n\n //Sanity check\n if(optionLen <= UINT8_MAX)\n {\n //Point to the buffer where the option is to be written\n option = (DhcpOption *) (message->options + n);\n\n //Option code\n option->code = optionCode;\n //Option length\n option->length = (uint8_t) optionLen;\n //Option value\n osMemcpy(option->value, optionValue, optionLen);\n\n //Jump to next the next option\n n += sizeof(DhcpOption) + option->length;\n\n //Point to the buffer where the option is to be written\n option = (DhcpOption *) (message->options + n);\n\n //Always terminate the options field with 255\n option->code = DHCP_OPT_END;\n }\n}", "label_name": "Class", "label": 2} {"code": "void pjsua_init_tpselector(pjsua_transport_id tp_id,\n\t\t\t pjsip_tpselector *sel)\n{\n pjsua_transport_data *tpdata;\n unsigned flag;\n\n pj_bzero(sel, sizeof(*sel));\n if (tp_id == PJSUA_INVALID_ID)\n\treturn;\n\n pj_assert(tp_id >= 0 && tp_id < (int)PJ_ARRAY_SIZE(pjsua_var.tpdata));\n tpdata = &pjsua_var.tpdata[tp_id];\n\n flag = pjsip_transport_get_flag_from_type(tpdata->type);\n\n if (flag & PJSIP_TRANSPORT_DATAGRAM) {\n\tsel->type = PJSIP_TPSELECTOR_TRANSPORT;\n\tsel->u.transport = tpdata->data.tp;\n } else {\n\tsel->type = PJSIP_TPSELECTOR_LISTENER;\n\tsel->u.listener = tpdata->data.factory;\n }\n}", "label_name": "Base", "label": 1} {"code": "PJ_DEF(pj_status_t) pjmedia_rtcp_fb_parse_sli(\n\t\t\t\t\tconst void *buf,\n\t\t\t\t\tpj_size_t length,\n\t\t\t\t\tunsigned *sli_cnt,\n\t\t\t\t\tpjmedia_rtcp_fb_sli sli[])\n{\n pjmedia_rtcp_common *hdr = (pjmedia_rtcp_common*) buf;\n pj_uint8_t *p;\n unsigned cnt, i;\n\n PJ_ASSERT_RETURN(buf && sli_cnt && sli, PJ_EINVAL);\n PJ_ASSERT_RETURN(length >= sizeof(pjmedia_rtcp_common), PJ_ETOOSMALL);\n\n /* PLI uses pt==RTCP_PSFB and FMT==2 */\n if (hdr->pt != RTCP_PSFB || hdr->count != 2)\n\treturn PJ_ENOTFOUND;\n\n cnt = pj_ntohs((pj_uint16_t)hdr->length) - 2;\n if (length < (cnt+3)*4)\n\treturn PJ_ETOOSMALL;\n\n *sli_cnt = PJ_MIN(*sli_cnt, cnt);\n\n p = (pj_uint8_t*)hdr + sizeof(*hdr);\n for (i = 0; i < *sli_cnt; ++i) {\n\t/* 'first' takes 13 bit */\n\tsli[i].first = (p[0] << 5) + ((p[1] & 0xF8) >> 3);\n\t/* 'number' takes 13 bit */\n\tsli[i].number = ((p[1] & 0x07) << 10) +\n\t\t\t(p[2] << 2) +\n\t\t\t((p[3] & 0xC0) >> 6);\n\t/* 'pict_id' takes 6 bit */\n\tsli[i].pict_id = (p[3] & 0x3F);\n\tp += 4;\n }\n\n return PJ_SUCCESS;\n}", "label_name": "Base", "label": 1} {"code": "int ppp_register_net_channel(struct net *net, struct ppp_channel *chan)\n{\n\tstruct channel *pch;\n\tstruct ppp_net *pn;\n\n\tpch = kzalloc(sizeof(struct channel), GFP_KERNEL);\n\tif (!pch)\n\t\treturn -ENOMEM;\n\n\tpn = ppp_pernet(net);\n\n\tpch->ppp = NULL;\n\tpch->chan = chan;\n\tpch->chan_net = net;\n\tchan->ppp = pch;\n\tinit_ppp_file(&pch->file, CHANNEL);\n\tpch->file.hdrlen = chan->hdrlen;\n#ifdef CONFIG_PPP_MULTILINK\n\tpch->lastseq = -1;\n#endif /* CONFIG_PPP_MULTILINK */\n\tinit_rwsem(&pch->chan_sem);\n\tspin_lock_init(&pch->downl);\n\trwlock_init(&pch->upl);\n\n\tspin_lock_bh(&pn->all_channels_lock);\n\tpch->file.index = ++pn->last_channel_index;\n\tlist_add(&pch->list, &pn->new_channels);\n\tatomic_inc(&channel_count);\n\tspin_unlock_bh(&pn->all_channels_lock);\n\n\treturn 0;\n}", "label_name": "Variant", "label": 0} -{"code": "static void f_parser (lua_State *L, void *ud) {\n int i;\n Proto *tf;\n Closure *cl;\n struct SParser *p = cast(struct SParser *, ud);\n int c = luaZ_lookahead(p->z);\n luaC_checkGC(L);\n tf = ((c == LUA_SIGNATURE[0]) ? luaU_undump : luaY_parser)(L, p->z,\n &p->buff, p->name);\n cl = luaF_newLclosure(L, tf->nups, hvalue(gt(L)));\n cl->l.p = tf;\n for (i = 0; i < tf->nups; i++) /* initialize eventual upvalues */\n cl->l.upvals[i] = luaF_newupval(L);\n setclvalue(L, L->top, cl);\n incr_top(L);\n}", "label_name": "CWE-17", "label": "CWE-17"} {"code": "static LUA_FUNCTION(openssl_x509_check_host)\n{\n X509 * cert = CHECK_OBJECT(1, X509, \"openssl.x509\");\n if (lua_isstring(L, 2))\n {\n const char *hostname = lua_tostring(L, 2);\n lua_pushboolean(L, X509_check_host(cert, hostname, strlen(hostname), 0, NULL));\n }\n else\n {\n lua_pushboolean(L, 0);\n }\n return 1;\n}", "label_name": "Base", "label": 1} {"code": "PJ_DEF(pj_status_t) pjsip_ua_unregister_dlg( pjsip_user_agent *ua,\n\t\t\t\t\t pjsip_dialog *dlg )\n{\n struct dlg_set *dlg_set;\n pjsip_dialog *d;\n\n /* Sanity-check arguments. */\n PJ_ASSERT_RETURN(ua && dlg, PJ_EINVAL);\n\n /* Check that dialog has been registered. */\n PJ_ASSERT_RETURN(dlg->dlg_set, PJ_EINVALIDOP);\n\n /* Lock user agent. */\n pj_mutex_lock(mod_ua.mutex);\n\n /* Find this dialog from the dialog set. */\n dlg_set = (struct dlg_set*) dlg->dlg_set;\n d = dlg_set->dlg_list.next;\n while (d != (pjsip_dialog*)&dlg_set->dlg_list && d != dlg) {\n\td = d->next;\n }\n\n if (d != dlg) {\n\tpj_assert(!\"Dialog is not registered!\");\n\tpj_mutex_unlock(mod_ua.mutex);\n\treturn PJ_EINVALIDOP;\n }\n\n /* Remove this dialog from the list. */\n pj_list_erase(dlg);\n\n /* If dialog list is empty, remove the dialog set from the hash table. */\n if (pj_list_empty(&dlg_set->dlg_list)) {\n\tpj_hash_set_lower(NULL, mod_ua.dlg_table, dlg->local.info->tag.ptr,\n\t\t (unsigned)dlg->local.info->tag.slen, \n\t\t\t dlg->local.tag_hval, NULL);\n\n\t/* Return dlg_set to free nodes. */\n\tpj_list_push_back(&mod_ua.free_dlgset_nodes, dlg_set);\n }\n\n /* Unlock user agent. */\n pj_mutex_unlock(mod_ua.mutex);\n\n /* Done. */\n return PJ_SUCCESS;\n}", "label_name": "Variant", "label": 0} {"code": "int imap_subscribe (char *path, int subscribe)\n{\n IMAP_DATA *idata;\n char buf[LONG_STRING];\n char mbox[LONG_STRING];\n char errstr[STRING];\n BUFFER err, token;\n IMAP_MBOX mx;\n\n if (!mx_is_imap (path) || imap_parse_path (path, &mx) || !mx.mbox)\n {\n mutt_error (_(\"Bad mailbox name\"));\n return -1;\n }\n if (!(idata = imap_conn_find (&(mx.account), 0)))\n goto fail;\n\n imap_fix_path (idata, mx.mbox, buf, sizeof (buf));\n if (!*buf)\n strfcpy (buf, \"INBOX\", sizeof (buf));\n\n if (option (OPTIMAPCHECKSUBSCRIBED))\n {\n mutt_buffer_init (&token);\n mutt_buffer_init (&err);\n err.data = errstr;\n err.dsize = sizeof (errstr);\n snprintf (mbox, sizeof (mbox), \"%smailboxes \\\"%s\\\"\",\n subscribe ? \"\" : \"un\", path);\n if (mutt_parse_rc_line (mbox, &token, &err))\n dprint (1, (debugfile, \"Error adding subscribed mailbox: %s\\n\", errstr));\n FREE (&token.data);\n }\n\n if (subscribe)\n mutt_message (_(\"Subscribing to %s...\"), buf);\n else\n mutt_message (_(\"Unsubscribing from %s...\"), buf);\n imap_munge_mbox_name (idata, mbox, sizeof(mbox), buf);\n\n snprintf (buf, sizeof (buf), \"%sSUBSCRIBE %s\", subscribe ? \"\" : \"UN\", mbox);\n\n if (imap_exec (idata, buf, 0) < 0)\n goto fail;\n\n imap_unmunge_mbox_name(idata, mx.mbox);\n if (subscribe)\n mutt_message (_(\"Subscribed to %s\"), mx.mbox);\n else\n mutt_message (_(\"Unsubscribed from %s\"), mx.mbox);\n FREE (&mx.mbox);\n return 0;\n\n fail:\n FREE (&mx.mbox);\n return -1;\n}", "label_name": "Base", "label": 1} {"code": "uint32_t GetPayloadTime(size_t handle, uint32_t index, float *in, float *out)\n{\n\tmp4object *mp4 = (mp4object *)handle;\n\tif (mp4 == NULL) return 0;\n\n\tif (mp4->metaoffsets == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in == NULL || out == NULL) return 1;\n\n\t*in = (float)((double)index * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);\n\t*out = (float)((double)(index + 1) * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);\n\treturn 0;\n}", "label_name": "Base", "label": 1} {"code": "process_plane(uint8 * in, int width, int height, uint8 * out, int size)\n{\n\tUNUSED(size);\n\tint indexw;\n\tint indexh;\n\tint code;\n\tint collen;\n\tint replen;\n\tint color;\n\tint x;\n\tint revcode;\n\tuint8 * last_line;\n\tuint8 * this_line;\n\tuint8 * org_in;\n\tuint8 * org_out;\n\n\torg_in = in;\n\torg_out = out;\n\tlast_line = 0;\n\tindexh = 0;\n\twhile (indexh < height)\n\t{\n\t\tout = (org_out + width * height * 4) - ((indexh + 1) * width * 4);\n\t\tcolor = 0;\n\t\tthis_line = out;\n\t\tindexw = 0;\n\t\tif (last_line == 0)\n\t\t{\n\t\t\twhile (indexw < width)\n\t\t\t{\n\t\t\t\tcode = CVAL(in);\n\t\t\t\treplen = code & 0xf;\n\t\t\t\tcollen = (code >> 4) & 0xf;\n\t\t\t\trevcode = (replen << 4) | collen;\n\t\t\t\tif ((revcode <= 47) && (revcode >= 16))\n\t\t\t\t{\n\t\t\t\t\treplen = revcode;\n\t\t\t\t\tcollen = 0;\n\t\t\t\t}\n\t\t\t\twhile (collen > 0)\n\t\t\t\t{\n\t\t\t\t\tcolor = CVAL(in);\n\t\t\t\t\t*out = color;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\tcollen--;\n\t\t\t\t}\n\t\t\t\twhile (replen > 0)\n\t\t\t\t{\n\t\t\t\t\t*out = color;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\treplen--;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\twhile (indexw < width)\n\t\t\t{\n\t\t\t\tcode = CVAL(in);\n\t\t\t\treplen = code & 0xf;\n\t\t\t\tcollen = (code >> 4) & 0xf;\n\t\t\t\trevcode = (replen << 4) | collen;\n\t\t\t\tif ((revcode <= 47) && (revcode >= 16))\n\t\t\t\t{\n\t\t\t\t\treplen = revcode;\n\t\t\t\t\tcollen = 0;\n\t\t\t\t}\n\t\t\t\twhile (collen > 0)\n\t\t\t\t{\n\t\t\t\t\tx = CVAL(in);\n\t\t\t\t\tif (x & 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tx = x >> 1;\n\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\tcolor = -x;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tx = x >> 1;\n\t\t\t\t\t\tcolor = x;\n\t\t\t\t\t}\n\t\t\t\t\tx = last_line[indexw * 4] + color;\n\t\t\t\t\t*out = x;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\tcollen--;\n\t\t\t\t}\n\t\t\t\twhile (replen > 0)\n\t\t\t\t{\n\t\t\t\t\tx = last_line[indexw * 4] + color;\n\t\t\t\t\t*out = x;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\treplen--;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tindexh++;\n\t\tlast_line = this_line;\n\t}\n\treturn (int) (in - org_in);\n}", "label_name": "Base", "label": 1} -{"code": "SYSCALL_DEFINE1(inotify_init1, int, flags)\n{\n\tstruct fsnotify_group *group;\n\tstruct user_struct *user;\n\tint ret;\n\n\t/* Check the IN_* constants for consistency. */\n\tBUILD_BUG_ON(IN_CLOEXEC != O_CLOEXEC);\n\tBUILD_BUG_ON(IN_NONBLOCK != O_NONBLOCK);\n\n\tif (flags & ~(IN_CLOEXEC | IN_NONBLOCK))\n\t\treturn -EINVAL;\n\n\tuser = get_current_user();\n\tif (unlikely(atomic_read(&user->inotify_devs) >=\n\t\t\tinotify_max_user_instances)) {\n\t\tret = -EMFILE;\n\t\tgoto out_free_uid;\n\t}\n\n\t/* fsnotify_obtain_group took a reference to group, we put this when we kill the file in the end */\n\tgroup = inotify_new_group(user, inotify_max_queued_events);\n\tif (IS_ERR(group)) {\n\t\tret = PTR_ERR(group);\n\t\tgoto out_free_uid;\n\t}\n\n\tatomic_inc(&user->inotify_devs);\n\n\tret = anon_inode_getfd(\"inotify\", &inotify_fops, group,\n\t\t\t\t O_RDONLY | flags);\n\tif (ret >= 0)\n\t\treturn ret;\n\n\tfsnotify_put_group(group);\n\tatomic_dec(&user->inotify_devs);\nout_free_uid:\n\tfree_uid(user);\n\treturn ret;\n}", "label_name": "CWE-399", "label": "CWE-399"} {"code": "static int __pyx_pf_17clickhouse_driver_14bufferedreader_14BufferedReader_8position_2__set__(struct __pyx_obj_17clickhouse_driver_14bufferedreader_BufferedReader *__pyx_v_self, PyObject *__pyx_v_value) {\n int __pyx_r;\n __Pyx_RefNannyDeclarations\n Py_ssize_t __pyx_t_1;\n __Pyx_RefNannySetupContext(\"__set__\", 0);\n __pyx_t_1 = __Pyx_PyIndex_AsSsize_t(__pyx_v_value); if (unlikely((__pyx_t_1 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 11, __pyx_L1_error)\n __pyx_v_self->position = __pyx_t_1;\n\n /* function exit code */\n __pyx_r = 0;\n goto __pyx_L0;\n __pyx_L1_error:;\n __Pyx_AddTraceback(\"clickhouse_driver.bufferedreader.BufferedReader.position.__set__\", __pyx_clineno, __pyx_lineno, __pyx_filename);\n __pyx_r = -1;\n __pyx_L0:;\n __Pyx_RefNannyFinishContext();\n return __pyx_r;\n}", "label_name": "Base", "label": 1} {"code": "FunctionDef(identifier name, arguments_ty args, asdl_seq * body, asdl_seq *\n decorator_list, expr_ty returns, int lineno, int col_offset, int\n end_lineno, int end_col_offset, PyArena *arena)\n{\n stmt_ty p;\n if (!name) {\n PyErr_SetString(PyExc_ValueError,\n \"field name is required for FunctionDef\");\n return NULL;\n }\n if (!args) {\n PyErr_SetString(PyExc_ValueError,\n \"field args is required for FunctionDef\");\n return NULL;\n }\n p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));\n if (!p)\n return NULL;\n p->kind = FunctionDef_kind;\n p->v.FunctionDef.name = name;\n p->v.FunctionDef.args = args;\n p->v.FunctionDef.body = body;\n p->v.FunctionDef.decorator_list = decorator_list;\n p->v.FunctionDef.returns = returns;\n p->lineno = lineno;\n p->col_offset = col_offset;\n p->end_lineno = end_lineno;\n p->end_col_offset = end_col_offset;\n return p;\n}", "label_name": "Base", "label": 1} {"code": "static int hash_recvmsg(struct kiocb *unused, struct socket *sock,\n\t\t\tstruct msghdr *msg, size_t len, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct alg_sock *ask = alg_sk(sk);\n\tstruct hash_ctx *ctx = ask->private;\n\tunsigned ds = crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req));\n\tint err;\n\n\tif (len > ds)\n\t\tlen = ds;\n\telse if (len < ds)\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\n\tmsg->msg_namelen = 0;\n\n\tlock_sock(sk);\n\tif (ctx->more) {\n\t\tctx->more = 0;\n\t\tahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0);\n\t\terr = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req),\n\t\t\t\t\t\t &ctx->completion);\n\t\tif (err)\n\t\t\tgoto unlock;\n\t}\n\n\terr = memcpy_toiovec(msg->msg_iov, ctx->result, len);\n\nunlock:\n\trelease_sock(sk);\n\n\treturn err ?: len;\n}", "label_name": "Class", "label": 2} {"code": "int ecall_start(struct ecall *ecall, enum icall_call_type call_type,\n\t\tbool audio_cbr)\n{\n\tint err;\n\n\tinfo(\"ecall(%p): start\\n\", ecall);\n\n\tif (!ecall)\n\t\treturn EINVAL;\n\n#ifdef ECALL_CBR_ALWAYS_ON\n\taudio_cbr = true;\n#endif\n\n\tif (ecall->econn) {\n\t\tif (ECONN_PENDING_INCOMING == econn_current_state(ecall->econn)) {\n\t\t\treturn ecall_answer(ecall, call_type, audio_cbr);\n\t\t}\n\t\telse {\n\t\t\twarning(\"ecall: start: already in progress (econn=%s)\\n\",\n\t\t\t\teconn_state_name(econn_current_state(ecall->econn)));\n\t\t\treturn EALREADY;\n\t\t}\n\t}\n\n#if 0\n\tif (ecall->turnc == 0) {\n\t\twarning(\"ecall: start: no TURN servers -- cannot start\\n\");\n\t\treturn EINTR;\n\t}\n#endif\n\n\tecall->call_type = call_type;\n\t\n\terr = ecall_create_econn(ecall);\n\tif (err) {\n\t\twarning(\"ecall: start: create_econn failed: %m\\n\", err);\n\t\treturn err;\n\t}\n\n\teconn_set_state(ecall_get_econn(ecall), ECONN_PENDING_OUTGOING);\n\n\terr = alloc_flow(ecall, ASYNC_OFFER, ecall->call_type, audio_cbr);\n\tif (err) {\n\t\twarning(\"ecall: start: alloc_flow failed: %m\\n\", err);\n\t\tgoto out;\n\t}\n\n\tIFLOW_CALL(ecall->flow, set_audio_cbr, audio_cbr);\n\t\n\tif (ecall->props_local &&\n\t (call_type == ICALL_CALL_TYPE_VIDEO\n\t && ecall->vstate == ICALL_VIDEO_STATE_STARTED)) {\n\t\tconst char *vstate_string = \"true\";\n\n\t\tint err2 = econn_props_update(ecall->props_local,\n\t\t\t\t\t \"videosend\", vstate_string);\n\t\tif (err2) {\n\t\t\twarning(\"ecall(%p): econn_props_update(videosend)\",\n\t\t\t\t\" failed (%m)\\n\", ecall, err2);\n\t\t\t/* Non fatal, carry on */\n\t\t}\n\t}\n\n\tecall->sdp.async = ASYNC_NONE;\n\terr = generate_offer(ecall);\n\tif (err) {\n\t\twarning(\"ecall(%p): start: generate_offer\"\n\t\t\t\" failed (%m)\\n\", ecall, err);\n\t\tgoto out;\n\t}\n\n\tecall->ts_started = tmr_jiffies();\n\tecall->call_setup_time = -1;\n\n out:\n\t/* err handling */\n\treturn err;\n}", "label_name": "Base", "label": 1} -{"code": "static int ceph_x_decrypt(struct ceph_crypto_key *secret,\n\t\t\t void **p, void *end, void *obuf, size_t olen)\n{\n\tstruct ceph_x_encrypt_header head;\n\tsize_t head_len = sizeof(head);\n\tint len, ret;\n\n\tlen = ceph_decode_32(p);\n\tif (*p + len > end)\n\t\treturn -EINVAL;\n\n\tdout(\"ceph_x_decrypt len %d\\n\", len);\n\tret = ceph_decrypt2(secret, &head, &head_len, obuf, &olen,\n\t\t\t *p, len);\n\tif (ret)\n\t\treturn ret;\n\tif (head.struct_v != 1 || le64_to_cpu(head.magic) != CEPHX_ENC_MAGIC)\n\t\treturn -EPERM;\n\t*p += len;\n\treturn olen;\n}", "label_name": "CWE-399", "label": "CWE-399"} {"code": "void ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields)\n{\n\tif (fields)\n\t{\n\t\tif (fields->Buffer)\n\t\t{\n\t\t\tfree(fields->Buffer);\n\t\t\tfields->Len = 0;\n\t\t\tfields->MaxLen = 0;\n\t\t\tfields->Buffer = NULL;\n\t\t\tfields->BufferOffset = 0;\n\t\t}\n\t}\n}", "label_name": "Base", "label": 1} {"code": "static void mbochs_remove(struct mdev_device *mdev)\n{\n\tstruct mdev_state *mdev_state = dev_get_drvdata(&mdev->dev);\n\n\tmbochs_used_mbytes -= mdev_state->type->mbytes;\n\tvfio_unregister_group_dev(&mdev_state->vdev);\n\tkfree(mdev_state->pages);\n\tkfree(mdev_state->vconfig);\n\tkfree(mdev_state);\n}", "label_name": "Variant", "label": 0} {"code": "SPL_METHOD(SplFileObject, ftruncate)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\tlong size;\n\t\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"l\", &size) == FAILURE) {\n\t\treturn;\n\t}\n\n\tif (!php_stream_truncate_supported(intern->u.file.stream)) {\n\t\tzend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, \"Can't truncate file %s\", intern->file_name);\n\t\tRETURN_FALSE;\n\t}\n\t\n\tRETURN_BOOL(0 == php_stream_truncate_set_size(intern->u.file.stream, size));\n} /* }}} */", "label_name": "Base", "label": 1} @@ -1028,7 +1019,6 @@ {"code": "For(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq * orelse, int\n lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena)\n{\n stmt_ty p;\n if (!target) {\n PyErr_SetString(PyExc_ValueError,\n \"field target is required for For\");\n return NULL;\n }\n if (!iter) {\n PyErr_SetString(PyExc_ValueError,\n \"field iter is required for For\");\n return NULL;\n }\n p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));\n if (!p)\n return NULL;\n p->kind = For_kind;\n p->v.For.target = target;\n p->v.For.iter = iter;\n p->v.For.body = body;\n p->v.For.orelse = orelse;\n p->lineno = lineno;\n p->col_offset = col_offset;\n p->end_lineno = end_lineno;\n p->end_col_offset = end_col_offset;\n return p;\n}", "label_name": "Base", "label": 1} {"code": "static int cp2112_gpio_direction_input(struct gpio_chip *chip, unsigned offset)\n{\n\tstruct cp2112_device *dev = gpiochip_get_data(chip);\n\tstruct hid_device *hdev = dev->hdev;\n\tu8 *buf = dev->in_out_buffer;\n\tunsigned long flags;\n\tint ret;\n\n\tspin_lock_irqsave(&dev->lock, flags);\n\n\tret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,\n\t\t\t\t CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,\n\t\t\t\t HID_REQ_GET_REPORT);\n\tif (ret != CP2112_GPIO_CONFIG_LENGTH) {\n\t\thid_err(hdev, \"error requesting GPIO config: %d\\n\", ret);\n\t\tgoto exit;\n\t}\n\n\tbuf[1] &= ~(1 << offset);\n\tbuf[2] = gpio_push_pull;\n\n\tret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,\n\t\t\t\t CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,\n\t\t\t\t HID_REQ_SET_REPORT);\n\tif (ret < 0) {\n\t\thid_err(hdev, \"error setting GPIO config: %d\\n\", ret);\n\t\tgoto exit;\n\t}\n\n\tret = 0;\n\nexit:\n\tspin_unlock_irqrestore(&dev->lock, flags);\n\treturn ret <= 0 ? ret : -EIO;\n}", "label_name": "Class", "label": 2} {"code": "ast_type_reduce(PyObject *self, PyObject *unused)\n{\n PyObject *res;\n _Py_IDENTIFIER(__dict__);\n PyObject *dict = _PyObject_GetAttrId(self, &PyId___dict__);\n if (dict == NULL) {\n if (PyErr_ExceptionMatches(PyExc_AttributeError))\n PyErr_Clear();\n else\n return NULL;\n }\n if (dict) {\n res = Py_BuildValue(\"O()O\", Py_TYPE(self), dict);\n Py_DECREF(dict);\n return res;\n }\n return Py_BuildValue(\"O()\", Py_TYPE(self));\n}", "label_name": "Base", "label": 1} -{"code": "static ssize_t lbs_debugfs_write(struct file *f, const char __user *buf,\n\t\t\t size_t cnt, loff_t *ppos)\n{\n\tint r, i;\n\tchar *pdata;\n\tchar *p;\n\tchar *p0;\n\tchar *p1;\n\tchar *p2;\n\tstruct debug_data *d = f->private_data;\n\n\tpdata = kmalloc(cnt, GFP_KERNEL);\n\tif (pdata == NULL)\n\t\treturn 0;\n\n\tif (copy_from_user(pdata, buf, cnt)) {\n\t\tlbs_deb_debugfs(\"Copy from user failed\\n\");\n\t\tkfree(pdata);\n\t\treturn 0;\n\t}\n\n\tp0 = pdata;\n\tfor (i = 0; i < num_of_items; i++) {\n\t\tdo {\n\t\t\tp = strstr(p0, d[i].name);\n\t\t\tif (p == NULL)\n\t\t\t\tbreak;\n\t\t\tp1 = strchr(p, '\\n');\n\t\t\tif (p1 == NULL)\n\t\t\t\tbreak;\n\t\t\tp0 = p1++;\n\t\t\tp2 = strchr(p, '=');\n\t\t\tif (!p2)\n\t\t\t\tbreak;\n\t\t\tp2++;\n\t\t\tr = simple_strtoul(p2, NULL, 0);\n\t\t\tif (d[i].size == 1)\n\t\t\t\t*((u8 *) d[i].addr) = (u8) r;\n\t\t\telse if (d[i].size == 2)\n\t\t\t\t*((u16 *) d[i].addr) = (u16) r;\n\t\t\telse if (d[i].size == 4)\n\t\t\t\t*((u32 *) d[i].addr) = (u32) r;\n\t\t\telse if (d[i].size == 8)\n\t\t\t\t*((u64 *) d[i].addr) = (u64) r;\n\t\t\tbreak;\n\t\t} while (1);\n\t}\n\tkfree(pdata);\n\n\treturn (ssize_t)cnt;\n}", "label_name": "CWE-189", "label": "CWE-189"} {"code": "static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)\n{\n\tmuscle_private_t* priv = MUSCLE_DATA(card);\n\tmscfs_t *fs = priv->fs;\n\tint x;\n\tint count = 0;\n\n\tmscfs_check_cache(priv->fs);\n\n\tfor(x = 0; x < fs->cache.size; x++) {\n\t\tu8* oid= fs->cache.array[x].objectId.id;\n\t\tsc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,\n\t\t\t\"FILE: %02X%02X%02X%02X\\n\",\n\t\t\toid[0],oid[1],oid[2],oid[3]);\n\t\tif(0 == memcmp(fs->currentPath, oid, 2)) {\n\t\t\tbuf[0] = oid[2];\n\t\t\tbuf[1] = oid[3];\n\t\t\tif(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */\n\t\t\tbuf += 2;\n\t\t\tcount+=2;\n\t\t}\n\t}\n\treturn count;\n}", "label_name": "Class", "label": 2} {"code": "static int serdes_probe(struct platform_device *pdev)\n{\n\tstruct phy_provider *provider;\n\tstruct serdes_ctrl *ctrl;\n\tunsigned int i;\n\tint ret;\n\n\tctrl = devm_kzalloc(&pdev->dev, sizeof(*ctrl), GFP_KERNEL);\n\tif (!ctrl)\n\t\treturn -ENOMEM;\n\n\tctrl->dev = &pdev->dev;\n\tctrl->regs = syscon_node_to_regmap(pdev->dev.parent->of_node);\n\tif (IS_ERR(ctrl->regs))\n\t\treturn PTR_ERR(ctrl->regs);\n\n\tfor (i = 0; i <= SERDES_MAX; i++) {\n\t\tret = serdes_phy_create(ctrl, i, &ctrl->phys[i]);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}\n\n\tdev_set_drvdata(&pdev->dev, ctrl);\n\n\tprovider = devm_of_phy_provider_register(ctrl->dev,\n\t\t\t\t\t\t serdes_simple_xlate);\n\n\treturn PTR_ERR_OR_ZERO(provider);\n}", "label_name": "Base", "label": 1} {"code": "mark_context_stack(mrb_state *mrb, struct mrb_context *c)\n{\n size_t i;\n size_t e;\n\n if (c->stack == NULL) return;\n e = c->stack - c->stbase;\n if (c->ci) e += c->ci->nregs;\n if (c->stbase + e > c->stend) e = c->stend - c->stbase;\n for (i=0; istbase[i];\n\n if (!mrb_immediate_p(v)) {\n if (mrb_basic_ptr(v)->tt == MRB_TT_FREE) {\n c->stbase[i] = mrb_nil_value();\n }\n else {\n mrb_gc_mark(mrb, mrb_basic_ptr(v));\n }\n }\n }\n}", "label_name": "Variant", "label": 0} @@ -1036,13 +1026,10 @@ {"code": "static ssize_t qrtr_tun_write_iter(struct kiocb *iocb, struct iov_iter *from)\n{\n\tstruct file *filp = iocb->ki_filp;\n\tstruct qrtr_tun *tun = filp->private_data;\n\tsize_t len = iov_iter_count(from);\n\tssize_t ret;\n\tvoid *kbuf;\n\n\tkbuf = kzalloc(len, GFP_KERNEL);\n\tif (!kbuf)\n\t\treturn -ENOMEM;\n\n\tif (!copy_from_iter_full(kbuf, len, from))\n\t\treturn -EFAULT;\n\n\tret = qrtr_endpoint_post(&tun->ep, kbuf, len);\n\n\treturn ret < 0 ? ret : len;\n}", "label_name": "Variant", "label": 0} {"code": "static unsigned int ipv6_defrag(void *priv,\n\t\t\t\tstruct sk_buff *skb,\n\t\t\t\tconst struct nf_hook_state *state)\n{\n\tint err;\n\n#if IS_ENABLED(CONFIG_NF_CONNTRACK)\n\t/* Previously seen (loopback)?\t*/\n\tif (skb->nfct && !nf_ct_is_template((struct nf_conn *)skb->nfct))\n\t\treturn NF_ACCEPT;\n#endif\n\n\terr = nf_ct_frag6_gather(state->net, skb,\n\t\t\t\t nf_ct6_defrag_user(state->hook, skb));\n\t/* queued */\n\tif (err == -EINPROGRESS)\n\t\treturn NF_STOLEN;\n\n\treturn NF_ACCEPT;\n}", "label_name": "Base", "label": 1} {"code": "decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len)\n{\n\tsize_t cipher_len;\n\tsize_t i;\n\tunsigned char iv[16] = { 0 };\n\tunsigned char plaintext[4096] = { 0 };\n\tepass2003_exdata *exdata = NULL;\n\n\tif (!card->drv_data) \n\t\treturn SC_ERROR_INVALID_ARGUMENTS;\n\n\texdata = (epass2003_exdata *)card->drv_data;\n\n\t/* no cipher */\n\tif (in[0] == 0x99)\n\t\treturn 0;\n\n\t/* parse cipher length */\n\tif (0x01 == in[2] && 0x82 != in[1]) {\n\t\tcipher_len = in[1];\n\t\ti = 3;\n\t}\n\telse if (0x01 == in[3] && 0x81 == in[1]) {\n\t\tcipher_len = in[2];\n\t\ti = 4;\n\t}\n\telse if (0x01 == in[4] && 0x82 == in[1]) {\n\t\tcipher_len = in[2] * 0x100;\n\t\tcipher_len += in[3];\n\t\ti = 5;\n\t}\n\telse {\n\t\treturn -1;\n\t}\n\n\tif (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext)\n\t\treturn -1;\n\n\t/* decrypt */\n\tif (KEY_TYPE_AES == exdata->smtype)\n\t\taes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext);\n\telse\n\t\tdes3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext);\n\n\t/* unpadding */\n\twhile (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0))\n\t\tcipher_len--;\n\n\tif (2 == cipher_len)\n\t\treturn -1;\n\n\tmemcpy(out, plaintext, cipher_len - 2);\n\t*out_len = cipher_len - 2;\n\treturn 0;\n}", "label_name": "Class", "label": 2} -{"code": "static void ip6_append_data_mtu(int *mtu,\n\t\t\t\tint *maxfraglen,\n\t\t\t\tunsigned int fragheaderlen,\n\t\t\t\tstruct sk_buff *skb,\n\t\t\t\tstruct rt6_info *rt)\n{\n\tif (!(rt->dst.flags & DST_XFRM_TUNNEL)) {\n\t\tif (skb == NULL) {\n\t\t\t/* first fragment, reserve header_len */\n\t\t\t*mtu = *mtu - rt->dst.header_len;\n\n\t\t} else {\n\t\t\t/*\n\t\t\t * this fragment is not first, the headers\n\t\t\t * space is regarded as data space.\n\t\t\t */\n\t\t\t*mtu = dst_mtu(rt->dst.path);\n\t\t}\n\t\t*maxfraglen = ((*mtu - fragheaderlen) & ~7)\n\t\t\t + fragheaderlen - sizeof(struct frag_hdr);\n\t}\n}", "label_name": "CWE-399", "label": "CWE-399"} {"code": "static int ovl_remove_upper(struct dentry *dentry, bool is_dir)\n{\n\tstruct dentry *upperdir = ovl_dentry_upper(dentry->d_parent);\n\tstruct inode *dir = upperdir->d_inode;\n\tstruct dentry *upper = ovl_dentry_upper(dentry);\n\tint err;\n\n\tinode_lock_nested(dir, I_MUTEX_PARENT);\n\terr = -ESTALE;\n\tif (upper->d_parent == upperdir) {\n\t\t/* Don't let d_delete() think it can reset d_inode */\n\t\tdget(upper);\n\t\tif (is_dir)\n\t\t\terr = vfs_rmdir(dir, upper);\n\t\telse\n\t\t\terr = vfs_unlink(dir, upper, NULL);\n\t\tdput(upper);\n\t\tovl_dentry_version_inc(dentry->d_parent);\n\t}\n\n\t/*\n\t * Keeping this dentry hashed would mean having to release\n\t * upperpath/lowerpath, which could only be done if we are the\n\t * sole user of this dentry. Too tricky... Just unhash for\n\t * now.\n\t */\n\tif (!err)\n\t\td_drop(dentry);\n\tinode_unlock(dir);\n\n\treturn err;\n}", "label_name": "Class", "label": 2} {"code": "int parse_rock_ridge_inode(struct iso_directory_record *de, struct inode *inode)\n{\n\tint result = parse_rock_ridge_inode_internal(de, inode, 0);\n\n\t/*\n\t * if rockridge flag was reset and we didn't look for attributes\n\t * behind eventual XA attributes, have a look there\n\t */\n\tif ((ISOFS_SB(inode->i_sb)->s_rock_offset == -1)\n\t && (ISOFS_SB(inode->i_sb)->s_rock == 2)) {\n\t\tresult = parse_rock_ridge_inode_internal(de, inode, 14);\n\t}\n\treturn result;\n}", "label_name": "Class", "label": 2} {"code": "void ptrace_triggered(struct perf_event *bp, int nmi,\n\t\t struct perf_sample_data *data, struct pt_regs *regs)\n{\n\tstruct perf_event_attr attr;\n\n\t/*\n\t * Disable the breakpoint request here since ptrace has defined a\n\t * one-shot behaviour for breakpoint exceptions.\n\t */\n\tattr = bp->attr;\n\tattr.disabled = true;\n\tmodify_user_hw_breakpoint(bp, &attr);\n}", "label_name": "Class", "label": 2} -{"code": "static int ext4_fill_flex_info(struct super_block *sb)\n{\n\tstruct ext4_sb_info *sbi = EXT4_SB(sb);\n\tstruct ext4_group_desc *gdp = NULL;\n\text4_group_t flex_group_count;\n\text4_group_t flex_group;\n\tint groups_per_flex = 0;\n\tsize_t size;\n\tint i;\n\n\tsbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;\n\tgroups_per_flex = 1 << sbi->s_log_groups_per_flex;\n\n\tif (groups_per_flex < 2) {\n\t\tsbi->s_log_groups_per_flex = 0;\n\t\treturn 1;\n\t}\n\n\t/* We allocate both existing and potentially added groups */\n\tflex_group_count = ((sbi->s_groups_count + groups_per_flex - 1) +\n\t\t\t((le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks) + 1) <<\n\t\t\t EXT4_DESC_PER_BLOCK_BITS(sb))) / groups_per_flex;\n\tsize = flex_group_count * sizeof(struct flex_groups);\n\tsbi->s_flex_groups = ext4_kvzalloc(size, GFP_KERNEL);\n\tif (sbi->s_flex_groups == NULL) {\n\t\text4_msg(sb, KERN_ERR, \"not enough memory for %u flex groups\",\n\t\t\t flex_group_count);\n\t\tgoto failed;\n\t}\n\n\tfor (i = 0; i < sbi->s_groups_count; i++) {\n\t\tgdp = ext4_get_group_desc(sb, i, NULL);\n\n\t\tflex_group = ext4_flex_group(sbi, i);\n\t\tatomic_add(ext4_free_inodes_count(sb, gdp),\n\t\t\t &sbi->s_flex_groups[flex_group].free_inodes);\n\t\tatomic_add(ext4_free_group_clusters(sb, gdp),\n\t\t\t &sbi->s_flex_groups[flex_group].free_clusters);\n\t\tatomic_add(ext4_used_dirs_count(sb, gdp),\n\t\t\t &sbi->s_flex_groups[flex_group].used_dirs);\n\t}\n\n\treturn 1;\nfailed:\n\treturn 0;\n}", "label_name": "CWE-189", "label": "CWE-189"} {"code": "static int cxusb_ctrl_msg(struct dvb_usb_device *d,\n\t\t\t u8 cmd, u8 *wbuf, int wlen, u8 *rbuf, int rlen)\n{\n\tstruct cxusb_state *st = d->priv;\n\tint ret, wo;\n\n\tif (1 + wlen > MAX_XFER_SIZE) {\n\t\twarn(\"i2c wr: len=%d is too big!\\n\", wlen);\n\t\treturn -EOPNOTSUPP;\n\t}\n\n\two = (rbuf == NULL || rlen == 0); /* write-only */\n\n\tmutex_lock(&d->data_mutex);\n\tst->data[0] = cmd;\n\tmemcpy(&st->data[1], wbuf, wlen);\n\tif (wo)\n\t\tret = dvb_usb_generic_write(d, st->data, 1 + wlen);\n\telse\n\t\tret = dvb_usb_generic_rw(d, st->data, 1 + wlen,\n\t\t\t\t\t rbuf, rlen, 0);\n\n\tmutex_unlock(&d->data_mutex);\n\treturn ret;\n}", "label_name": "Class", "label": 2} -{"code": "pipe_iov_copy_from_user(void *to, struct iovec *iov, unsigned long len,\n\t\t\tint atomic)\n{\n\tunsigned long copy;\n\n\twhile (len > 0) {\n\t\twhile (!iov->iov_len)\n\t\t\tiov++;\n\t\tcopy = min_t(unsigned long, len, iov->iov_len);\n\n\t\tif (atomic) {\n\t\t\tif (__copy_from_user_inatomic(to, iov->iov_base, copy))\n\t\t\t\treturn -EFAULT;\n\t\t} else {\n\t\t\tif (copy_from_user(to, iov->iov_base, copy))\n\t\t\t\treturn -EFAULT;\n\t\t}\n\t\tto += copy;\n\t\tlen -= copy;\n\t\tiov->iov_base += copy;\n\t\tiov->iov_len -= copy;\n\t}\n\treturn 0;\n}", "label_name": "CWE-17", "label": "CWE-17"} {"code": "static void shm_destroy(struct ipc_namespace *ns, struct shmid_kernel *shp)\n{\n\tns->shm_tot -= (shp->shm_segsz + PAGE_SIZE - 1) >> PAGE_SHIFT;\n\tshm_rmid(ns, shp);\n\tshm_unlock(shp);\n\tif (!is_file_hugepages(shp->shm_file))\n\t\tshmem_lock(shp->shm_file, 0, shp->mlock_user);\n\telse if (shp->mlock_user)\n\t\tuser_shm_unlock(file_inode(shp->shm_file)->i_size,\n\t\t\t\t\t\tshp->mlock_user);\n\tfput (shp->shm_file);\n\tipc_rcu_putref(shp, shm_rcu_free);\n}", "label_name": "Class", "label": 2} {"code": "static int msg_parse_fetch(struct ImapHeader *h, char *s)\n{\n char tmp[SHORT_STRING];\n char *ptmp = NULL;\n\n if (!s)\n return -1;\n\n while (*s)\n {\n SKIPWS(s);\n\n if (mutt_str_strncasecmp(\"FLAGS\", s, 5) == 0)\n {\n s = msg_parse_flags(h, s);\n if (!s)\n return -1;\n }\n else if (mutt_str_strncasecmp(\"UID\", s, 3) == 0)\n {\n s += 3;\n SKIPWS(s);\n if (mutt_str_atoui(s, &h->data->uid) < 0)\n return -1;\n\n s = imap_next_word(s);\n }\n else if (mutt_str_strncasecmp(\"INTERNALDATE\", s, 12) == 0)\n {\n s += 12;\n SKIPWS(s);\n if (*s != '\\\"')\n {\n mutt_debug(1, \"bogus INTERNALDATE entry: %s\\n\", s);\n return -1;\n }\n s++;\n ptmp = tmp;\n while (*s && *s != '\\\"')\n *ptmp++ = *s++;\n if (*s != '\\\"')\n return -1;\n s++; /* skip past the trailing \" */\n *ptmp = '\\0';\n h->received = mutt_date_parse_imap(tmp);\n }\n else if (mutt_str_strncasecmp(\"RFC822.SIZE\", s, 11) == 0)\n {\n s += 11;\n SKIPWS(s);\n ptmp = tmp;\n while (isdigit((unsigned char) *s))\n *ptmp++ = *s++;\n *ptmp = '\\0';\n if (mutt_str_atol(tmp, &h->content_length) < 0)\n return -1;\n }\n else if ((mutt_str_strncasecmp(\"BODY\", s, 4) == 0) ||\n (mutt_str_strncasecmp(\"RFC822.HEADER\", s, 13) == 0))\n {\n /* handle above, in msg_fetch_header */\n return -2;\n }\n else if (*s == ')')\n s++; /* end of request */\n else if (*s)\n {\n /* got something i don't understand */\n imap_error(\"msg_parse_fetch\", s);\n return -1;\n }\n }\n\n return 0;\n}", "label_name": "Base", "label": 1} {"code": "static void show_object(struct object *obj,\n\t\t\tstruct strbuf *path, const char *component,\n\t\t\tvoid *cb_data)\n{\n\tstruct rev_list_info *info = cb_data;\n\tfinish_object(obj, path, component, cb_data);\n\tif (info->flags & REV_LIST_QUIET)\n\t\treturn;\n\tshow_object_with_name(stdout, obj, path, component);\n}", "label_name": "Class", "label": 2} @@ -1060,14 +1047,12 @@ {"code": "getlogin_r (name, name_len)\n char *name;\n size_t name_len;\n{\n char tty_pathname[2 + 2 * NAME_MAX];\n char *real_tty_path = tty_pathname;\n int result = 0;\n struct utmp *ut, line, buffer;\n\n {\n int d = __open (\"/dev/tty\", 0);\n if (d < 0)\n return errno;\n\n result = __ttyname_r (d, real_tty_path, sizeof (tty_pathname));\n (void) __close (d);\n\n if (result != 0)\n {\n\t__set_errno (result);\n\treturn result;\n }\n }\n\n real_tty_path += 5;\t\t/* Remove \"/dev/\". */\n\n __setutent ();\n strncpy (line.ut_line, real_tty_path, sizeof line.ut_line);\n if (__getutline_r (&line, &buffer, &ut) < 0)\n {\n if (errno == ESRCH)\n\t/* The caller expects ENOENT if nothing is found. */\n\tresult = ENOENT;\n else\n\tresult = errno;\n }\n else\n {\n size_t needed = strlen (ut->ut_line) + 1;\n\n if (needed < name_len)\n\t{\n\t __set_errno (ERANGE);\n\t result = ERANGE;\n\t}\n else\n\t{\n\t memcpy (name, ut->ut_line, needed);\n\t result = 0;\n\t}\n }\n __endutent ();\n\n return result;\n}", "label_name": "Base", "label": 1} {"code": "process_plane(uint8 * in, int width, int height, uint8 * out, int size)\n{\n\tUNUSED(size);\n\tint indexw;\n\tint indexh;\n\tint code;\n\tint collen;\n\tint replen;\n\tint color;\n\tint x;\n\tint revcode;\n\tuint8 * last_line;\n\tuint8 * this_line;\n\tuint8 * org_in;\n\tuint8 * org_out;\n\n\torg_in = in;\n\torg_out = out;\n\tlast_line = 0;\n\tindexh = 0;\n\twhile (indexh < height)\n\t{\n\t\tout = (org_out + width * height * 4) - ((indexh + 1) * width * 4);\n\t\tcolor = 0;\n\t\tthis_line = out;\n\t\tindexw = 0;\n\t\tif (last_line == 0)\n\t\t{\n\t\t\twhile (indexw < width)\n\t\t\t{\n\t\t\t\tcode = CVAL(in);\n\t\t\t\treplen = code & 0xf;\n\t\t\t\tcollen = (code >> 4) & 0xf;\n\t\t\t\trevcode = (replen << 4) | collen;\n\t\t\t\tif ((revcode <= 47) && (revcode >= 16))\n\t\t\t\t{\n\t\t\t\t\treplen = revcode;\n\t\t\t\t\tcollen = 0;\n\t\t\t\t}\n\t\t\t\twhile (collen > 0)\n\t\t\t\t{\n\t\t\t\t\tcolor = CVAL(in);\n\t\t\t\t\t*out = color;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\tcollen--;\n\t\t\t\t}\n\t\t\t\twhile (replen > 0)\n\t\t\t\t{\n\t\t\t\t\t*out = color;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\treplen--;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\twhile (indexw < width)\n\t\t\t{\n\t\t\t\tcode = CVAL(in);\n\t\t\t\treplen = code & 0xf;\n\t\t\t\tcollen = (code >> 4) & 0xf;\n\t\t\t\trevcode = (replen << 4) | collen;\n\t\t\t\tif ((revcode <= 47) && (revcode >= 16))\n\t\t\t\t{\n\t\t\t\t\treplen = revcode;\n\t\t\t\t\tcollen = 0;\n\t\t\t\t}\n\t\t\t\twhile (collen > 0)\n\t\t\t\t{\n\t\t\t\t\tx = CVAL(in);\n\t\t\t\t\tif (x & 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tx = x >> 1;\n\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\tcolor = -x;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tx = x >> 1;\n\t\t\t\t\t\tcolor = x;\n\t\t\t\t\t}\n\t\t\t\t\tx = last_line[indexw * 4] + color;\n\t\t\t\t\t*out = x;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\tcollen--;\n\t\t\t\t}\n\t\t\t\twhile (replen > 0)\n\t\t\t\t{\n\t\t\t\t\tx = last_line[indexw * 4] + color;\n\t\t\t\t\t*out = x;\n\t\t\t\t\tout += 4;\n\t\t\t\t\tindexw++;\n\t\t\t\t\treplen--;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tindexh++;\n\t\tlast_line = this_line;\n\t}\n\treturn (int) (in - org_in);\n}", "label_name": "Base", "label": 1} {"code": "BOOL rdp_read_share_control_header(wStream* s, UINT16* length, UINT16* type, UINT16* channel_id)\n{\n\tif (Stream_GetRemainingLength(s) < 2)\n\t\treturn FALSE;\n\n\t/* Share Control Header */\n\tStream_Read_UINT16(s, *length); /* totalLength */\n\n\t/* If length is 0x8000 then we actually got a flow control PDU that we should ignore\n\t http://msdn.microsoft.com/en-us/library/cc240576.aspx */\n\tif (*length == 0x8000)\n\t{\n\t\trdp_read_flow_control_pdu(s, type);\n\t\t*channel_id = 0;\n\t\t*length = 8; /* Flow control PDU is 8 bytes */\n\t\treturn TRUE;\n\t}\n\n\tif (((size_t)*length - 2) > Stream_GetRemainingLength(s))\n\t\treturn FALSE;\n\n\tStream_Read_UINT16(s, *type); /* pduType */\n\t*type &= 0x0F; /* type is in the 4 least significant bits */\n\n\tif (*length > 4)\n\t\tStream_Read_UINT16(s, *channel_id); /* pduSource */\n\telse\n\t\t*channel_id = 0; /* Windows XP can send such short DEACTIVATE_ALL PDUs. */\n\n\treturn TRUE;\n}", "label_name": "Base", "label": 1} -{"code": "static int sanitize_ptr_alu(struct bpf_verifier_env *env,\n\t\t\t struct bpf_insn *insn,\n\t\t\t const struct bpf_reg_state *ptr_reg,\n\t\t\t struct bpf_reg_state *dst_reg,\n\t\t\t bool off_is_neg)\n{\n\tstruct bpf_verifier_state *vstate = env->cur_state;\n\tstruct bpf_insn_aux_data *aux = cur_aux(env);\n\tbool ptr_is_dst_reg = ptr_reg == dst_reg;\n\tu8 opcode = BPF_OP(insn->code);\n\tu32 alu_state, alu_limit;\n\tstruct bpf_reg_state tmp;\n\tbool ret;\n\n\tif (env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K)\n\t\treturn 0;\n\n\t/* We already marked aux for masking from non-speculative\n\t * paths, thus we got here in the first place. We only care\n\t * to explore bad access from here.\n\t */\n\tif (vstate->speculative)\n\t\tgoto do_sim;\n\n\talu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;\n\talu_state |= ptr_is_dst_reg ?\n\t\t BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;\n\n\tif (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))\n\t\treturn 0;\n\n\t/* If we arrived here from different branches with different\n\t * limits to sanitize, then this won't work.\n\t */\n\tif (aux->alu_state &&\n\t (aux->alu_state != alu_state ||\n\t aux->alu_limit != alu_limit))\n\t\treturn -EACCES;\n\n\t/* Corresponding fixup done in fixup_bpf_calls(). */\n\taux->alu_state = alu_state;\n\taux->alu_limit = alu_limit;\n\ndo_sim:\n\t/* Simulate and find potential out-of-bounds access under\n\t * speculative execution from truncation as a result of\n\t * masking when off was not within expected range. If off\n\t * sits in dst, then we temporarily need to move ptr there\n\t * to simulate dst (== 0) +/-= ptr. Needed, for example,\n\t * for cases where we use K-based arithmetic in one direction\n\t * and truncated reg-based in the other in order to explore\n\t * bad access.\n\t */\n\tif (!ptr_is_dst_reg) {\n\t\ttmp = *dst_reg;\n\t\t*dst_reg = *ptr_reg;\n\t}\n\tret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);\n\tif (!ptr_is_dst_reg)\n\t\t*dst_reg = tmp;\n\treturn !ret ? -EFAULT : 0;\n}", "label_name": "CWE-189", "label": "CWE-189"} {"code": "PredictorEncodeTile(TIFF* tif, uint8* bp0, tmsize_t cc0, uint16 s)\n{\n\tstatic const char module[] = \"PredictorEncodeTile\";\n\tTIFFPredictorState *sp = PredictorState(tif);\n uint8 *working_copy;\n\ttmsize_t cc = cc0, rowsize;\n\tunsigned char* bp;\n int result_code;\n\n\tassert(sp != NULL);\n\tassert(sp->encodepfunc != NULL);\n\tassert(sp->encodetile != NULL);\n\n /* \n * Do predictor manipulation in a working buffer to avoid altering\n * the callers buffer. http://trac.osgeo.org/gdal/ticket/1965\n */\n working_copy = (uint8*) _TIFFmalloc(cc0);\n if( working_copy == NULL )\n {\n TIFFErrorExt(tif->tif_clientdata, module, \n \"Out of memory allocating \" TIFF_SSIZE_FORMAT \" byte temp buffer.\",\n cc0 );\n return 0;\n }\n memcpy( working_copy, bp0, cc0 );\n bp = working_copy;\n\n\trowsize = sp->rowsize;\n\tassert(rowsize > 0);\n\tassert((cc0%rowsize)==0);\n\twhile (cc > 0) {\n\t\t(*sp->encodepfunc)(tif, bp, rowsize);\n\t\tcc -= rowsize;\n\t\tbp += rowsize;\n\t}\n\tresult_code = (*sp->encodetile)(tif, working_copy, cc0, s);\n\n _TIFFfree( working_copy );\n\n return result_code;\n}", "label_name": "Class", "label": 2} {"code": "static int trusted_update(struct key *key, struct key_preparsed_payload *prep)\n{\n\tstruct trusted_key_payload *p = key->payload.data[0];\n\tstruct trusted_key_payload *new_p;\n\tstruct trusted_key_options *new_o;\n\tsize_t datalen = prep->datalen;\n\tchar *datablob;\n\tint ret = 0;\n\n\tif (!p->migratable)\n\t\treturn -EPERM;\n\tif (datalen <= 0 || datalen > 32767 || !prep->data)\n\t\treturn -EINVAL;\n\n\tdatablob = kmalloc(datalen + 1, GFP_KERNEL);\n\tif (!datablob)\n\t\treturn -ENOMEM;\n\tnew_o = trusted_options_alloc();\n\tif (!new_o) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}\n\tnew_p = trusted_payload_alloc(key);\n\tif (!new_p) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}\n\n\tmemcpy(datablob, prep->data, datalen);\n\tdatablob[datalen] = '\\0';\n\tret = datablob_parse(datablob, new_p, new_o);\n\tif (ret != Opt_update) {\n\t\tret = -EINVAL;\n\t\tkfree(new_p);\n\t\tgoto out;\n\t}\n\n\tif (!new_o->keyhandle) {\n\t\tret = -EINVAL;\n\t\tkfree(new_p);\n\t\tgoto out;\n\t}\n\n\t/* copy old key values, and reseal with new pcrs */\n\tnew_p->migratable = p->migratable;\n\tnew_p->key_len = p->key_len;\n\tmemcpy(new_p->key, p->key, p->key_len);\n\tdump_payload(p);\n\tdump_payload(new_p);\n\n\tret = key_seal(new_p, new_o);\n\tif (ret < 0) {\n\t\tpr_info(\"trusted_key: key_seal failed (%d)\\n\", ret);\n\t\tkfree(new_p);\n\t\tgoto out;\n\t}\n\tif (new_o->pcrlock) {\n\t\tret = pcrlock(new_o->pcrlock);\n\t\tif (ret < 0) {\n\t\t\tpr_info(\"trusted_key: pcrlock failed (%d)\\n\", ret);\n\t\t\tkfree(new_p);\n\t\t\tgoto out;\n\t\t}\n\t}\n\trcu_assign_keypointer(key, new_p);\n\tcall_rcu(&p->rcu, trusted_rcu_free);\nout:\n\tkfree(datablob);\n\tkfree(new_o);\n\treturn ret;\n}", "label_name": "Class", "label": 2} {"code": "vips_foreign_load_start( VipsImage *out, void *a, void *b )\n{\n\tVipsForeignLoad *load = VIPS_FOREIGN_LOAD( b );\n\tVipsForeignLoadClass *class = VIPS_FOREIGN_LOAD_GET_CLASS( load );\n\n\tif( !load->real ) {\n\t\tif( !(load->real = vips_foreign_load_temp( load )) )\n\t\t\treturn( NULL );\n\n#ifdef DEBUG\n\t\tprintf( \"vips_foreign_load_start: triggering ->load()\\n\" );\n#endif /*DEBUG*/\n\n\t\t/* Read the image in. This may involve a long computation and\n\t\t * will finish with load->real holding the decompressed image. \n\t\t *\n\t\t * We want our caller to be able to see this computation on\n\t\t * @out, so eval signals on ->real need to appear on ->out.\n\t\t */\n\t\tload->real->progress_signal = load->out;\n\n\t\t/* Note the load object on the image. Loaders can use \n\t\t * this to signal invalidate if they hit a load error. See\n\t\t * vips_foreign_load_invalidate() below.\n\t\t */\n\t\tg_object_set_qdata( G_OBJECT( load->real ), \n\t\t\tvips__foreign_load_operation, load ); \n\n\t\tif( class->load( load ) ||\n\t\t\tvips_image_pio_input( load->real ) ) \n\t\t\treturn( NULL );\n\n\t\t/* ->header() read the header into @out, load has read the\n\t\t * image into @real. They must match exactly in size, bands,\n\t\t * format and coding for the copy to work. \n\t\t *\n\t\t * Some versions of ImageMagick give different results between\n\t\t * Ping and Load for some formats, for example.\n\t\t */\n\t\tif( !vips_foreign_load_iscompat( load->real, out ) )\n\t\t\treturn( NULL );\n\n\t\t/* We have to tell vips that out depends on real. We've set\n\t\t * the demand hint below, but not given an input there.\n\t\t */\n\t\tvips_image_pipelinev( load->out, load->out->dhint, \n\t\t\tload->real, NULL );\n\t}\n\n\treturn( vips_region_new( load->real ) );\n}", "label_name": "Class", "label": 2} {"code": "fixExec2Error(int action,\n u_char * var_val,\n u_char var_val_type,\n size_t var_val_len,\n u_char * statP, oid * name, size_t name_len)\n{\n netsnmp_old_extend *exten = NULL;\n unsigned int idx;\n\n idx = name[name_len-1] -1;\n exten = &compatability_entries[ idx ];\n\n#ifndef NETSNMP_NO_WRITE_SUPPORT\n switch (action) {\n case MODE_SET_RESERVE1:\n if (var_val_type != ASN_INTEGER) {\n snmp_log(LOG_ERR, \"Wrong type != int\\n\");\n return SNMP_ERR_WRONGTYPE;\n }\n idx = *((long *) var_val);\n if (idx != 1) {\n snmp_log(LOG_ERR, \"Wrong value != 1\\n\");\n return SNMP_ERR_WRONGVALUE;\n }\n if (!exten || !exten->efix_entry) {\n snmp_log(LOG_ERR, \"No command to run\\n\");\n return SNMP_ERR_GENERR;\n }\n return SNMP_ERR_NOERROR;\n\n case MODE_SET_COMMIT:\n netsnmp_cache_check_and_reload( exten->efix_entry->cache );\n }\n#endif /* !NETSNMP_NO_WRITE_SUPPORT */\n return SNMP_ERR_NOERROR;\n}", "label_name": "Class", "label": 2} {"code": "mcs_recv_connect_response(STREAM mcs_data)\n{\n\tUNUSED(mcs_data);\n\tuint8 result;\n\tint length;\n\tSTREAM s;\n\tRD_BOOL is_fastpath;\n\tuint8 fastpath_hdr;\n\n\tlogger(Protocol, Debug, \"%s()\", __func__);\n\ts = iso_recv(&is_fastpath, &fastpath_hdr);\n\n\tif (s == NULL)\n\t\treturn False;\n\n\tber_parse_header(s, MCS_CONNECT_RESPONSE, &length);\n\n\tber_parse_header(s, BER_TAG_RESULT, &length);\n\tin_uint8(s, result);\n\tif (result != 0)\n\t{\n\t\tlogger(Protocol, Error, \"mcs_recv_connect_response(), result=%d\", result);\n\t\treturn False;\n\t}\n\n\tber_parse_header(s, BER_TAG_INTEGER, &length);\n\tin_uint8s(s, length);\t/* connect id */\n\tmcs_parse_domain_params(s);\n\n\tber_parse_header(s, BER_TAG_OCTET_STRING, &length);\n\n\tsec_process_mcs_data(s);\n\t/*\n\t if (length > mcs_data->size)\n\t {\n\t logger(Protocol, Error, \"mcs_recv_connect_response(), expected length=%d, got %d\",length, mcs_data->size);\n\t length = mcs_data->size;\n\t }\n\n\t in_uint8a(s, mcs_data->data, length);\n\t mcs_data->p = mcs_data->data;\n\t mcs_data->end = mcs_data->data + length;\n\t */\n\treturn s_check_end(s);\n}", "label_name": "Base", "label": 1} {"code": "init_normalization(struct compiling *c)\n{\n PyObject *m = PyImport_ImportModuleNoBlock(\"unicodedata\");\n if (!m)\n return 0;\n c->c_normalize = PyObject_GetAttrString(m, \"normalize\");\n Py_DECREF(m);\n if (!c->c_normalize)\n return 0;\n c->c_normalize_args = Py_BuildValue(\"(sN)\", \"NFKC\", Py_None);\n if (!c->c_normalize_args) {\n Py_CLEAR(c->c_normalize);\n return 0;\n }\n PyTuple_SET_ITEM(c->c_normalize_args, 1, NULL);\n return 1;\n}", "label_name": "Base", "label": 1} -{"code": "void bpf_int_jit_compile(struct bpf_prog *prog)\n{\n\tstruct bpf_binary_header *header = NULL;\n\tint proglen, oldproglen = 0;\n\tstruct jit_context ctx = {};\n\tu8 *image = NULL;\n\tint *addrs;\n\tint pass;\n\tint i;\n\n\tif (!bpf_jit_enable)\n\t\treturn;\n\n\tif (!prog || !prog->len)\n\t\treturn;\n\n\taddrs = kmalloc(prog->len * sizeof(*addrs), GFP_KERNEL);\n\tif (!addrs)\n\t\treturn;\n\n\t/* Before first pass, make a rough estimation of addrs[]\n\t * each bpf instruction is translated to less than 64 bytes\n\t */\n\tfor (proglen = 0, i = 0; i < prog->len; i++) {\n\t\tproglen += 64;\n\t\taddrs[i] = proglen;\n\t}\n\tctx.cleanup_addr = proglen;\n\n\tfor (pass = 0; pass < 10; pass++) {\n\t\tproglen = do_jit(prog, addrs, image, oldproglen, &ctx);\n\t\tif (proglen <= 0) {\n\t\t\timage = NULL;\n\t\t\tif (header)\n\t\t\t\tbpf_jit_binary_free(header);\n\t\t\tgoto out;\n\t\t}\n\t\tif (image) {\n\t\t\tif (proglen != oldproglen) {\n\t\t\t\tpr_err(\"bpf_jit: proglen=%d != oldproglen=%d\\n\",\n\t\t\t\t proglen, oldproglen);\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tif (proglen == oldproglen) {\n\t\t\theader = bpf_jit_binary_alloc(proglen, &image,\n\t\t\t\t\t\t 1, jit_fill_hole);\n\t\t\tif (!header)\n\t\t\t\tgoto out;\n\t\t}\n\t\toldproglen = proglen;\n\t}\n\n\tif (bpf_jit_enable > 1)\n\t\tbpf_jit_dump(prog->len, proglen, 0, image);\n\n\tif (image) {\n\t\tbpf_flush_icache(header, image + proglen);\n\t\tset_memory_ro((unsigned long)header, header->pages);\n\t\tprog->bpf_func = (void *)image;\n\t\tprog->jited = true;\n\t}\nout:\n\tkfree(addrs);\n}", "label_name": "CWE-17", "label": "CWE-17"} {"code": "check_entry_size_and_hooks(struct ip6t_entry *e,\n\t\t\t struct xt_table_info *newinfo,\n\t\t\t const unsigned char *base,\n\t\t\t const unsigned char *limit,\n\t\t\t const unsigned int *hook_entries,\n\t\t\t const unsigned int *underflows,\n\t\t\t unsigned int valid_hooks)\n{\n\tunsigned int h;\n\tint err;\n\n\tif ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 ||\n\t (unsigned char *)e + sizeof(struct ip6t_entry) >= limit) {\n\t\tduprintf(\"Bad offset %p\\n\", e);\n\t\treturn -EINVAL;\n\t}\n\n\tif (e->next_offset\n\t < sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) {\n\t\tduprintf(\"checking: element %p size %u\\n\",\n\t\t\t e, e->next_offset);\n\t\treturn -EINVAL;\n\t}\n\n\terr = check_entry(e);\n\tif (err)\n\t\treturn err;\n\n\t/* Check hooks & underflows */\n\tfor (h = 0; h < NF_INET_NUMHOOKS; h++) {\n\t\tif (!(valid_hooks & (1 << h)))\n\t\t\tcontinue;\n\t\tif ((unsigned char *)e - base == hook_entries[h])\n\t\t\tnewinfo->hook_entry[h] = hook_entries[h];\n\t\tif ((unsigned char *)e - base == underflows[h]) {\n\t\t\tif (!check_underflow(e)) {\n\t\t\t\tpr_err(\"Underflows must be unconditional and \"\n\t\t\t\t \"use the STANDARD target with \"\n\t\t\t\t \"ACCEPT/DROP\\n\");\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\t\t\tnewinfo->underflow[h] = underflows[h];\n\t\t}\n\t}\n\n\t/* Clear counters and comefrom */\n\te->counters = ((struct xt_counters) { 0, 0 });\n\te->comefrom = 0;\n\treturn 0;\n}", "label_name": "Class", "label": 2} {"code": "n_start_visual_mode(int c)\n{\n#ifdef FEAT_CONCEAL\n int cursor_line_was_concealed = curwin->w_p_cole > 0\n\t\t\t\t\t\t&& conceal_cursor_line(curwin);\n#endif\n\n VIsual_mode = c;\n VIsual_active = TRUE;\n VIsual_reselect = TRUE;\n trigger_modechanged();\n\n // Corner case: the 0 position in a tab may change when going into\n // virtualedit. Recalculate curwin->w_cursor to avoid bad highlighting.\n if (c == Ctrl_V && (get_ve_flags() & VE_BLOCK) && gchar_cursor() == TAB)\n {\n\tvalidate_virtcol();\n\tcoladvance(curwin->w_virtcol);\n }\n VIsual = curwin->w_cursor;\n\n#ifdef FEAT_FOLDING\n foldAdjustVisual();\n#endif\n\n setmouse();\n#ifdef FEAT_CONCEAL\n // Check if redraw is needed after changing the state.\n conceal_check_cursor_line(cursor_line_was_concealed);\n#endif\n\n if (p_smd && msg_silent == 0)\n\tredraw_cmdline = TRUE;\t// show visual mode later\n#ifdef FEAT_CLIPBOARD\n // Make sure the clipboard gets updated. Needed because start and\n // end may still be the same, and the selection needs to be owned\n clip_star.vmode = NUL;\n#endif\n\n // Only need to redraw this line, unless still need to redraw an old\n // Visual area (when 'lazyredraw' is set).\n if (curwin->w_redr_type < INVERTED)\n {\n\tcurwin->w_old_cursor_lnum = curwin->w_cursor.lnum;\n\tcurwin->w_old_visual_lnum = curwin->w_cursor.lnum;\n }\n}", "label_name": "Variant", "label": 0} {"code": "static int xen_netbk_get_extras(struct xenvif *vif,\n\t\t\t\tstruct xen_netif_extra_info *extras,\n\t\t\t\tint work_to_do)\n{\n\tstruct xen_netif_extra_info extra;\n\tRING_IDX cons = vif->tx.req_cons;\n\n\tdo {\n\t\tif (unlikely(work_to_do-- <= 0)) {\n\t\t\tnetdev_dbg(vif->dev, \"Missing extra info\\n\");\n\t\t\treturn -EBADR;\n\t\t}\n\n\t\tmemcpy(&extra, RING_GET_REQUEST(&vif->tx, cons),\n\t\t sizeof(extra));\n\t\tif (unlikely(!extra.type ||\n\t\t\t extra.type >= XEN_NETIF_EXTRA_TYPE_MAX)) {\n\t\t\tvif->tx.req_cons = ++cons;\n\t\t\tnetdev_dbg(vif->dev,\n\t\t\t\t \"Invalid extra type: %d\\n\", extra.type);\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tmemcpy(&extras[extra.type - 1], &extra, sizeof(extra));\n\t\tvif->tx.req_cons = ++cons;\n\t} while (extra.flags & XEN_NETIF_EXTRA_FLAG_MORE);\n\n\treturn work_to_do;\n}", "label_name": "Class", "label": 2} @@ -1080,7 +1065,6 @@ {"code": "int ipmi_si_port_setup(struct si_sm_io *io)\n{\n\tunsigned int addr = io->addr_data;\n\tint idx;\n\n\tif (!addr)\n\t\treturn -ENODEV;\n\n\tio->io_cleanup = port_cleanup;\n\n\t/*\n\t * Figure out the actual inb/inw/inl/etc routine to use based\n\t * upon the register size.\n\t */\n\tswitch (io->regsize) {\n\tcase 1:\n\t\tio->inputb = port_inb;\n\t\tio->outputb = port_outb;\n\t\tbreak;\n\tcase 2:\n\t\tio->inputb = port_inw;\n\t\tio->outputb = port_outw;\n\t\tbreak;\n\tcase 4:\n\t\tio->inputb = port_inl;\n\t\tio->outputb = port_outl;\n\t\tbreak;\n\tdefault:\n\t\tdev_warn(io->dev, \"Invalid register size: %d\\n\",\n\t\t\t io->regsize);\n\t\treturn -EINVAL;\n\t}\n\n\t/*\n\t * Some BIOSes reserve disjoint I/O regions in their ACPI\n\t * tables. This causes problems when trying to register the\n\t * entire I/O region. Therefore we must register each I/O\n\t * port separately.\n\t */\n\tfor (idx = 0; idx < io->io_size; idx++) {\n\t\tif (request_region(addr + idx * io->regspacing,\n\t\t\t\t io->regsize, DEVICE_NAME) == NULL) {\n\t\t\t/* Undo allocations */\n\t\t\twhile (idx--)\n\t\t\t\trelease_region(addr + idx * io->regspacing,\n\t\t\t\t\t io->regsize);\n\t\t\treturn -EIO;\n\t\t}\n\t}\n\treturn 0;\n}", "label_name": "Variant", "label": 0} {"code": "init_ctx_new(OM_uint32 *minor_status,\n\t spnego_gss_cred_id_t spcred,\n\t gss_ctx_id_t *ctx,\n\t send_token_flag *tokflag)\n{\n\tOM_uint32 ret;\n\tspnego_gss_ctx_id_t sc = NULL;\n\n\tsc = create_spnego_ctx();\n\tif (sc == NULL)\n\t\treturn GSS_S_FAILURE;\n\n\t/* determine negotiation mech set */\n\tret = get_negotiable_mechs(minor_status, spcred, GSS_C_INITIATE,\n\t\t\t\t &sc->mech_set);\n\tif (ret != GSS_S_COMPLETE)\n\t\tgoto cleanup;\n\n\t/* Set an initial internal mech to make the first context token. */\n\tsc->internal_mech = &sc->mech_set->elements[0];\n\n\tif (put_mech_set(sc->mech_set, &sc->DER_mechTypes) < 0) {\n\t\tret = GSS_S_FAILURE;\n\t\tgoto cleanup;\n\t}\n\t/*\n\t * The actual context is not yet determined, set the output\n\t * context handle to refer to the spnego context itself.\n\t */\n\tsc->ctx_handle = GSS_C_NO_CONTEXT;\n\t*ctx = (gss_ctx_id_t)sc;\n\tsc = NULL;\n\t*tokflag = INIT_TOKEN_SEND;\n\tret = GSS_S_CONTINUE_NEEDED;\n\ncleanup:\n\trelease_spnego_ctx(&sc);\n\treturn ret;\n}", "label_name": "Base", "label": 1} {"code": "int qeth_snmp_command(struct qeth_card *card, char __user *udata)\n{\n\tstruct qeth_cmd_buffer *iob;\n\tstruct qeth_ipa_cmd *cmd;\n\tstruct qeth_snmp_ureq *ureq;\n\tint req_len;\n\tstruct qeth_arp_query_info qinfo = {0, };\n\tint rc = 0;\n\n\tQETH_CARD_TEXT(card, 3, \"snmpcmd\");\n\n\tif (card->info.guestlan)\n\t\treturn -EOPNOTSUPP;\n\n\tif ((!qeth_adp_supported(card, IPA_SETADP_SET_SNMP_CONTROL)) &&\n\t (!card->options.layer2)) {\n\t\treturn -EOPNOTSUPP;\n\t}\n\t/* skip 4 bytes (data_len struct member) to get req_len */\n\tif (copy_from_user(&req_len, udata + sizeof(int), sizeof(int)))\n\t\treturn -EFAULT;\n\tureq = memdup_user(udata, req_len + sizeof(struct qeth_snmp_ureq_hdr));\n\tif (IS_ERR(ureq)) {\n\t\tQETH_CARD_TEXT(card, 2, \"snmpnome\");\n\t\treturn PTR_ERR(ureq);\n\t}\n\tqinfo.udata_len = ureq->hdr.data_len;\n\tqinfo.udata = kzalloc(qinfo.udata_len, GFP_KERNEL);\n\tif (!qinfo.udata) {\n\t\tkfree(ureq);\n\t\treturn -ENOMEM;\n\t}\n\tqinfo.udata_offset = sizeof(struct qeth_snmp_ureq_hdr);\n\n\tiob = qeth_get_adapter_cmd(card, IPA_SETADP_SET_SNMP_CONTROL,\n\t\t\t\t QETH_SNMP_SETADP_CMDLENGTH + req_len);\n\tcmd = (struct qeth_ipa_cmd *)(iob->data+IPA_PDU_HEADER_SIZE);\n\tmemcpy(&cmd->data.setadapterparms.data.snmp, &ureq->cmd, req_len);\n\trc = qeth_send_ipa_snmp_cmd(card, iob, QETH_SETADP_BASE_LEN + req_len,\n\t\t\t\t qeth_snmp_command_cb, (void *)&qinfo);\n\tif (rc)\n\t\tQETH_DBF_MESSAGE(2, \"SNMP command failed on %s: (0x%x)\\n\",\n\t\t\t QETH_CARD_IFNAME(card), rc);\n\telse {\n\t\tif (copy_to_user(udata, qinfo.udata, qinfo.udata_len))\n\t\t\trc = -EFAULT;\n\t}\n\n\tkfree(ureq);\n\tkfree(qinfo.udata);\n\treturn rc;\n}", "label_name": "Class", "label": 2} -{"code": "choose_filters(struct archive_read *a)\n{\n\tint number_bidders, i, bid, best_bid;\n\tstruct archive_read_filter_bidder *bidder, *best_bidder;\n\tstruct archive_read_filter *filter;\n\tssize_t avail;\n\tint r;\n\n\tfor (;;) {\n\t\tnumber_bidders = sizeof(a->bidders) / sizeof(a->bidders[0]);\n\n\t\tbest_bid = 0;\n\t\tbest_bidder = NULL;\n\n\t\tbidder = a->bidders;\n\t\tfor (i = 0; i < number_bidders; i++, bidder++) {\n\t\t\tif (bidder->bid != NULL) {\n\t\t\t\tbid = (bidder->bid)(bidder, a->filter);\n\t\t\t\tif (bid > best_bid) {\n\t\t\t\t\tbest_bid = bid;\n\t\t\t\t\tbest_bidder = bidder;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/* If no bidder, we're done. */\n\t\tif (best_bidder == NULL) {\n\t\t\t/* Verify the filter by asking it for some data. */\n\t\t\t__archive_read_filter_ahead(a->filter, 1, &avail);\n\t\t\tif (avail < 0) {\n\t\t\t\t__archive_read_close_filters(a);\n\t\t\t\t__archive_read_free_filters(a);\n\t\t\t\treturn (ARCHIVE_FATAL);\n\t\t\t}\n\t\t\ta->archive.compression_name = a->filter->name;\n\t\t\ta->archive.compression_code = a->filter->code;\n\t\t\treturn (ARCHIVE_OK);\n\t\t}\n\n\t\tfilter\n\t\t = (struct archive_read_filter *)calloc(1, sizeof(*filter));\n\t\tif (filter == NULL)\n\t\t\treturn (ARCHIVE_FATAL);\n\t\tfilter->bidder = best_bidder;\n\t\tfilter->archive = a;\n\t\tfilter->upstream = a->filter;\n\t\ta->filter = filter;\n\t\tr = (best_bidder->init)(a->filter);\n\t\tif (r != ARCHIVE_OK) {\n\t\t\t__archive_read_close_filters(a);\n\t\t\t__archive_read_free_filters(a);\n\t\t\treturn (ARCHIVE_FATAL);\n\t\t}\n\t}\n}", "label_name": "CWE-399", "label": "CWE-399"} {"code": "void trustedDkgVerifyAES(int *errStatus, char *errString, const char *public_shares, const char *s_share,\n uint8_t *encryptedPrivateKey, uint64_t enc_len, unsigned _t, int _ind, int *result) {\n LOG_INFO(__FUNCTION__);\n\n INIT_ERROR_STATE\n\n CHECK_STATE(public_shares);\n CHECK_STATE(s_share);\n CHECK_STATE(encryptedPrivateKey);\n\n SAFE_CHAR_BUF(skey, ECDSA_SKEY_LEN);\n\n mpz_t s;\n mpz_init(s);\n\n int status = AES_decrypt(encryptedPrivateKey, enc_len, skey, ECDSA_SKEY_LEN);\n\n CHECK_STATUS2(\"AES_decrypt failed (in trustedDkgVerifyAES) with status %d\");\n\n SAFE_CHAR_BUF(encr_sshare, ECDSA_SKEY_LEN);\n\n strncpy(encr_sshare, s_share, ECDSA_SKEY_LEN - 1);\n\n SAFE_CHAR_BUF(common_key, ECDSA_SKEY_LEN);\n\n status = session_key_recover(skey, s_share, common_key);\n\n CHECK_STATUS(\"session_key_recover failed\");\n\n SAFE_CHAR_BUF(decr_sshare, ECDSA_SKEY_LEN);\n\n status=xor_decrypt(common_key, encr_sshare, decr_sshare);\n\n CHECK_STATUS(\"xor_decrypt failed\")\n\n\n status = mpz_set_str(s, decr_sshare, 16);\n CHECK_STATUS(\"invalid decr secret share\");\n\n *result = Verification(public_shares, s, _t, _ind);\n\n SET_SUCCESS\n clean:\n\n mpz_clear(s);\n LOG_INFO(__FUNCTION__ );\n LOG_INFO(\"SGX call completed\");\n}", "label_name": "Base", "label": 1} {"code": "static int validate_user_key(struct fscrypt_info *crypt_info,\n\t\t\tstruct fscrypt_context *ctx, u8 *raw_key,\n\t\t\tconst char *prefix)\n{\n\tchar *description;\n\tstruct key *keyring_key;\n\tstruct fscrypt_key *master_key;\n\tconst struct user_key_payload *ukp;\n\tint res;\n\n\tdescription = kasprintf(GFP_NOFS, \"%s%*phN\", prefix,\n\t\t\t\tFS_KEY_DESCRIPTOR_SIZE,\n\t\t\t\tctx->master_key_descriptor);\n\tif (!description)\n\t\treturn -ENOMEM;\n\n\tkeyring_key = request_key(&key_type_logon, description, NULL);\n\tkfree(description);\n\tif (IS_ERR(keyring_key))\n\t\treturn PTR_ERR(keyring_key);\n\n\tif (keyring_key->type != &key_type_logon) {\n\t\tprintk_once(KERN_WARNING\n\t\t\t\t\"%s: key type must be logon\\n\", __func__);\n\t\tres = -ENOKEY;\n\t\tgoto out;\n\t}\n\tdown_read(&keyring_key->sem);\n\tukp = user_key_payload(keyring_key);\n\tif (ukp->datalen != sizeof(struct fscrypt_key)) {\n\t\tres = -EINVAL;\n\t\tup_read(&keyring_key->sem);\n\t\tgoto out;\n\t}\n\tmaster_key = (struct fscrypt_key *)ukp->data;\n\tBUILD_BUG_ON(FS_AES_128_ECB_KEY_SIZE != FS_KEY_DERIVATION_NONCE_SIZE);\n\n\tif (master_key->size != FS_AES_256_XTS_KEY_SIZE) {\n\t\tprintk_once(KERN_WARNING\n\t\t\t\t\"%s: key size incorrect: %d\\n\",\n\t\t\t\t__func__, master_key->size);\n\t\tres = -ENOKEY;\n\t\tup_read(&keyring_key->sem);\n\t\tgoto out;\n\t}\n\tres = derive_key_aes(ctx->nonce, master_key->raw, raw_key);\n\tup_read(&keyring_key->sem);\n\tif (res)\n\t\tgoto out;\n\n\tcrypt_info->ci_keyring_key = keyring_key;\n\treturn 0;\nout:\n\tkey_put(keyring_key);\n\treturn res;\n}", "label_name": "Base", "label": 1} {"code": "void TEMPLATE(process_block_dec)(decoder_info_t *decoder_info,int size,int yposY,int xposY,int sub)\n{\n int width = decoder_info->width;\n int height = decoder_info->height;\n stream_t *stream = decoder_info->stream;\n frame_type_t frame_type = decoder_info->frame_info.frame_type;\n int split_flag = 0;\n\n if (yposY >= height || xposY >= width)\n return;\n\n int decode_this_size = (yposY + size <= height) && (xposY + size <= width);\n int decode_rectangular_size = !decode_this_size && frame_type != I_FRAME;\n\n int bit_start = stream->bitcnt;\n\n int mode = MODE_SKIP;\n \n block_context_t block_context;\n TEMPLATE(find_block_contexts)(yposY, xposY, height, width, size, decoder_info->deblock_data, &block_context, decoder_info->use_block_contexts);\n decoder_info->block_context = &block_context;\n\n split_flag = decode_super_mode(decoder_info,size,decode_this_size);\n mode = decoder_info->mode;\n \n /* Read delta_qp and set block-level qp */\n if (size == (1<log2_sb_size) && (split_flag || mode != MODE_SKIP) && decoder_info->max_delta_qp > 0) {\n /* Read delta_qp */\n int delta_qp = read_delta_qp(stream);\n int prev_qp;\n if (yposY == 0 && xposY == 0)\n prev_qp = decoder_info->frame_info.qp;\n else\n prev_qp = decoder_info->frame_info.qpb;\n decoder_info->frame_info.qpb = prev_qp + delta_qp;\n }\n\n decoder_info->bit_count.super_mode[decoder_info->bit_count.stat_frame_type] += (stream->bitcnt - bit_start);\n\n if (split_flag){\n int new_size = size/2;\n TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+0*new_size,xposY+0*new_size,sub);\n TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+1*new_size,xposY+0*new_size,sub);\n TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+0*new_size,xposY+1*new_size,sub);\n TEMPLATE(process_block_dec)(decoder_info,new_size,yposY+1*new_size,xposY+1*new_size,sub);\n }\n else if (decode_this_size || decode_rectangular_size){\n decode_block(decoder_info,size,yposY,xposY,sub);\n }\n}", "label_name": "Class", "label": 2} @@ -1102,7 +1086,6 @@ {"code": "static int sd_isoc_init(struct gspca_dev *gspca_dev)\n{\n\tstruct usb_host_interface *alt;\n\tint max_packet_size;\n\n\tswitch (gspca_dev->pixfmt.width) {\n\tcase 160:\n\t\tmax_packet_size = 450;\n\t\tbreak;\n\tcase 176:\n\t\tmax_packet_size = 600;\n\t\tbreak;\n\tdefault:\n\t\tmax_packet_size = 1022;\n\t\tbreak;\n\t}\n\n\t/* Start isoc bandwidth \"negotiation\" at max isoc bandwidth */\n\talt = &gspca_dev->dev->actconfig->intf_cache[0]->altsetting[1];\n\talt->endpoint[0].desc.wMaxPacketSize = cpu_to_le16(max_packet_size);\n\n\treturn 0;\n}", "label_name": "Base", "label": 1} {"code": "static int jpc_ppm_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)\n{\n\tjpc_ppm_t *ppm = &ms->parms.ppm;\n\n\t/* Eliminate compiler warning about unused variables. */\n\tcstate = 0;\n\n\tif (JAS_CAST(uint, jas_stream_write(out, (char *) ppm->data, ppm->len)) != ppm->len) {\n\t\treturn -1;\n\t}\n\treturn 0;\n}", "label_name": "Base", "label": 1} {"code": "static void get_nb10(ut8* dbg_data, SCV_NB10_HEADER* res) {\n\tconst int nb10sz = 16;\n\tmemcpy (res, dbg_data, nb10sz);\n\tres->file_name = (ut8*) strdup ((const char*) dbg_data + nb10sz);\n}", "label_name": "Base", "label": 1} -{"code": "static int crypto_rng_report(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\tstruct crypto_report_rng rrng;\n\n\tsnprintf(rrng.type, CRYPTO_MAX_ALG_NAME, \"%s\", \"rng\");\n\n\trrng.seedsize = alg->cra_rng.seedsize;\n\n\tif (nla_put(skb, CRYPTOCFGA_REPORT_RNG,\n\t\t sizeof(struct crypto_report_rng), &rrng))\n\t\tgoto nla_put_failure;\n\treturn 0;\n\nnla_put_failure:\n\treturn -EMSGSIZE;\n}", "label_name": "CWE-310", "label": "CWE-310"} {"code": "void cipso_v4_sock_delattr(struct sock *sk)\n{\n\tint hdr_delta;\n\tstruct ip_options *opt;\n\tstruct inet_sock *sk_inet;\n\n\tsk_inet = inet_sk(sk);\n\topt = sk_inet->opt;\n\tif (opt == NULL || opt->cipso == 0)\n\t\treturn;\n\n\thdr_delta = cipso_v4_delopt(&sk_inet->opt);\n\tif (sk_inet->is_icsk && hdr_delta > 0) {\n\t\tstruct inet_connection_sock *sk_conn = inet_csk(sk);\n\t\tsk_conn->icsk_ext_hdr_len -= hdr_delta;\n\t\tsk_conn->icsk_sync_mss(sk, sk_conn->icsk_pmtu_cookie);\n\t}\n}", "label_name": "Class", "label": 2} {"code": "cJSON *cJSON_DetachItemFromObject( cJSON *object, const char *string )\n{\n\tint i = 0;\n\tcJSON *c = object->child;\n\twhile ( c && cJSON_strcasecmp( c->string, string ) ) {\n\t\t++i;\n\t\tc = c->next;\n\t}\n\tif ( c )\n\t\treturn cJSON_DetachItemFromArray( object, i );\n\treturn 0;\n}", "label_name": "Base", "label": 1} {"code": "PGTYPESinterval_from_asc(char *str, char **endptr)\n{\n\tinterval *result = NULL;\n\tfsec_t\t\tfsec;\n\tstruct tm\ttt,\n\t\t\t *tm = &tt;\n\tint\t\t\tdtype;\n\tint\t\t\tnf;\n\tchar\t *field[MAXDATEFIELDS];\n\tint\t\t\tftype[MAXDATEFIELDS];\n\tchar\t\tlowstr[MAXDATELEN + MAXDATEFIELDS];\n\tchar\t *realptr;\n\tchar\t **ptr = (endptr != NULL) ? endptr : &realptr;\n\n\ttm->tm_year = 0;\n\ttm->tm_mon = 0;\n\ttm->tm_mday = 0;\n\ttm->tm_hour = 0;\n\ttm->tm_min = 0;\n\ttm->tm_sec = 0;\n\tfsec = 0;\n\n\tif (strlen(str) >= sizeof(lowstr))\n\t{\n\t\terrno = PGTYPES_INTVL_BAD_INTERVAL;\n\t\treturn NULL;\n\t}\n\n\tif (ParseDateTime(str, lowstr, field, ftype, &nf, ptr) != 0 ||\n\t\t(DecodeInterval(field, ftype, nf, &dtype, tm, &fsec) != 0 &&\n\t\t DecodeISO8601Interval(str, &dtype, tm, &fsec) != 0))\n\t{\n\t\terrno = PGTYPES_INTVL_BAD_INTERVAL;\n\t\treturn NULL;\n\t}\n\n\tresult = (interval *) pgtypes_alloc(sizeof(interval));\n\tif (!result)\n\t\treturn NULL;\n\n\tif (dtype != DTK_DELTA)\n\t{\n\t\terrno = PGTYPES_INTVL_BAD_INTERVAL;\n\t\tfree(result);\n\t\treturn NULL;\n\t}\n\n\tif (tm2interval(tm, fsec, result) != 0)\n\t{\n\t\terrno = PGTYPES_INTVL_BAD_INTERVAL;\n\t\tfree(result);\n\t\treturn NULL;\n\t}\n\n\terrno = 0;\n\treturn result;\n}", "label_name": "Class", "label": 2} @@ -1131,7 +1114,6 @@ {"code": "static void ftrace_syscall_exit(void *data, struct pt_regs *regs, long ret)\n{\n\tstruct trace_array *tr = data;\n\tstruct ftrace_event_file *ftrace_file;\n\tstruct syscall_trace_exit *entry;\n\tstruct syscall_metadata *sys_data;\n\tstruct ring_buffer_event *event;\n\tstruct ring_buffer *buffer;\n\tunsigned long irq_flags;\n\tint pc;\n\tint syscall_nr;\n\n\tsyscall_nr = trace_get_syscall_nr(current, regs);\n\tif (syscall_nr < 0)\n\t\treturn;\n\n\t/* Here we're inside tp handler's rcu_read_lock_sched (__DO_TRACE()) */\n\tftrace_file = rcu_dereference_sched(tr->exit_syscall_files[syscall_nr]);\n\tif (!ftrace_file)\n\t\treturn;\n\n\tif (ftrace_trigger_soft_disabled(ftrace_file))\n\t\treturn;\n\n\tsys_data = syscall_nr_to_meta(syscall_nr);\n\tif (!sys_data)\n\t\treturn;\n\n\tlocal_save_flags(irq_flags);\n\tpc = preempt_count();\n\n\tbuffer = tr->trace_buffer.buffer;\n\tevent = trace_buffer_lock_reserve(buffer,\n\t\t\tsys_data->exit_event->event.type, sizeof(*entry),\n\t\t\tirq_flags, pc);\n\tif (!event)\n\t\treturn;\n\n\tentry = ring_buffer_event_data(event);\n\tentry->nr = syscall_nr;\n\tentry->ret = syscall_get_return_value(current, regs);\n\n\tevent_trigger_unlock_commit(ftrace_file, buffer, event, entry,\n\t\t\t\t irq_flags, pc);\n}", "label_name": "Base", "label": 1} {"code": "error_t httpClientSetMethod(HttpClientContext *context, const char_t *method)\n{\n size_t m;\n size_t n;\n char_t *p;\n\n //Check parameters\n if(context == NULL || method == NULL)\n return ERROR_INVALID_PARAMETER;\n\n //Compute the length of the HTTP method\n n = osStrlen(method);\n\n //Make sure the length of the user name is acceptable\n if(n == 0 || n > HTTP_CLIENT_MAX_METHOD_LEN)\n return ERROR_INVALID_LENGTH;\n\n //Make sure the buffer contains a valid HTTP request\n if(context->bufferLen > HTTP_CLIENT_BUFFER_SIZE)\n return ERROR_INVALID_SYNTAX;\n\n //Properly terminate the string with a NULL character\n context->buffer[context->bufferLen] = '\\0';\n\n //The Request-Line begins with a method token\n p = strchr(context->buffer, ' ');\n //Any parsing error?\n if(p == NULL)\n return ERROR_INVALID_SYNTAX;\n\n //Compute the length of the current method token\n m = p - context->buffer;\n\n //Make sure the buffer is large enough to hold the new HTTP request method\n if((context->bufferLen + n - m) > HTTP_CLIENT_BUFFER_SIZE)\n return ERROR_BUFFER_OVERFLOW;\n\n //Make room for the new method token\n osMemmove(context->buffer + n, p, context->bufferLen + 1 - m);\n //Copy the new method token\n osStrncpy(context->buffer, method, n);\n\n //Adjust the length of the request header\n context->bufferLen = context->bufferLen + n - m;\n\n //Save HTTP request method\n osStrcpy(context->method, method);\n\n //Successful processing\n return NO_ERROR;\n}", "label_name": "Class", "label": 2} {"code": "static RFlagsAtOffset* r_flag_get_nearest_list(RFlag *f, ut64 off, int dir) {\n\tRFlagsAtOffset *flags = NULL;\n\tRFlagsAtOffset key;\n\tkey.off = off;\n\tif (dir >= 0) {\n\t\tflags = r_skiplist_get_geq (f->by_off, &key);\n\t} else {\n\t\tflags = r_skiplist_get_leq (f->by_off, &key);\n\t}\n\tif (dir == 0 && flags && flags->off != off) {\n\t\treturn NULL;\n\t}\n\treturn flags;\n}", "label_name": "Base", "label": 1} -{"code": "static void __exit exit_ext2_fs(void)\n{\n\tunregister_filesystem(&ext2_fs_type);\n\tdestroy_inodecache();\n\texit_ext2_xattr();\n}", "label_name": "CWE-19", "label": "CWE-19"} {"code": "static int sco_send_frame(struct sock *sk, struct msghdr *msg, int len)\n{\n\tstruct sco_conn *conn = sco_pi(sk)->conn;\n\tstruct sk_buff *skb;\n\tint err;\n\n\t/* Check outgoing MTU */\n\tif (len > conn->mtu)\n\t\treturn -EINVAL;\n\n\tBT_DBG(\"sk %p len %d\", sk, len);\n\n\tskb = bt_skb_send_alloc(sk, len, msg->msg_flags & MSG_DONTWAIT, &err);\n\tif (!skb)\n\t\treturn err;\n\n\tif (memcpy_from_msg(skb_put(skb, len), msg, len)) {\n\t\tkfree_skb(skb);\n\t\treturn -EFAULT;\n\t}\n\n\thci_send_sco(conn->hcon, skb);\n\n\treturn len;\n}", "label_name": "Variant", "label": 0} {"code": "static int vmci_transport_dgram_dequeue(struct kiocb *kiocb,\n\t\t\t\t\tstruct vsock_sock *vsk,\n\t\t\t\t\tstruct msghdr *msg, size_t len,\n\t\t\t\t\tint flags)\n{\n\tint err;\n\tint noblock;\n\tstruct vmci_datagram *dg;\n\tsize_t payload_len;\n\tstruct sk_buff *skb;\n\n\tnoblock = flags & MSG_DONTWAIT;\n\n\tif (flags & MSG_OOB || flags & MSG_ERRQUEUE)\n\t\treturn -EOPNOTSUPP;\n\n\tmsg->msg_namelen = 0;\n\n\t/* Retrieve the head sk_buff from the socket's receive queue. */\n\terr = 0;\n\tskb = skb_recv_datagram(&vsk->sk, flags, noblock, &err);\n\tif (err)\n\t\treturn err;\n\n\tif (!skb)\n\t\treturn -EAGAIN;\n\n\tdg = (struct vmci_datagram *)skb->data;\n\tif (!dg)\n\t\t/* err is 0, meaning we read zero bytes. */\n\t\tgoto out;\n\n\tpayload_len = dg->payload_size;\n\t/* Ensure the sk_buff matches the payload size claimed in the packet. */\n\tif (payload_len != skb->len - sizeof(*dg)) {\n\t\terr = -EINVAL;\n\t\tgoto out;\n\t}\n\n\tif (payload_len > len) {\n\t\tpayload_len = len;\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t}\n\n\t/* Place the datagram payload in the user's iovec. */\n\terr = skb_copy_datagram_iovec(skb, sizeof(*dg), msg->msg_iov,\n\t\tpayload_len);\n\tif (err)\n\t\tgoto out;\n\n\tif (msg->msg_name) {\n\t\tstruct sockaddr_vm *vm_addr;\n\n\t\t/* Provide the address of the sender. */\n\t\tvm_addr = (struct sockaddr_vm *)msg->msg_name;\n\t\tvsock_addr_init(vm_addr, dg->src.context, dg->src.resource);\n\t\tmsg->msg_namelen = sizeof(*vm_addr);\n\t}\n\terr = payload_len;\n\nout:\n\tskb_free_datagram(&vsk->sk, skb);\n\treturn err;\n}", "label_name": "Class", "label": 2} {"code": "static int generate(struct crypto_rng *tfm, const u8 *src, unsigned int slen,\n\t\t u8 *dst, unsigned int dlen)\n{\n\treturn crypto_old_rng_alg(tfm)->rng_make_random(tfm, dst, dlen);\n}", "label_name": "Base", "label": 1} @@ -1154,7 +1136,6 @@ {"code": "int socket_accept(int fd, uint16_t port)\n{\n#ifdef WIN32\n\tint addr_len;\n#else\n\tsocklen_t addr_len;\n#endif\n\tint result;\n\tstruct sockaddr_in addr;\n\n\tmemset(&addr, 0, sizeof(addr));\n\taddr.sin_family = AF_INET;\n\taddr.sin_addr.s_addr = htonl(INADDR_ANY);\n\taddr.sin_port = htons(port);\n\n\taddr_len = sizeof(addr);\n\tresult = accept(fd, (struct sockaddr*)&addr, &addr_len);\n\n\treturn result;\n}", "label_name": "Pillar", "label": 3} {"code": "static __exit void sctp_exit(void)\n{\n\t/* BUG. This should probably do something useful like clean\n\t * up all the remaining associations and all that memory.\n\t */\n\n\t/* Unregister with inet6/inet layers. */\n\tsctp_v6_del_protocol();\n\tsctp_v4_del_protocol();\n\n\tunregister_pernet_subsys(&sctp_net_ops);\n\n\t/* Free protosw registrations */\n\tsctp_v6_protosw_exit();\n\tsctp_v4_protosw_exit();\n\n\t/* Unregister with socket layer. */\n\tsctp_v6_pf_exit();\n\tsctp_v4_pf_exit();\n\n\tsctp_sysctl_unregister();\n\n\tfree_pages((unsigned long)sctp_assoc_hashtable,\n\t\t get_order(sctp_assoc_hashsize *\n\t\t\t sizeof(struct sctp_hashbucket)));\n\tkfree(sctp_ep_hashtable);\n\tfree_pages((unsigned long)sctp_port_hashtable,\n\t\t get_order(sctp_port_hashsize *\n\t\t\t sizeof(struct sctp_bind_hashbucket)));\n\n\tpercpu_counter_destroy(&sctp_sockets_allocated);\n\n\trcu_barrier(); /* Wait for completion of call_rcu()'s */\n\n\tkmem_cache_destroy(sctp_chunk_cachep);\n\tkmem_cache_destroy(sctp_bucket_cachep);\n}", "label_name": "Class", "label": 2} {"code": "read_attribute(cdk_stream_t inp, size_t pktlen, cdk_pkt_userid_t attr,\n\t int name_size)\n{\n\tconst byte *p;\n\tbyte *buf;\n\tsize_t len, nread;\n\tcdk_error_t rc;\n\n\tif (!inp || !attr || !pktlen)\n\t\treturn CDK_Inv_Value;\n\n\tif (DEBUG_PKT)\n\t\t_gnutls_write_log(\"read_attribute: %d octets\\n\",\n\t\t\t\t (int) pktlen);\n\n\t_gnutls_str_cpy(attr->name, name_size, ATTRIBUTE);\n\tattr->len = MIN(name_size, sizeof(ATTRIBUTE) - 1);\n\n\tbuf = cdk_calloc(1, pktlen);\n\tif (!buf)\n\t\treturn CDK_Out_Of_Core;\n\trc = stream_read(inp, buf, pktlen, &nread);\n\tif (rc) {\n\t\tcdk_free(buf);\n\t\treturn CDK_Inv_Packet;\n\t}\n\tp = buf;\n\tlen = *p++;\n\tpktlen--;\n\tif (len == 255) {\n\t\tlen = _cdk_buftou32(p);\n\t\tp += 4;\n\t\tpktlen -= 4;\n\t} else if (len >= 192) {\n\t\tif (pktlen < 2) {\n\t\t\tcdk_free(buf);\n\t\t\treturn CDK_Inv_Packet;\n\t\t}\n\t\tlen = ((len - 192) << 8) + *p + 192;\n\t\tp++;\n\t\tpktlen--;\n\t}\n\n\tif (*p != 1) {\t\t/* Currently only 1, meaning an image, is defined. */\n\t\tcdk_free(buf);\n\t\treturn CDK_Inv_Packet;\n\t}\n\tp++;\n\tlen--;\n\n\tif (len >= pktlen) {\n\t\tcdk_free(buf);\n\t\treturn CDK_Inv_Packet;\n\t}\n\tattr->attrib_img = cdk_calloc(1, len);\n\tif (!attr->attrib_img) {\n\t\tcdk_free(buf);\n\t\treturn CDK_Out_Of_Core;\n\t}\n\tattr->attrib_len = len;\n\tmemcpy(attr->attrib_img, p, len);\n\tcdk_free(buf);\n\treturn rc;\n}", "label_name": "Class", "label": 2} -{"code": "ext4_xattr_put_super(struct super_block *sb)\n{\n\tmb_cache_shrink(sb->s_bdev);\n}", "label_name": "CWE-19", "label": "CWE-19"} {"code": "void trustedEnclaveInit(uint32_t _logLevel) {\n CALL_ONCE\n LOG_INFO(__FUNCTION__);\n\n globalLogLevel_ = _logLevel;\n\n oc_realloc_func = &reallocate_function;\n oc_free_func = &free_function;\n\n LOG_INFO(\"Setting memory functions\");\n\n mp_get_memory_functions(NULL, &gmp_realloc_func, &gmp_free_func);\n mp_set_memory_functions(NULL, oc_realloc_func, oc_free_func);\n\n LOG_INFO(\"Calling enclave init\");\n\n\n enclave_init();\n\n\n LOG_INFO(\"Reading random\");\n\n globalRandom = calloc(32,1);\n\n int ret = sgx_read_rand(globalRandom, 32);\n\n if(ret != SGX_SUCCESS)\n {\n LOG_ERROR(\"sgx_read_rand failed. Aboring enclave.\");\n abort();\n }\n\n LOG_INFO(\"Successfully inited enclave. Signed enclave version:\" SIGNED_ENCLAVE_VERSION );\n#ifndef SGX_DEBUG\n LOG_INFO(\"SECURITY WARNING: sgxwallet is running in INSECURE DEBUG MODE! NEVER USE IN PRODUCTION!\");\n#endif\n\n#if SGX_DEBUG != 0\n LOG_INFO(\"SECURITY WARNING: sgxwallet is running in INSECURE DEBUG MODE! NEVER USE IN PRODUCTION!\");\n#endif\n\n#if SGX_MODE == SIM\n LOG_INFO(\"SECURITY WARNING: sgxwallet is running in INSECURE SIMULATION MODE! NEVER USE IN PRODUCTION!\");\n#endif\n\n\n\n\n\n\n}", "label_name": "Base", "label": 1} {"code": "swabHorDiff16(TIFF* tif, uint8* cp0, tmsize_t cc)\n{\n uint16* wp = (uint16*) cp0;\n tmsize_t wc = cc / 2;\n\n horDiff16(tif, cp0, cc);\n\n TIFFSwabArrayOfShort(wp, wc);\n}", "label_name": "Class", "label": 2} {"code": "static void voutf(struct GlobalConfig *config,\n const char *prefix,\n const char *fmt,\n va_list ap)\n{\n size_t width = (79 - strlen(prefix));\n if(!config->mute) {\n size_t len;\n char *ptr;\n char *print_buffer;\n\n print_buffer = curlx_mvaprintf(fmt, ap);\n if(!print_buffer)\n return;\n len = strlen(print_buffer);\n\n ptr = print_buffer;\n while(len > 0) {\n fputs(prefix, config->errors);\n\n if(len > width) {\n size_t cut = width-1;\n\n while(!ISSPACE(ptr[cut]) && cut) {\n cut--;\n }\n if(0 == cut)\n /* not a single cutting position was found, just cut it at the\n max text width then! */\n cut = width-1;\n\n (void)fwrite(ptr, cut + 1, 1, config->errors);\n fputs(\"\\n\", config->errors);\n ptr += cut + 1; /* skip the space too */\n len -= cut;\n }\n else {\n fputs(ptr, config->errors);\n len = 0;\n }\n }\n curl_free(print_buffer);\n }\n}", "label_name": "Base", "label": 1} @@ -1168,11 +1149,9 @@ {"code": "void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)\n{\n\tstruct btrfs_fs_info *fs_info = trans->fs_info;\n\tstruct btrfs_transaction *cur_trans = trans->transaction;\n\n\tif (!trans->chunk_bytes_reserved)\n\t\treturn;\n\n\tWARN_ON_ONCE(!list_empty(&trans->new_bgs));\n\n\tbtrfs_block_rsv_release(fs_info, &fs_info->chunk_block_rsv,\n\t\t\t\ttrans->chunk_bytes_reserved, NULL);\n\tatomic64_sub(trans->chunk_bytes_reserved, &cur_trans->chunk_bytes_reserved);\n\tcond_wake_up(&cur_trans->chunk_reserve_wait);\n\ttrans->chunk_bytes_reserved = 0;\n}", "label_name": "Class", "label": 2} {"code": "static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag,\n uint32_t lun, void *hba_private)\n{\n SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);\n SCSIRequest *req;\n SCSIDiskReq *r;\n\n req = scsi_req_alloc(&scsi_disk_reqops, &s->qdev, tag, lun, hba_private);\n r = DO_UPCAST(SCSIDiskReq, req, req);\n r->iov.iov_base = qemu_blockalign(s->bs, SCSI_DMA_BUF_SIZE);\n return req;\n}", "label_name": "Class", "label": 2} {"code": "int wcall_i_answer(struct wcall *wcall,\n\t\t int call_type, int audio_cbr)\n{\n\tint err = 0;\n\tbool cbr = audio_cbr != 0;\n\n\tif (!wcall) {\n\t\twarning(\"wcall; answer: no wcall\\n\");\n\t\treturn EINVAL;\n\t}\n\n\tcall_type = (call_type == WCALL_CALL_TYPE_FORCED_AUDIO) ?\n\t\t WCALL_CALL_TYPE_NORMAL : call_type;\n\n\tinfo(APITAG \"wcall(%p): answer calltype=%s\\n\",\n\t wcall, wcall_call_type_name(call_type));\n\n\tif (wcall->disable_audio)\n\t\twcall->disable_audio = false;\n\t\n\tif (!wcall->icall) {\n\t\twarning(\"wcall(%p): answer: no call object found\\n\", wcall);\n\t\treturn ENOTSUP;\n\t}\n\tset_state(wcall, WCALL_STATE_ANSWERED);\n\n\tif (call_type == WCALL_CALL_TYPE_VIDEO) {\n\t\tICALL_CALL(wcall->icall,\n\t\t\t set_video_send_state,\n\t\t\t ICALL_VIDEO_STATE_STARTED);\n\t}\n\telse {\n\t\tICALL_CALL(wcall->icall,\n\t\t\t set_video_send_state,\n\t\t\t ICALL_VIDEO_STATE_STOPPED);\n\t}\n\t\n\terr = ICALL_CALLE(wcall->icall, answer,\n\t\t\t call_type, cbr);\n\n\treturn err;\n}", "label_name": "Base", "label": 1} -{"code": "static int crypto_rng_report(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\tstruct crypto_report_rng rrng;\n\n\tsnprintf(rrng.type, CRYPTO_MAX_ALG_NAME, \"%s\", \"rng\");\n\n\trrng.seedsize = alg->cra_rng.seedsize;\n\n\tif (nla_put(skb, CRYPTOCFGA_REPORT_RNG,\n\t\t sizeof(struct crypto_report_rng), &rrng))\n\t\tgoto nla_put_failure;\n\treturn 0;\n\nnla_put_failure:\n\treturn -EMSGSIZE;\n}", "label_name": "CWE-310", "label": "CWE-310"} {"code": "xfs_acl_from_disk(struct xfs_acl *aclp)\n{\n\tstruct posix_acl_entry *acl_e;\n\tstruct posix_acl *acl;\n\tstruct xfs_acl_entry *ace;\n\tint count, i;\n\n\tcount = be32_to_cpu(aclp->acl_cnt);\n\tif (count > XFS_ACL_MAX_ENTRIES)\n\t\treturn ERR_PTR(-EFSCORRUPTED);\n\n\tacl = posix_acl_alloc(count, GFP_KERNEL);\n\tif (!acl)\n\t\treturn ERR_PTR(-ENOMEM);\n\n\tfor (i = 0; i < count; i++) {\n\t\tacl_e = &acl->a_entries[i];\n\t\tace = &aclp->acl_entry[i];\n\n\t\t/*\n\t\t * The tag is 32 bits on disk and 16 bits in core.\n\t\t *\n\t\t * Because every access to it goes through the core\n\t\t * format first this is not a problem.\n\t\t */\n\t\tacl_e->e_tag = be32_to_cpu(ace->ae_tag);\n\t\tacl_e->e_perm = be16_to_cpu(ace->ae_perm);\n\n\t\tswitch (acl_e->e_tag) {\n\t\tcase ACL_USER:\n\t\tcase ACL_GROUP:\n\t\t\tacl_e->e_id = be32_to_cpu(ace->ae_id);\n\t\t\tbreak;\n\t\tcase ACL_USER_OBJ:\n\t\tcase ACL_GROUP_OBJ:\n\t\tcase ACL_MASK:\n\t\tcase ACL_OTHER:\n\t\t\tacl_e->e_id = ACL_UNDEFINED_ID;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tgoto fail;\n\t\t}\n\t}\n\treturn acl;\n\nfail:\n\tposix_acl_release(acl);\n\treturn ERR_PTR(-EINVAL);\n}", "label_name": "Base", "label": 1} {"code": "skip_string(char_u *p)\n{\n int\t i;\n\n // We loop, because strings may be concatenated: \"date\"\"time\".\n for ( ; ; ++p)\n {\n\tif (p[0] == '\\'')\t\t // 'c' or '\\n' or '\\000'\n\t{\n\t if (p[1] == NUL)\t\t // ' at end of line\n\t\tbreak;\n\t i = 2;\n\t if (p[1] == '\\\\' && p[2] != NUL) // '\\n' or '\\000'\n\t {\n\t\t++i;\n\t\twhile (vim_isdigit(p[i - 1])) // '\\000'\n\t\t ++i;\n\t }\n\t if (p[i] == '\\'')\t\t // check for trailing '\n\t {\n\t\tp += i;\n\t\tcontinue;\n\t }\n\t}\n\telse if (p[0] == '\"')\t\t // start of string\n\t{\n\t for (++p; p[0]; ++p)\n\t {\n\t\tif (p[0] == '\\\\' && p[1] != NUL)\n\t\t ++p;\n\t\telse if (p[0] == '\"')\t // end of string\n\t\t break;\n\t }\n\t if (p[0] == '\"')\n\t\tcontinue; // continue for another string\n\t}\n\telse if (p[0] == 'R' && p[1] == '\"')\n\t{\n\t // Raw string: R\"[delim](...)[delim]\"\n\t char_u *delim = p + 2;\n\t char_u *paren = vim_strchr(delim, '(');\n\n\t if (paren != NULL)\n\t {\n\t\tsize_t delim_len = paren - delim;\n\n\t\tfor (p += 3; *p; ++p)\n\t\t if (p[0] == ')' && STRNCMP(p + 1, delim, delim_len) == 0\n\t\t\t && p[delim_len + 1] == '\"')\n\t\t {\n\t\t\tp += delim_len + 1;\n\t\t\tbreak;\n\t\t }\n\t\tif (p[0] == '\"')\n\t\t continue; // continue for another string\n\t }\n\t}\n\tbreak;\t\t\t\t // no string found\n }\n if (!*p)\n\t--p;\t\t\t\t // backup from NUL\n return p;\n}", "label_name": "Base", "label": 1} {"code": "ParseNameValue(const char * buffer, int bufsize,\n struct NameValueParserData * data)\n{\n\tstruct xmlparser parser;\n\tdata->l_head = NULL;\n\tdata->portListing = NULL;\n\tdata->portListingLength = 0;\n\t/* init xmlparser object */\n\tparser.xmlstart = buffer;\n\tparser.xmlsize = bufsize;\n\tparser.data = data;\n\tparser.starteltfunc = NameValueParserStartElt;\n\tparser.endeltfunc = NameValueParserEndElt;\n\tparser.datafunc = NameValueParserGetData;\n\tparser.attfunc = 0;\n\tparsexml(&parser);\n}", "label_name": "Class", "label": 2} -{"code": "static int br_multicast_add_group(struct net_bridge *br,\n\t\t\t\t struct net_bridge_port *port,\n\t\t\t\t struct br_ip *group)\n{\n\tstruct net_bridge_mdb_entry *mp;\n\tstruct net_bridge_port_group *p;\n\tstruct net_bridge_port_group __rcu **pp;\n\tunsigned long now = jiffies;\n\tint err;\n\n\tspin_lock(&br->multicast_lock);\n\tif (!netif_running(br->dev) ||\n\t (port && port->state == BR_STATE_DISABLED))\n\t\tgoto out;\n\n\tmp = br_multicast_new_group(br, port, group);\n\terr = PTR_ERR(mp);\n\tif (IS_ERR(mp))\n\t\tgoto err;\n\n\tif (!port) {\n\t\thlist_add_head(&mp->mglist, &br->mglist);\n\t\tmod_timer(&mp->timer, now + br->multicast_membership_interval);\n\t\tgoto out;\n\t}\n\n\tfor (pp = &mp->ports;\n\t (p = mlock_dereference(*pp, br)) != NULL;\n\t pp = &p->next) {\n\t\tif (p->port == port)\n\t\t\tgoto found;\n\t\tif ((unsigned long)p->port < (unsigned long)port)\n\t\t\tbreak;\n\t}\n\n\tp = kzalloc(sizeof(*p), GFP_ATOMIC);\n\terr = -ENOMEM;\n\tif (unlikely(!p))\n\t\tgoto err;\n\n\tp->addr = *group;\n\tp->port = port;\n\tp->next = *pp;\n\thlist_add_head(&p->mglist, &port->mglist);\n\tsetup_timer(&p->timer, br_multicast_port_group_expired,\n\t\t (unsigned long)p);\n\tsetup_timer(&p->query_timer, br_multicast_port_group_query_expired,\n\t\t (unsigned long)p);\n\n\trcu_assign_pointer(*pp, p);\n\nfound:\n\tmod_timer(&p->timer, now + br->multicast_membership_interval);\nout:\n\terr = 0;\n\nerr:\n\tspin_unlock(&br->multicast_lock);\n\treturn err;\n}", "label_name": "CWE-399", "label": "CWE-399"} {"code": "static int read_private_key(RSA *rsa)\n{\n\tint r;\n\tsc_path_t path;\n\tsc_file_t *file;\n\tconst sc_acl_entry_t *e;\n\n\tu8 buf[2048], *p = buf;\n\tsize_t bufsize, keysize;\n\n\tr = select_app_df();\n\tif (r)\n\t\treturn 1;\n\tsc_format_path(\"I0012\", &path);\n\tr = sc_select_file(card, &path, &file);\n\tif (r) {\n\t\tfprintf(stderr, \"Unable to select private key file: %s\\n\", sc_strerror(r));\n\t\treturn 2;\n\t}\n\te = sc_file_get_acl_entry(file, SC_AC_OP_READ);\n\tif (e == NULL || e->method == SC_AC_NEVER)\n\t\treturn 10;\n\tbufsize = file->size;\n\tsc_file_free(file);\n\tr = sc_read_binary(card, 0, buf, bufsize, 0);\n\tif (r < 0) {\n\t\tfprintf(stderr, \"Unable to read private key file: %s\\n\", sc_strerror(r));\n\t\treturn 2;\n\t}\n\tbufsize = r;\n\tdo {\n\t\tif (bufsize < 4)\n\t\t\treturn 3;\n\t\tkeysize = (p[0] << 8) | p[1];\n\t\tif (keysize == 0)\n\t\t\tbreak;\n\t\tif (keysize < 3)\n\t\t\treturn 3;\n\t\tif (p[2] == opt_key_num)\n\t\t\tbreak;\n\t\tp += keysize;\n\t\tbufsize -= keysize;\n\t} while (1);\n\tif (keysize == 0) {\n\t\tprintf(\"Key number %d not found.\\n\", opt_key_num);\n\t\treturn 2;\n\t}\n\treturn parse_private_key(p, keysize, rsa);\n}", "label_name": "Class", "label": 2} {"code": "cJSON *cJSON_CreateArray( void )\n{\n\tcJSON *item = cJSON_New_Item();\n\tif ( item )\n\t\titem->type = cJSON_Array;\n\treturn item;\n}", "label_name": "Base", "label": 1} {"code": "static int crypto_ccm_auth(struct aead_request *req, struct scatterlist *plain,\n\t\t\t unsigned int cryptlen)\n{\n\tstruct crypto_ccm_req_priv_ctx *pctx = crypto_ccm_reqctx(req);\n\tstruct crypto_aead *aead = crypto_aead_reqtfm(req);\n\tstruct crypto_ccm_ctx *ctx = crypto_aead_ctx(aead);\n\tAHASH_REQUEST_ON_STACK(ahreq, ctx->mac);\n\tunsigned int assoclen = req->assoclen;\n\tstruct scatterlist sg[3];\n\tu8 odata[16];\n\tu8 idata[16];\n\tint ilen, err;\n\n\t/* format control data for input */\n\terr = format_input(odata, req, cryptlen);\n\tif (err)\n\t\tgoto out;\n\n\tsg_init_table(sg, 3);\n\tsg_set_buf(&sg[0], odata, 16);\n\n\t/* format associated data and compute into mac */\n\tif (assoclen) {\n\t\tilen = format_adata(idata, assoclen);\n\t\tsg_set_buf(&sg[1], idata, ilen);\n\t\tsg_chain(sg, 3, req->src);\n\t} else {\n\t\tilen = 0;\n\t\tsg_chain(sg, 2, req->src);\n\t}\n\n\tahash_request_set_tfm(ahreq, ctx->mac);\n\tahash_request_set_callback(ahreq, pctx->flags, NULL, NULL);\n\tahash_request_set_crypt(ahreq, sg, NULL, assoclen + ilen + 16);\n\terr = crypto_ahash_init(ahreq);\n\tif (err)\n\t\tgoto out;\n\terr = crypto_ahash_update(ahreq);\n\tif (err)\n\t\tgoto out;\n\n\t/* we need to pad the MAC input to a round multiple of the block size */\n\tilen = 16 - (assoclen + ilen) % 16;\n\tif (ilen < 16) {\n\t\tmemset(idata, 0, ilen);\n\t\tsg_init_table(sg, 2);\n\t\tsg_set_buf(&sg[0], idata, ilen);\n\t\tif (plain)\n\t\t\tsg_chain(sg, 2, plain);\n\t\tplain = sg;\n\t\tcryptlen += ilen;\n\t}\n\n\tahash_request_set_crypt(ahreq, plain, pctx->odata, cryptlen);\n\terr = crypto_ahash_finup(ahreq);\nout:\n\treturn err;\n}", "label_name": "Class", "label": 2} @@ -1183,7 +1162,6 @@ {"code": "static int uvesafb_setcmap(struct fb_cmap *cmap, struct fb_info *info)\n{\n\tstruct uvesafb_pal_entry *entries;\n\tint shift = 16 - dac_width;\n\tint i, err = 0;\n\n\tif (info->var.bits_per_pixel == 8) {\n\t\tif (cmap->start + cmap->len > info->cmap.start +\n\t\t info->cmap.len || cmap->start < info->cmap.start)\n\t\t\treturn -EINVAL;\n\n\t\tentries = kmalloc(sizeof(*entries) * cmap->len, GFP_KERNEL);\n\t\tif (!entries)\n\t\t\treturn -ENOMEM;\n\n\t\tfor (i = 0; i < cmap->len; i++) {\n\t\t\tentries[i].red = cmap->red[i] >> shift;\n\t\t\tentries[i].green = cmap->green[i] >> shift;\n\t\t\tentries[i].blue = cmap->blue[i] >> shift;\n\t\t\tentries[i].pad = 0;\n\t\t}\n\t\terr = uvesafb_setpalette(entries, cmap->len, cmap->start, info);\n\t\tkfree(entries);\n\t} else {\n\t\t/*\n\t\t * For modes with bpp > 8, we only set the pseudo palette in\n\t\t * the fb_info struct. We rely on uvesafb_setcolreg to do all\n\t\t * sanity checking.\n\t\t */\n\t\tfor (i = 0; i < cmap->len; i++) {\n\t\t\terr |= uvesafb_setcolreg(cmap->start + i, cmap->red[i],\n\t\t\t\t\t\tcmap->green[i], cmap->blue[i],\n\t\t\t\t\t\t0, info);\n\t\t}\n\t}\n\treturn err;\n}", "label_name": "Base", "label": 1} {"code": "static int jpc_ppm_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)\n{\n\tjpc_ppm_t *ppm = &ms->parms.ppm;\n\n\t/* Eliminate compiler warning about unused variables. */\n\tcstate = 0;\n\n\tppm->data = 0;\n\n\tif (ms->len < 1) {\n\t\tgoto error;\n\t}\n\tif (jpc_getuint8(in, &ppm->ind)) {\n\t\tgoto error;\n\t}\n\n\tppm->len = ms->len - 1;\n\tif (ppm->len > 0) {\n\t\tif (!(ppm->data = jas_malloc(ppm->len))) {\n\t\t\tgoto error;\n\t\t}\n\t\tif (JAS_CAST(uint, jas_stream_read(in, ppm->data, ppm->len)) != ppm->len) {\n\t\t\tgoto error;\n\t\t}\n\t} else {\n\t\tppm->data = 0;\n\t}\n\treturn 0;\n\nerror:\n\tjpc_ppm_destroyparms(ms);\n\treturn -1;\n}", "label_name": "Class", "label": 2} {"code": "webSocketsHasDataInBuffer(rfbClientPtr cl)\n{\n ws_ctx_t *wsctx = (ws_ctx_t *)cl->wsctx;\n\n if (wsctx && wsctx->readbuflen)\n return TRUE;\n\n return (cl->sslctx && rfbssl_pending(cl) > 0);\n}", "label_name": "Base", "label": 1} -{"code": "static int crypto_blkcipher_report(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\tstruct crypto_report_blkcipher rblkcipher;\n\n\tsnprintf(rblkcipher.type, CRYPTO_MAX_ALG_NAME, \"%s\", \"blkcipher\");\n\tsnprintf(rblkcipher.geniv, CRYPTO_MAX_ALG_NAME, \"%s\",\n\t\t alg->cra_blkcipher.geniv ?: \"\");\n\n\trblkcipher.blocksize = alg->cra_blocksize;\n\trblkcipher.min_keysize = alg->cra_blkcipher.min_keysize;\n\trblkcipher.max_keysize = alg->cra_blkcipher.max_keysize;\n\trblkcipher.ivsize = alg->cra_blkcipher.ivsize;\n\n\tif (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER,\n\t\t sizeof(struct crypto_report_blkcipher), &rblkcipher))\n\t\tgoto nla_put_failure;\n\treturn 0;\n\nnla_put_failure:\n\treturn -EMSGSIZE;\n}", "label_name": "CWE-310", "label": "CWE-310"} {"code": "key_ref_t keyring_search(key_ref_t keyring,\n\t\t\t struct key_type *type,\n\t\t\t const char *description)\n{\n\tstruct keyring_search_context ctx = {\n\t\t.index_key.type\t\t= type,\n\t\t.index_key.description\t= description,\n\t\t.cred\t\t\t= current_cred(),\n\t\t.match_data.cmp\t\t= type->match,\n\t\t.match_data.raw_data\t= description,\n\t\t.match_data.lookup_type\t= KEYRING_SEARCH_LOOKUP_DIRECT,\n\t\t.flags\t\t\t= KEYRING_SEARCH_DO_STATE_CHECK,\n\t};\n\tkey_ref_t key;\n\tint ret;\n\n\tif (!ctx.match_data.cmp)\n\t\treturn ERR_PTR(-ENOKEY);\n\n\tif (type->match_preparse) {\n\t\tret = type->match_preparse(&ctx.match_data);\n\t\tif (ret < 0)\n\t\t\treturn ERR_PTR(ret);\n\t}\n\n\tkey = keyring_search_aux(keyring, &ctx);\n\n\tif (type->match_free)\n\t\ttype->match_free(&ctx.match_data);\n\treturn key;\n}", "label_name": "Base", "label": 1} {"code": "static int pn_recvmsg(struct kiocb *iocb, struct sock *sk,\n\t\t\tstruct msghdr *msg, size_t len, int noblock,\n\t\t\tint flags, int *addr_len)\n{\n\tstruct sk_buff *skb = NULL;\n\tstruct sockaddr_pn sa;\n\tint rval = -EOPNOTSUPP;\n\tint copylen;\n\n\tif (flags & ~(MSG_PEEK|MSG_TRUNC|MSG_DONTWAIT|MSG_NOSIGNAL|\n\t\t\tMSG_CMSG_COMPAT))\n\t\tgoto out_nofree;\n\n\tif (addr_len)\n\t\t*addr_len = sizeof(sa);\n\n\tskb = skb_recv_datagram(sk, flags, noblock, &rval);\n\tif (skb == NULL)\n\t\tgoto out_nofree;\n\n\tpn_skb_get_src_sockaddr(skb, &sa);\n\n\tcopylen = skb->len;\n\tif (len < copylen) {\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t\tcopylen = len;\n\t}\n\n\trval = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copylen);\n\tif (rval) {\n\t\trval = -EFAULT;\n\t\tgoto out;\n\t}\n\n\trval = (flags & MSG_TRUNC) ? skb->len : copylen;\n\n\tif (msg->msg_name != NULL)\n\t\tmemcpy(msg->msg_name, &sa, sizeof(struct sockaddr_pn));\n\nout:\n\tskb_free_datagram(sk, skb);\n\nout_nofree:\n\treturn rval;\n}", "label_name": "Class", "label": 2} {"code": "cJSON *cJSON_CreateFalse( void )\n{\n\tcJSON *item = cJSON_New_Item();\n\tif ( item )\n\t\titem->type = cJSON_False;\n\treturn item;\n}", "label_name": "Base", "label": 1} @@ -1193,7 +1171,6 @@ {"code": "static void nsc_rle_decompress_data(NSC_CONTEXT* context)\n{\n\tUINT16 i;\n\tBYTE* rle;\n\tUINT32 planeSize;\n\tUINT32 originalSize;\n\trle = context->Planes;\n\n\tfor (i = 0; i < 4; i++)\n\t{\n\t\toriginalSize = context->OrgByteCount[i];\n\t\tplaneSize = context->PlaneByteCount[i];\n\n\t\tif (planeSize == 0)\n\t\t\tFillMemory(context->priv->PlaneBuffers[i], originalSize, 0xFF);\n\t\telse if (planeSize < originalSize)\n\t\t\tnsc_rle_decode(rle, context->priv->PlaneBuffers[i], originalSize);\n\t\telse\n\t\t\tCopyMemory(context->priv->PlaneBuffers[i], rle, originalSize);\n\n\t\trle += planeSize;\n\t}\n}", "label_name": "Base", "label": 1} {"code": "static void iwjpeg_scan_exif(struct iwjpegrcontext *rctx,\n\t\tconst iw_byte *d, size_t d_len)\n{\n\tstruct iw_exif_state e;\n\tiw_uint32 ifd;\n\n\tif(d_len<8) return;\n\n\tiw_zeromem(&e,sizeof(struct iw_exif_state));\n\te.d = d;\n\te.d_len = d_len;\n\n\te.endian = d[0]=='I' ? IW_ENDIAN_LITTLE : IW_ENDIAN_BIG;\n\n\tifd = iw_get_ui32_e(&d[4],e.endian);\n\n\tiwjpeg_scan_exif_ifd(rctx,&e,ifd);\n}", "label_name": "Base", "label": 1} {"code": "int __fsnotify_parent(const struct path *path, struct dentry *dentry, __u32 mask)\n{\n\tstruct dentry *parent;\n\tstruct inode *p_inode;\n\tint ret = 0;\n\n\tif (!dentry)\n\t\tdentry = path->dentry;\n\n\tif (!(dentry->d_flags & DCACHE_FSNOTIFY_PARENT_WATCHED))\n\t\treturn 0;\n\n\tparent = dget_parent(dentry);\n\tp_inode = parent->d_inode;\n\n\tif (unlikely(!fsnotify_inode_watches_children(p_inode)))\n\t\t__fsnotify_update_child_dentry_flags(p_inode);\n\telse if (p_inode->i_fsnotify_mask & mask) {\n\t\t/* we are notifying a parent so come up with the new mask which\n\t\t * specifies these are events which came from a child. */\n\t\tmask |= FS_EVENT_ON_CHILD;\n\n\t\tif (path)\n\t\t\tret = fsnotify(p_inode, mask, path, FSNOTIFY_EVENT_PATH,\n\t\t\t\t dentry->d_name.name, 0);\n\t\telse\n\t\t\tret = fsnotify(p_inode, mask, dentry->d_inode, FSNOTIFY_EVENT_INODE,\n\t\t\t\t dentry->d_name.name, 0);\n\t}\n\n\tdput(parent);\n\n\treturn ret;\n}", "label_name": "Class", "label": 2} -{"code": "void *hashtable_iter_at(hashtable_t *hashtable, const char *key)\n{\n pair_t *pair;\n size_t hash;\n bucket_t *bucket;\n\n hash = hash_str(key);\n bucket = &hashtable->buckets[hash % num_buckets(hashtable)];\n\n pair = hashtable_find_pair(hashtable, bucket, key, hash);\n if(!pair)\n return NULL;\n\n return &pair->list;\n}", "label_name": "CWE-310", "label": "CWE-310"} {"code": "ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep)\n{\n\tint totlen;\n\tuint32_t t;\n\n\tif (p[0] & 0x80)\n\t\ttotlen = 4;\n\telse\n\t\ttotlen = 4 + EXTRACT_16BITS(&p[2]);\n\tif (ep < p + totlen) {\n\t\tND_PRINT((ndo,\"[|attr]\"));\n\t\treturn ep + 1;\n\t}\n\n\tND_PRINT((ndo,\"(\"));\n\tt = EXTRACT_16BITS(&p[0]) & 0x7fff;\n\tND_PRINT((ndo,\"type=#%d \", t));\n\tif (p[0] & 0x80) {\n\t\tND_PRINT((ndo,\"value=\"));\n\t\tt = p[2];\n\t\trawprint(ndo, (const uint8_t *)&p[2], 2);\n\t} else {\n\t\tND_PRINT((ndo,\"len=%d value=\", EXTRACT_16BITS(&p[2])));\n\t\trawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));\n\t}\n\tND_PRINT((ndo,\")\"));\n\treturn p + totlen;\n}", "label_name": "Base", "label": 1} {"code": "SPL_METHOD(DirectoryIterator, key)\n{\n\tspl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);\n\t\n\tif (zend_parse_parameters_none() == FAILURE) {\n\t\treturn;\n\t}\n\n\tif (intern->u.dir.dirp) {\n\t\tRETURN_LONG(intern->u.dir.index);\n\t} else {\n\t\tRETURN_FALSE;\n\t}\n}", "label_name": "Base", "label": 1} {"code": "pci_emul_add_msicap(struct pci_vdev *dev, int msgnum)\n{\n\tstruct msicap msicap;\n\n\tpci_populate_msicap(&msicap, msgnum, 0);\n\n\treturn pci_emul_add_capability(dev, (u_char *)&msicap, sizeof(msicap));\n}", "label_name": "Base", "label": 1} @@ -1202,17 +1179,14 @@ {"code": "int cipso_v4_sock_getattr(struct sock *sk, struct netlbl_lsm_secattr *secattr)\n{\n\tstruct ip_options *opt;\n\n\topt = inet_sk(sk)->opt;\n\tif (opt == NULL || opt->cipso == 0)\n\t\treturn -ENOMSG;\n\n\treturn cipso_v4_getattr(opt->__data + opt->cipso - sizeof(struct iphdr),\n\t\t\t\tsecattr);\n}", "label_name": "Class", "label": 2} {"code": "static int hci_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\t struct msghdr *msg, size_t len, int flags)\n{\n\tint noblock = flags & MSG_DONTWAIT;\n\tstruct sock *sk = sock->sk;\n\tstruct sk_buff *skb;\n\tint copied, err;\n\n\tBT_DBG(\"sock %p, sk %p\", sock, sk);\n\n\tif (flags & (MSG_OOB))\n\t\treturn -EOPNOTSUPP;\n\n\tif (sk->sk_state == BT_CLOSED)\n\t\treturn 0;\n\n\tskb = skb_recv_datagram(sk, flags, noblock, &err);\n\tif (!skb)\n\t\treturn err;\n\n\tmsg->msg_namelen = 0;\n\n\tcopied = skb->len;\n\tif (len < copied) {\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\t\tcopied = len;\n\t}\n\n\tskb_reset_transport_header(skb);\n\terr = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);\n\n\tswitch (hci_pi(sk)->channel) {\n\tcase HCI_CHANNEL_RAW:\n\t\thci_sock_cmsg(sk, msg, skb);\n\t\tbreak;\n\tcase HCI_CHANNEL_USER:\n\tcase HCI_CHANNEL_CONTROL:\n\tcase HCI_CHANNEL_MONITOR:\n\t\tsock_recv_timestamp(msg, sk, skb);\n\t\tbreak;\n\t}\n\n\tskb_free_datagram(sk, skb);\n\n\treturn err ? : copied;\n}", "label_name": "Class", "label": 2} {"code": "processBatchMultiRuleset(batch_t *pBatch)\n{\n\truleset_t *currRuleset;\n\tbatch_t snglRuleBatch;\n\tint i;\n\tint iStart;\t/* start index of partial batch */\n\tint iNew;\t/* index for new (temporary) batch */\n\tDEFiRet;\n\n\tCHKiRet(batchInit(&snglRuleBatch, pBatch->nElem));\n\tsnglRuleBatch.pbShutdownImmediate = pBatch->pbShutdownImmediate;\n\n\twhile(1) { /* loop broken inside */\n\t\t/* search for first unprocessed element */\n\t\tfor(iStart = 0 ; iStart < pBatch->nElem && pBatch->pElem[iStart].state == BATCH_STATE_DISC ; ++iStart)\n\t\t\t/* just search, no action */;\n\n\t\tif(iStart == pBatch->nElem)\n\t\t\tFINALIZE; /* everything processed */\n\n\t\t/* prepare temporary batch */\n\t\tcurrRuleset = batchElemGetRuleset(pBatch, iStart);\n\t\tiNew = 0;\n\t\tfor(i = iStart ; i < pBatch->nElem ; ++i) {\n\t\t\tif(batchElemGetRuleset(pBatch, i) == currRuleset) {\n\t\t\t\tbatchCopyElem(&(snglRuleBatch.pElem[iNew++]), &(pBatch->pElem[i]));\n\t\t\t\t/* We indicate the element also as done, so it will not be processed again */\n\t\t\t\tpBatch->pElem[i].state = BATCH_STATE_DISC;\n\t\t\t}\n\t\t}\n\t\tsnglRuleBatch.nElem = iNew; /* was left just right by the for loop */\n\t\tbatchSetSingleRuleset(&snglRuleBatch, 1);\n\t\t/* process temp batch */\n\t\tprocessBatch(&snglRuleBatch);\n\t}\n\tbatchFree(&snglRuleBatch);\n\nfinalize_it:\n\tRETiRet;\n}", "label_name": "Base", "label": 1} -{"code": "static int g2m_init_buffers(G2MContext *c)\n{\n int aligned_height;\n\n if (!c->framebuf || c->old_width < c->width || c->old_height < c->height) {\n c->framebuf_stride = FFALIGN(c->width * 3, 16);\n aligned_height = FFALIGN(c->height, 16);\n av_free(c->framebuf);\n c->framebuf = av_mallocz(c->framebuf_stride * aligned_height);\n if (!c->framebuf)\n return AVERROR(ENOMEM);\n }\n if (!c->synth_tile || !c->jpeg_tile ||\n c->old_tile_w < c->tile_width ||\n c->old_tile_h < c->tile_height) {\n c->tile_stride = FFALIGN(c->tile_width * 3, 16);\n aligned_height = FFALIGN(c->tile_height, 16);\n av_free(c->synth_tile);\n av_free(c->jpeg_tile);\n av_free(c->kempf_buf);\n av_free(c->kempf_flags);\n c->synth_tile = av_mallocz(c->tile_stride * aligned_height);\n c->jpeg_tile = av_mallocz(c->tile_stride * aligned_height);\n c->kempf_buf = av_mallocz((c->tile_width + 1) * aligned_height\n + FF_INPUT_BUFFER_PADDING_SIZE);\n c->kempf_flags = av_mallocz( c->tile_width * aligned_height);\n if (!c->synth_tile || !c->jpeg_tile ||\n !c->kempf_buf || !c->kempf_flags)\n return AVERROR(ENOMEM);\n }\n\n return 0;\n}", "label_name": "CWE-189", "label": "CWE-189"} {"code": "static LUA_FUNCTION(openssl_x509_check_email)\n{\n X509 * cert = CHECK_OBJECT(1, X509, \"openssl.x509\");\n if (lua_isstring(L, 2))\n {\n const char *email = lua_tostring(L, 2);\n lua_pushboolean(L, X509_check_email(cert, email, strlen(email), 0));\n }\n else\n {\n lua_pushboolean(L, 0);\n }\n return 1;\n}", "label_name": "Base", "label": 1} {"code": "static VALUE read_memory(VALUE klass, VALUE content)\n{\n xmlSchemaPtr schema;\n xmlSchemaParserCtxtPtr ctx = xmlSchemaNewMemParserCtxt(\n (const char *)StringValuePtr(content),\n (int)RSTRING_LEN(content)\n );\n VALUE rb_schema;\n VALUE errors = rb_ary_new();\n xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher);\n\n#ifdef HAVE_XMLSCHEMASETPARSERSTRUCTUREDERRORS\n xmlSchemaSetParserStructuredErrors(\n ctx,\n Nokogiri_error_array_pusher,\n (void *)errors\n );\n#endif\n\n schema = xmlSchemaParse(ctx);\n\n xmlSetStructuredErrorFunc(NULL, NULL);\n xmlSchemaFreeParserCtxt(ctx);\n\n if(NULL == schema) {\n xmlErrorPtr error = xmlGetLastError();\n if(error)\n Nokogiri_error_raise(NULL, error);\n else\n rb_raise(rb_eRuntimeError, \"Could not parse document\");\n\n return Qnil;\n }\n\n rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema);\n rb_iv_set(rb_schema, \"@errors\", errors);\n\n return rb_schema;\n}", "label_name": "Base", "label": 1} {"code": "PJ_DEF(pj_status_t) pjsip_endpt_send_response( pjsip_endpoint *endpt,\n\t\t\t\t\t pjsip_response_addr *res_addr,\n\t\t\t\t\t pjsip_tx_data *tdata,\n\t\t\t\t\t void *token,\n\t\t\t\t\t pjsip_send_callback cb)\n{\n /* Determine which transports and addresses to send the response,\n * based on Section 18.2.2 of RFC 3261.\n */\n pjsip_send_state *send_state;\n pj_status_t status;\n\n /* Create structure to keep the sending state. */\n send_state = PJ_POOL_ZALLOC_T(tdata->pool, pjsip_send_state);\n send_state->endpt = endpt;\n send_state->tdata = tdata;\n send_state->token = token;\n send_state->app_cb = cb;\n\n if (res_addr->transport != NULL) {\n\tsend_state->cur_transport = res_addr->transport;\n\tpjsip_transport_add_ref(send_state->cur_transport);\n\n\tstatus = pjsip_transport_send( send_state->cur_transport, tdata, \n\t\t\t\t &res_addr->addr,\n\t\t\t\t res_addr->addr_len,\n\t\t\t\t send_state,\n\t\t\t\t &send_response_transport_cb );\n\tif (status == PJ_SUCCESS) {\n\t pj_ssize_t sent = tdata->buf.cur - tdata->buf.start;\n\t send_response_transport_cb(send_state, tdata, sent);\n\t return PJ_SUCCESS;\n\t} else if (status == PJ_EPENDING) {\n\t /* Callback will be called later. */\n\t return PJ_SUCCESS;\n\t} else {\n\t pjsip_transport_dec_ref(send_state->cur_transport);\n\t return status;\n\t}\n } else {\n\t/* Copy the destination host name to TX data */\n\tpj_strdup(tdata->pool, &tdata->dest_info.name, \n\t\t &res_addr->dst_host.addr.host);\n\n\tpjsip_endpt_resolve(endpt, tdata->pool, &res_addr->dst_host, \n\t\t\t send_state, &send_response_resolver_cb);\n\treturn PJ_SUCCESS;\n }\n}", "label_name": "Base", "label": 1} {"code": "int ip6_find_1stfragopt(struct sk_buff *skb, u8 **nexthdr)\n{\n\tu16 offset = sizeof(struct ipv6hdr);\n\tunsigned int packet_len = skb_tail_pointer(skb) -\n\t\tskb_network_header(skb);\n\tint found_rhdr = 0;\n\t*nexthdr = &ipv6_hdr(skb)->nexthdr;\n\n\twhile (offset <= packet_len) {\n\t\tstruct ipv6_opt_hdr *exthdr;\n\n\t\tswitch (**nexthdr) {\n\n\t\tcase NEXTHDR_HOP:\n\t\t\tbreak;\n\t\tcase NEXTHDR_ROUTING:\n\t\t\tfound_rhdr = 1;\n\t\t\tbreak;\n\t\tcase NEXTHDR_DEST:\n#if IS_ENABLED(CONFIG_IPV6_MIP6)\n\t\t\tif (ipv6_find_tlv(skb, offset, IPV6_TLV_HAO) >= 0)\n\t\t\t\tbreak;\n#endif\n\t\t\tif (found_rhdr)\n\t\t\t\treturn offset;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn offset;\n\t\t}\n\n\t\tif (offset + sizeof(struct ipv6_opt_hdr) > packet_len)\n\t\t\treturn -EINVAL;\n\n\t\texthdr = (struct ipv6_opt_hdr *)(skb_network_header(skb) +\n\t\t\t\t\t\t offset);\n\t\toffset += ipv6_optlen(exthdr);\n\t\t*nexthdr = &exthdr->nexthdr;\n\t}\n\n\treturn -EINVAL;\n}", "label_name": "Base", "label": 1} -{"code": "static int crypto_givcipher_report(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\tstruct crypto_report_blkcipher rblkcipher;\n\n\tsnprintf(rblkcipher.type, CRYPTO_MAX_ALG_NAME, \"%s\", \"givcipher\");\n\tsnprintf(rblkcipher.geniv, CRYPTO_MAX_ALG_NAME, \"%s\",\n\t\t alg->cra_ablkcipher.geniv ?: \"\");\n\n\trblkcipher.blocksize = alg->cra_blocksize;\n\trblkcipher.min_keysize = alg->cra_ablkcipher.min_keysize;\n\trblkcipher.max_keysize = alg->cra_ablkcipher.max_keysize;\n\trblkcipher.ivsize = alg->cra_ablkcipher.ivsize;\n\n\tif (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER,\n\t\t sizeof(struct crypto_report_blkcipher), &rblkcipher))\n\t\tgoto nla_put_failure;\n\treturn 0;\n\nnla_put_failure:\n\treturn -EMSGSIZE;\n}", "label_name": "CWE-310", "label": "CWE-310"} {"code": "rs_filter_graph(RSFilter *filter)\n{\n\tg_return_if_fail(RS_IS_FILTER(filter));\n\tGString *str = g_string_new(\"digraph G {\\n\");\n\n\trs_filter_graph_helper(str, filter);\n\n\tg_string_append_printf(str, \"}\\n\");\n\tg_file_set_contents(\"/tmp/rs-filter-graph\", str->str, str->len, NULL);\n\n\tif (0 != system(\"dot -Tpng >/tmp/rs-filter-graph.png vmacache_seqnum++;\n\n\t/* deal with overflows */\n\tif (unlikely(mm->vmacache_seqnum == 0))\n\t\tvmacache_flush_all(mm);\n}", "label_name": "Variant", "label": 0} {"code": "void usb_sg_cancel(struct usb_sg_request *io)\n{\n\tunsigned long flags;\n\tint i, retval;\n\n\tspin_lock_irqsave(&io->lock, flags);\n\tif (io->status) {\n\t\tspin_unlock_irqrestore(&io->lock, flags);\n\t\treturn;\n\t}\n\t/* shut everything down */\n\tio->status = -ECONNRESET;\n\tspin_unlock_irqrestore(&io->lock, flags);\n\n\tfor (i = io->entries - 1; i >= 0; --i) {\n\t\tusb_block_urb(io->urbs[i]);\n\n\t\tretval = usb_unlink_urb(io->urbs[i]);\n\t\tif (retval != -EINPROGRESS\n\t\t && retval != -ENODEV\n\t\t && retval != -EBUSY\n\t\t && retval != -EIDRM)\n\t\t\tdev_warn(&io->dev->dev, \"%s, unlink --> %d\\n\",\n\t\t\t\t __func__, retval);\n\t}\n}", "label_name": "Variant", "label": 0} -{"code": "void xacct_add_tsk(struct taskstats *stats, struct task_struct *p)\n{\n\t/* convert pages-jiffies to Mbyte-usec */\n\tstats->coremem = jiffies_to_usecs(p->acct_rss_mem1) * PAGE_SIZE / MB;\n\tstats->virtmem = jiffies_to_usecs(p->acct_vm_mem1) * PAGE_SIZE / MB;\n\tif (p->mm) {\n\t\t/* adjust to KB unit */\n\t\tstats->hiwater_rss = p->mm->hiwater_rss * PAGE_SIZE / KB;\n\t\tstats->hiwater_vm = p->mm->hiwater_vm * PAGE_SIZE / KB;\n\t}\n\tstats->read_char\t= p->rchar;\n\tstats->write_char\t= p->wchar;\n\tstats->read_syscalls\t= p->syscr;\n\tstats->write_syscalls\t= p->syscw;\n}", "label_name": "CWE-399", "label": "CWE-399"} {"code": "double GetGPMFSampleRateAndTimes(size_t handle, GPMF_stream *gs, double rate, uint32_t index, double *in, double *out)\n{\n\tmp4object *mp4 = (mp4object *)handle;\n\tif (mp4 == NULL) return 0.0;\n\n\tuint32_t key, insamples;\n\tuint32_t repeat, outsamples;\n\tGPMF_stream find_stream;\n\n\tif (gs == NULL || mp4->metaoffsets == 0 || mp4->indexcount == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in == NULL || out == NULL) return 0.0;\n\n\tkey = GPMF_Key(gs);\n\trepeat = GPMF_Repeat(gs);\n\tif (rate == 0.0)\n\t\trate = GetGPMFSampleRate(handle, key, GPMF_SAMPLE_RATE_FAST);\n\n\tif (rate == 0.0)\n\t{\n\t\t*in = *out = 0.0;\n\t\treturn 0.0;\n\t}\n\n\tGPMF_CopyState(gs, &find_stream);\n\tif (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL))\n\t{\n\t\toutsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream));\n\t\tinsamples = outsamples - repeat;\n\n\t\t*in = ((double)insamples / (double)rate);\n\t\t*out = ((double)outsamples / (double)rate);\n\t}\n\telse\n\t{\n\t\t// might too costly in some applications read all the samples to determine the clock jitter, here I return the estimate from the MP4 track.\n\t\t*in = ((double)index * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);\n\t\t*out = ((double)(index + 1) * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);\n\t}\n\treturn rate;\n}", "label_name": "Base", "label": 1} {"code": "_PyMemoTable_ResizeTable(PyMemoTable *self, Py_ssize_t min_size)\n{\n PyMemoEntry *oldtable = NULL;\n PyMemoEntry *oldentry, *newentry;\n Py_ssize_t new_size = MT_MINSIZE;\n Py_ssize_t to_process;\n\n assert(min_size > 0);\n\n /* Find the smallest valid table size >= min_size. */\n while (new_size < min_size && new_size > 0)\n new_size <<= 1;\n if (new_size <= 0) {\n PyErr_NoMemory();\n return -1;\n }\n /* new_size needs to be a power of two. */\n assert((new_size & (new_size - 1)) == 0);\n\n /* Allocate new table. */\n oldtable = self->mt_table;\n self->mt_table = PyMem_NEW(PyMemoEntry, new_size);\n if (self->mt_table == NULL) {\n self->mt_table = oldtable;\n PyErr_NoMemory();\n return -1;\n }\n self->mt_allocated = new_size;\n self->mt_mask = new_size - 1;\n memset(self->mt_table, 0, sizeof(PyMemoEntry) * new_size);\n\n /* Copy entries from the old table. */\n to_process = self->mt_used;\n for (oldentry = oldtable; to_process > 0; oldentry++) {\n if (oldentry->me_key != NULL) {\n to_process--;\n /* newentry is a pointer to a chunk of the new\n mt_table, so we're setting the key:value pair\n in-place. */\n newentry = _PyMemoTable_Lookup(self, oldentry->me_key);\n newentry->me_key = oldentry->me_key;\n newentry->me_value = oldentry->me_value;\n }\n }\n\n /* Deallocate the old table. */\n PyMem_FREE(oldtable);\n return 0;\n}", "label_name": "Base", "label": 1} {"code": "int read_file(struct sc_card *card, char *str_path, unsigned char **data, size_t *data_len)\n{\n\tstruct sc_path path;\n\tstruct sc_file *file;\n\tunsigned char *p;\n\tint ok = 0;\n\tint r;\n\tsize_t len;\n\n\tsc_format_path(str_path, &path);\n\tif (SC_SUCCESS != sc_select_file(card, &path, &file)) {\n\t\tgoto err;\n\t}\n\n\tlen = file ? file->size : 4096;\n\tp = realloc(*data, len);\n\tif (!p) {\n\t\tgoto err;\n\t}\n\t*data = p;\n\t*data_len = len;\n\n\tr = sc_read_binary(card, 0, p, len, 0);\n\tif (r < 0)\n\t\tgoto err;\n\n\t*data_len = r;\n\tok = 1;\n\nerr:\n\tsc_file_free(file);\n\n\treturn ok;\n}", "label_name": "Variant", "label": 0} @@ -1220,7 +1194,6 @@ {"code": "pci_emul_alloc_resource(uint64_t *baseptr, uint64_t limit, uint64_t size,\n\t\t\tuint64_t *addr)\n{\n\tuint64_t base;\n\n\tassert((size & (size - 1)) == 0);\t/* must be a power of 2 */\n\n\tbase = roundup2(*baseptr, size);\n\n\tif (base + size <= limit) {\n\t\t*addr = base;\n\t\t*baseptr = base + size;\n\t\treturn 0;\n\t} else\n\t\treturn -1;\n}", "label_name": "Base", "label": 1} {"code": "char *curl_easy_escape(CURL *handle, const char *string, int inlength)\n{\n size_t alloc = (inlength?(size_t)inlength:strlen(string))+1;\n char *ns;\n char *testing_ptr = NULL;\n unsigned char in; /* we need to treat the characters unsigned */\n size_t newlen = alloc;\n int strindex=0;\n size_t length;\n CURLcode res;\n\n ns = malloc(alloc);\n if(!ns)\n return NULL;\n\n length = alloc-1;\n while(length--) {\n in = *string;\n\n if(Curl_isunreserved(in))\n /* just copy this */\n ns[strindex++]=in;\n else {\n /* encode it */\n newlen += 2; /* the size grows with two, since this'll become a %XX */\n if(newlen > alloc) {\n alloc *= 2;\n testing_ptr = realloc(ns, alloc);\n if(!testing_ptr) {\n free( ns );\n return NULL;\n }\n else {\n ns = testing_ptr;\n }\n }\n\n res = Curl_convert_to_network(handle, &in, 1);\n if(res) {\n /* Curl_convert_to_network calls failf if unsuccessful */\n free(ns);\n return NULL;\n }\n\n snprintf(&ns[strindex], 4, \"%%%02X\", in);\n\n strindex+=3;\n }\n string++;\n }\n ns[strindex]=0; /* terminate it */\n return ns;\n}", "label_name": "Base", "label": 1} {"code": "static int rfcomm_sock_recvmsg(struct kiocb *iocb, struct socket *sock,\n\t\t\t struct msghdr *msg, size_t size, int flags)\n{\n\tstruct sock *sk = sock->sk;\n\tstruct rfcomm_dlc *d = rfcomm_pi(sk)->dlc;\n\tint len;\n\n\tif (test_and_clear_bit(RFCOMM_DEFER_SETUP, &d->flags)) {\n\t\trfcomm_dlc_accept(d);\n\t\tmsg->msg_namelen = 0;\n\t\treturn 0;\n\t}\n\n\tlen = bt_sock_stream_recvmsg(iocb, sock, msg, size, flags);\n\n\tlock_sock(sk);\n\tif (!(flags & MSG_PEEK) && len > 0)\n\t\tatomic_sub(len, &sk->sk_rmem_alloc);\n\n\tif (atomic_read(&sk->sk_rmem_alloc) <= (sk->sk_rcvbuf >> 2))\n\t\trfcomm_dlc_unthrottle(rfcomm_pi(sk)->dlc);\n\trelease_sock(sk);\n\n\treturn len;\n}", "label_name": "Class", "label": 2} -{"code": "void __fput_sync(struct file *file)\n{\n\tif (atomic_long_dec_and_test(&file->f_count)) {\n\t\tstruct task_struct *task = current;\n\t\tfile_sb_list_del(file);\n\t\tBUG_ON(!(task->flags & PF_KTHREAD));\n\t\t__fput(file);\n\t}\n}", "label_name": "CWE-17", "label": "CWE-17"} {"code": "BITMAP_UPDATE* update_read_bitmap_update(rdpUpdate* update, wStream* s)\n{\n\tUINT32 i;\n\tBITMAP_UPDATE* bitmapUpdate = calloc(1, sizeof(BITMAP_UPDATE));\n\n\tif (!bitmapUpdate)\n\t\tgoto fail;\n\n\tif (Stream_GetRemainingLength(s) < 2)\n\t\tgoto fail;\n\n\tStream_Read_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */\n\tWLog_Print(update->log, WLOG_TRACE, \"BitmapUpdate: %\"PRIu32\"\", bitmapUpdate->number);\n\n\tif (bitmapUpdate->number > bitmapUpdate->count)\n\t{\n\t\tUINT16 count;\n\t\tBITMAP_DATA* newdata;\n\t\tcount = bitmapUpdate->number * 2;\n\t\tnewdata = (BITMAP_DATA*) realloc(bitmapUpdate->rectangles,\n\t\t sizeof(BITMAP_DATA) * count);\n\n\t\tif (!newdata)\n\t\t\tgoto fail;\n\n\t\tbitmapUpdate->rectangles = newdata;\n\t\tZeroMemory(&bitmapUpdate->rectangles[bitmapUpdate->count],\n\t\t sizeof(BITMAP_DATA) * (count - bitmapUpdate->count));\n\t\tbitmapUpdate->count = count;\n\t}\n\n\t/* rectangles */\n\tfor (i = 0; i < bitmapUpdate->number; i++)\n\t{\n\t\tif (!update_read_bitmap_data(update, s, &bitmapUpdate->rectangles[i]))\n\t\t\tgoto fail;\n\t}\n\n\treturn bitmapUpdate;\nfail:\n\tfree_bitmap_update(update->context, bitmapUpdate);\n\treturn NULL;\n}", "label_name": "Base", "label": 1} {"code": "mem_log_init(const char* prog_name, const char *banner)\n{\n\tsize_t log_name_len;\n\tchar *log_name;\n\n\tif (__test_bit(LOG_CONSOLE_BIT, &debug)) {\n\t\tlog_op = stderr;\n\t\treturn;\n\t}\n\n\tif (log_op)\n\t\tfclose(log_op);\n\n\tlog_name_len = 5 + strlen(prog_name) + 5 + 7 + 4 + 1;\t/* \"/tmp/\" + prog_name + \"_mem.\" + PID + \".log\" + '\\0\" */\n\tlog_name = malloc(log_name_len);\n\tif (!log_name) {\n\t\tlog_message(LOG_INFO, \"Unable to malloc log file name\");\n\t\tlog_op = stderr;\n\t\treturn;\n\t}\n\n\tsnprintf(log_name, log_name_len, \"/tmp/%s_mem.%d.log\", prog_name, getpid());\n\tlog_op = fopen(log_name, \"a\");\n\tif (log_op == NULL) {\n\t\tlog_message(LOG_INFO, \"Unable to open %s for appending\", log_name);\n\t\tlog_op = stderr;\n\t}\n\telse {\n\t\tint fd = fileno(log_op);\n\n\t\t/* We don't want any children to inherit the log file */\n\t\tfcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);\n\n\t\t/* Make the log output line buffered. This was to ensure that\n\t\t * children didn't inherit the buffer, but the CLOEXEC above\n\t\t * should resolve that. */\n\t\tsetlinebuf(log_op);\n\n\t\tfprintf(log_op, \"\\n\");\n\t}\n\n\tfree(log_name);\n\n\tterminate_banner = banner;\n}", "label_name": "Base", "label": 1} {"code": "exif_data_load_data_thumbnail (ExifData *data, const unsigned char *d,\n\t\t\t unsigned int ds, ExifLong o, ExifLong s)\n{\n\t/* Sanity checks */\n\tif ((o + s < o) || (o + s < s) || (o + s > ds) || (o > ds)) {\n\t\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\",\n\t\t\t \"Bogus thumbnail offset (%u) or size (%u).\",\n\t\t\t o, s);\n\t\treturn;\n\t}\n\n\tif (data->data) \n\t\texif_mem_free (data->priv->mem, data->data);\n\tif (!(data->data = exif_data_alloc (data, s))) {\n\t\tEXIF_LOG_NO_MEMORY (data->priv->log, \"ExifData\", s);\n\t\tdata->size = 0;\n\t\treturn;\n\t}\n\tdata->size = s;\n\tmemcpy (data->data, d + o, s);\n}", "label_name": "Base", "label": 1} @@ -1234,13 +1207,10 @@ {"code": "cJSON *cJSON_CreateString( const char *string )\n{\n\tcJSON *item = cJSON_New_Item();\n\tif ( item ) {\n\t\titem->type = cJSON_String;\n\t\titem->valuestring = cJSON_strdup( string );\n\t}\n\treturn item;\n}", "label_name": "Base", "label": 1} {"code": "l2tp_framing_type_print(netdissect_options *ndo, const u_char *dat)\n{\n\tconst uint32_t *ptr = (const uint32_t *)dat;\n\n\tif (EXTRACT_32BITS(ptr) & L2TP_FRAMING_TYPE_ASYNC_MASK) {\n\t\tND_PRINT((ndo, \"A\"));\n\t}\n\tif (EXTRACT_32BITS(ptr) & L2TP_FRAMING_TYPE_SYNC_MASK) {\n\t\tND_PRINT((ndo, \"S\"));\n\t}\n}", "label_name": "Base", "label": 1} {"code": "int jpg_validate(jas_stream_t *in)\n{\n\tuchar buf[JPG_MAGICLEN];\n\tint i;\n\tint n;\n\n\tassert(JAS_STREAM_MAXPUTBACK >= JPG_MAGICLEN);\n\n\t/* Read the validation data (i.e., the data used for detecting\n\t the format). */\n\tif ((n = jas_stream_read(in, buf, JPG_MAGICLEN)) < 0) {\n\t\treturn -1;\n\t}\n\n\t/* Put the validation data back onto the stream, so that the\n\t stream position will not be changed. */\n\tfor (i = n - 1; i >= 0; --i) {\n\t\tif (jas_stream_ungetc(in, buf[i]) == EOF) {\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\t/* Did we read enough data? */\n\tif (n < JPG_MAGICLEN) {\n\t\treturn -1;\n\t}\n\n\t/* Does this look like JPEG? */\n\tif (buf[0] != (JPG_MAGIC >> 8) || buf[1] != (JPG_MAGIC & 0xff)) {\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}", "label_name": "Class", "label": 2} -{"code": "static int iov_fault_in_pages_write(struct iovec *iov, unsigned long len)\n{\n\twhile (!iov->iov_len)\n\t\tiov++;\n\n\twhile (len > 0) {\n\t\tunsigned long this_len;\n\n\t\tthis_len = min_t(unsigned long, len, iov->iov_len);\n\t\tif (fault_in_pages_writeable(iov->iov_base, this_len))\n\t\t\tbreak;\n\n\t\tlen -= this_len;\n\t\tiov++;\n\t}\n\n\treturn len;\n}", "label_name": "CWE-17", "label": "CWE-17"} {"code": "cJSON *cJSON_GetObjectItem( cJSON *object, const char *string )\n{\n\tcJSON *c = object->child;\n\twhile ( c && cJSON_strcasecmp( c->string, string ) )\n\t\tc = c->next;\n\treturn c;\n}", "label_name": "Base", "label": 1} {"code": "inline void update_rq_clock(struct rq *rq)\n{\n\tif (!rq->skip_clock_update) {\n\t\tint cpu = cpu_of(rq);\n\t\tu64 irq_time;\n\n\t\trq->clock = sched_clock_cpu(cpu);\n\t\tirq_time = irq_time_cpu(cpu);\n\t\tif (rq->clock - irq_time > rq->clock_task)\n\t\t\trq->clock_task = rq->clock - irq_time;\n\n\t\tsched_irq_time_avg_update(rq, irq_time);\n\t}\n}", "label_name": "Base", "label": 1} -{"code": "int test_sqr(BIO *bp, BN_CTX *ctx)\n\t{\n\tBIGNUM a,c,d,e;\n\tint i;\n\n\tBN_init(&a);\n\tBN_init(&c);\n\tBN_init(&d);\n\tBN_init(&e);\n\n\tfor (i=0; iarg);\n if (!value) goto failed;\n if (_PyObject_SetAttrId(result, &PyId_arg, value) == -1)\n goto failed;\n Py_DECREF(value);\n value = ast2obj_expr(o->annotation);\n if (!value) goto failed;\n if (_PyObject_SetAttrId(result, &PyId_annotation, value) == -1)\n goto failed;\n Py_DECREF(value);\n value = ast2obj_string(o->type_comment);\n if (!value) goto failed;\n if (_PyObject_SetAttrId(result, &PyId_type_comment, value) == -1)\n goto failed;\n Py_DECREF(value);\n value = ast2obj_int(o->lineno);\n if (!value) goto failed;\n if (_PyObject_SetAttrId(result, &PyId_lineno, value) < 0)\n goto failed;\n Py_DECREF(value);\n value = ast2obj_int(o->col_offset);\n if (!value) goto failed;\n if (_PyObject_SetAttrId(result, &PyId_col_offset, value) < 0)\n goto failed;\n Py_DECREF(value);\n return result;\nfailed:\n Py_XDECREF(value);\n Py_XDECREF(result);\n return NULL;\n}", "label_name": "Base", "label": 1} {"code": "static const struct usb_cdc_union_desc *\nims_pcu_get_cdc_union_desc(struct usb_interface *intf)\n{\n\tconst void *buf = intf->altsetting->extra;\n\tsize_t buflen = intf->altsetting->extralen;\n\tstruct usb_cdc_union_desc *union_desc;\n\n\tif (!buf) {\n\t\tdev_err(&intf->dev, \"Missing descriptor data\\n\");\n\t\treturn NULL;\n\t}\n\n\tif (!buflen) {\n\t\tdev_err(&intf->dev, \"Zero length descriptor\\n\");\n\t\treturn NULL;\n\t}\n\n\twhile (buflen > 0) {\n\t\tunion_desc = (struct usb_cdc_union_desc *)buf;\n\n\t\tif (union_desc->bDescriptorType == USB_DT_CS_INTERFACE &&\n\t\t union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) {\n\t\t\tdev_dbg(&intf->dev, \"Found union header\\n\");\n\t\t\treturn union_desc;\n\t\t}\n\n\t\tbuflen -= union_desc->bLength;\n\t\tbuf += union_desc->bLength;\n\t}\n\n\tdev_err(&intf->dev, \"Missing CDC union descriptor\\n\");\n\treturn NULL;", "label_name": "Base", "label": 1} -{"code": "static int sctp_v6_xmit(struct sk_buff *skb, struct sctp_transport *transport)\n{\n\tstruct sock *sk = skb->sk;\n\tstruct ipv6_pinfo *np = inet6_sk(sk);\n\tstruct flowi6 fl6;\n\n\tmemset(&fl6, 0, sizeof(fl6));\n\n\tfl6.flowi6_proto = sk->sk_protocol;\n\n\t/* Fill in the dest address from the route entry passed with the skb\n\t * and the source address from the transport.\n\t */\n\tfl6.daddr = transport->ipaddr.v6.sin6_addr;\n\tfl6.saddr = transport->saddr.v6.sin6_addr;\n\n\tfl6.flowlabel = np->flow_label;\n\tIP6_ECN_flow_xmit(sk, fl6.flowlabel);\n\tif (ipv6_addr_type(&fl6.saddr) & IPV6_ADDR_LINKLOCAL)\n\t\tfl6.flowi6_oif = transport->saddr.v6.sin6_scope_id;\n\telse\n\t\tfl6.flowi6_oif = sk->sk_bound_dev_if;\n\n\tif (np->opt && np->opt->srcrt) {\n\t\tstruct rt0_hdr *rt0 = (struct rt0_hdr *) np->opt->srcrt;\n\t\tfl6.daddr = *rt0->addr;\n\t}\n\n\tpr_debug(\"%s: skb:%p, len:%d, src:%pI6 dst:%pI6\\n\", __func__, skb,\n\t\t skb->len, &fl6.saddr, &fl6.daddr);\n\n\tSCTP_INC_STATS(sock_net(sk), SCTP_MIB_OUTSCTPPACKS);\n\n\tif (!(transport->param_flags & SPP_PMTUD_ENABLE))\n\t\tskb->local_df = 1;\n\n\treturn ip6_xmit(sk, skb, &fl6, np->opt, np->tclass);\n}", "label_name": "CWE-310", "label": "CWE-310"} {"code": "void set_module_sig_enforced(void)\n{\n\tsig_enforce = true;\n}", "label_name": "Base", "label": 1} {"code": "static void handle_run(HttpRequest req, HttpResponse res) {\n const char *action = get_parameter(req, \"action\");\n if (action) {\n if (is_readonly(req)) {\n send_error(req, res, SC_FORBIDDEN, \"You do not have sufficient privileges to access this page\");\n return;\n }\n if (IS(action, \"validate\")) {\n LogInfo(\"The Monit http server woke up on user request\\n\");\n do_wakeupcall();\n } else if (IS(action, \"stop\")) {\n LogInfo(\"The Monit http server stopped on user request\\n\");\n send_error(req, res, SC_SERVICE_UNAVAILABLE, \"The Monit http server is stopped\");\n Engine_stop();\n return;\n }\n }\n LOCK(Run.mutex)\n do_runtime(req, res);\n END_LOCK;\n}", "label_name": "Compound", "label": 4} {"code": "static int nntp_hcache_namer(const char *path, char *dest, size_t destlen)\n{\n return snprintf(dest, destlen, \"%s.hcache\", path);\n}", "label_name": "Class", "label": 2} @@ -1256,7 +1226,6 @@ {"code": "static int spl_array_has_dimension_ex(int check_inherited, zval *object, zval *offset, int check_empty TSRMLS_DC) /* {{{ */\n{\n\tspl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);\n\tlong index;\n\tzval *rv, *value = NULL, **tmp;\n\n\tif (check_inherited && intern->fptr_offset_has) {\n\t\tzval *offset_tmp = offset;\n\t\tSEPARATE_ARG_IF_REF(offset_tmp);\n\t\tzend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_has, \"offsetExists\", &rv, offset_tmp);\n\t\tzval_ptr_dtor(&offset_tmp);\n\n\t\tif (rv && zend_is_true(rv)) {\n\t\t\tzval_ptr_dtor(&rv);\n\t\t\tif (check_empty != 1) {\n\t\t\t\treturn 1;\n\t\t\t} else if (intern->fptr_offset_get) {\n\t\t\t\tvalue = spl_array_read_dimension_ex(1, object, offset, BP_VAR_R TSRMLS_CC);\n\t\t\t}\n\t\t} else {\n\t\t\tif (rv) {\n\t\t\t\tzval_ptr_dtor(&rv);\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tif (!value) {\n\t\tHashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);\n\n\t\tswitch(Z_TYPE_P(offset)) {\n\t\t\tcase IS_STRING: \n\t\t\t\tif (zend_symtable_find(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **) &tmp) != FAILURE) {\n\t\t\t\t\tif (check_empty == 2) {\n\t\t\t\t\t\treturn 1;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase IS_DOUBLE:\n\t\t\tcase IS_RESOURCE:\n\t\t\tcase IS_BOOL: \n\t\t\tcase IS_LONG:\n\t\t\t\tif (offset->type == IS_DOUBLE) {\n\t\t\t\t\tindex = (long)Z_DVAL_P(offset);\n\t\t\t\t} else {\n\t\t\t\t\tindex = Z_LVAL_P(offset);\n\t\t\t\t}\n\t\t\t\tif (zend_hash_index_find(ht, index, (void **)&tmp) != FAILURE) {\n\t\t\t\t\tif (check_empty == 2) {\n\t\t\t\t\t\treturn 1;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tzend_error(E_WARNING, \"Illegal offset type\");\n\t\t\t\treturn 0;\n\t\t}\n\n\t\tif (check_empty && check_inherited && intern->fptr_offset_get) {\n\t\t\tvalue = spl_array_read_dimension_ex(1, object, offset, BP_VAR_R TSRMLS_CC);\n\t\t} else {\n\t\t\tvalue = *tmp;\n\t\t}\n\t}\n\n\treturn check_empty ? zend_is_true(value) : Z_TYPE_P(value) != IS_NULL;\n} /* }}} */", "label_name": "Class", "label": 2} {"code": "static int pgx_gethdr(jas_stream_t *in, pgx_hdr_t *hdr)\n{\n\tint c;\n\tuchar buf[2];\n\n\tif ((c = jas_stream_getc(in)) == EOF) {\n\t\tgoto error;\n\t}\n\tbuf[0] = c;\n\tif ((c = jas_stream_getc(in)) == EOF) {\n\t\tgoto error;\n\t}\n\tbuf[1] = c;\n\thdr->magic = buf[0] << 8 | buf[1];\n\tif (hdr->magic != PGX_MAGIC) {\n\t\tjas_eprintf(\"invalid PGX signature\\n\");\n\t\tgoto error;\n\t}\n\tif ((c = pgx_getc(in)) == EOF || !isspace(c)) {\n\t\tgoto error;\n\t}\n\tif (pgx_getbyteorder(in, &hdr->bigendian)) {\n\t\tjas_eprintf(\"cannot get byte order\\n\");\n\t\tgoto error;\n\t}\n\tif (pgx_getsgnd(in, &hdr->sgnd)) {\n\t\tjas_eprintf(\"cannot get signedness\\n\");\n\t\tgoto error;\n\t}\n\tif (pgx_getuint32(in, &hdr->prec)) {\n\t\tjas_eprintf(\"cannot get precision\\n\");\n\t\tgoto error;\n\t}\n\tif (pgx_getuint32(in, &hdr->width)) {\n\t\tjas_eprintf(\"cannot get width\\n\");\n\t\tgoto error;\n\t}\n\tif (pgx_getuint32(in, &hdr->height)) {\n\t\tjas_eprintf(\"cannot get height\\n\");\n\t\tgoto error;\n\t}\n\treturn 0;\n\nerror:\n\treturn -1;\n}", "label_name": "Base", "label": 1} {"code": "main_get_appheader (xd3_stream *stream, main_file *ifile,\n\t\t main_file *output, main_file *sfile)\n{\n uint8_t *apphead;\n usize_t appheadsz;\n int ret;\n\n /* The user may disable the application header. Once the appheader\n * is set, this disables setting it again. */\n if (! option_use_appheader) { return; }\n\n ret = xd3_get_appheader (stream, & apphead, & appheadsz);\n\n /* Ignore failure, it only means we haven't received a header yet. */\n if (ret != 0) { return; }\n\n if (appheadsz > 0)\n {\n char *start = (char*)apphead;\n char *slash;\n int place = 0;\n char *parsed[4];\n\n memset (parsed, 0, sizeof (parsed));\n\n while ((slash = strchr (start, '/')) != NULL)\n\t{\n\t *slash = 0;\n\t parsed[place++] = start;\n\t start = slash + 1;\n\t}\n\n parsed[place++] = start;\n\n /* First take the output parameters. */\n if (place == 2 || place == 4)\n\t{\n\t main_get_appheader_params (output, parsed, 1, \"output\", ifile);\n\t}\n\n /* Then take the source parameters. */\n if (place == 4)\n\t{\n\t main_get_appheader_params (sfile, parsed+2, 0, \"source\", ifile);\n\t}\n }\n\n option_use_appheader = 0;\n return;\n}", "label_name": "Class", "label": 2} -{"code": "static int crypto_aead_report(struct sk_buff *skb, struct crypto_alg *alg)\n{\n\tstruct crypto_report_aead raead;\n\tstruct aead_alg *aead = &alg->cra_aead;\n\n\tsnprintf(raead.type, CRYPTO_MAX_ALG_NAME, \"%s\", \"aead\");\n\tsnprintf(raead.geniv, CRYPTO_MAX_ALG_NAME, \"%s\",\n\t\t aead->geniv ?: \"\");\n\n\traead.blocksize = alg->cra_blocksize;\n\traead.maxauthsize = aead->maxauthsize;\n\traead.ivsize = aead->ivsize;\n\n\tif (nla_put(skb, CRYPTOCFGA_REPORT_AEAD,\n\t\t sizeof(struct crypto_report_aead), &raead))\n\t\tgoto nla_put_failure;\n\treturn 0;\n\nnla_put_failure:\n\treturn -EMSGSIZE;\n}", "label_name": "CWE-310", "label": "CWE-310"} {"code": "int rtp_packetize_xiph_config( sout_stream_id_sys_t *id, const char *fmtp,\n int64_t i_pts )\n{\n if (fmtp == NULL)\n return VLC_EGENERIC;\n\n /* extract base64 configuration from fmtp */\n char *start = strstr(fmtp, \"configuration=\");\n assert(start != NULL);\n start += sizeof(\"configuration=\") - 1;\n char *end = strchr(start, ';');\n assert(end != NULL);\n size_t len = end - start;\n char b64[len + 1];\n memcpy(b64, start, len);\n b64[len] = '\\0';\n\n int i_max = rtp_mtu (id) - 6; /* payload max in one packet */\n\n uint8_t *p_orig, *p_data;\n int i_data;\n\n i_data = vlc_b64_decode_binary(&p_orig, b64);\n if (i_data <= 9)\n {\n free(p_orig);\n return VLC_EGENERIC;\n }\n p_data = p_orig + 9;\n i_data -= 9;\n\n int i_count = ( i_data + i_max - 1 ) / i_max;\n\n for( int i = 0; i < i_count; i++ )\n {\n int i_payload = __MIN( i_max, i_data );\n block_t *out = block_Alloc( 18 + i_payload );\n\n unsigned fragtype, numpkts;\n if (i_count == 1)\n {\n fragtype = 0;\n numpkts = 1;\n }\n else\n {\n numpkts = 0;\n if (i == 0)\n fragtype = 1;\n else if (i == i_count - 1)\n fragtype = 3;\n else\n fragtype = 2;\n }\n /* Ident:24, Fragment type:2, Vorbis/Theora Data Type:2, # of pkts:4 */\n uint32_t header = ((XIPH_IDENT & 0xffffff) << 8) |\n (fragtype << 6) | (1 << 4) | numpkts;\n\n /* rtp common header */\n rtp_packetize_common( id, out, 0, i_pts );\n\n SetDWBE( out->p_buffer + 12, header);\n SetWBE( out->p_buffer + 16, i_payload);\n memcpy( &out->p_buffer[18], p_data, i_payload );\n\n out->i_dts = i_pts;\n\n rtp_packetize_send( id, out );\n\n p_data += i_payload;\n i_data -= i_payload;\n }\n\n free(p_orig);\n\n return VLC_SUCCESS;\n}", "label_name": "Class", "label": 2} {"code": "static void mark_object(struct object *obj, struct strbuf *path,\n\t\t\tconst char *name, void *data)\n{\n\tupdate_progress(data);\n}", "label_name": "Class", "label": 2} {"code": "static int newque(struct ipc_namespace *ns, struct ipc_params *params)\n{\n\tstruct msg_queue *msq;\n\tint id, retval;\n\tkey_t key = params->key;\n\tint msgflg = params->flg;\n\n\tmsq = ipc_rcu_alloc(sizeof(*msq));\n\tif (!msq)\n\t\treturn -ENOMEM;\n\n\tmsq->q_perm.mode = msgflg & S_IRWXUGO;\n\tmsq->q_perm.key = key;\n\n\tmsq->q_perm.security = NULL;\n\tretval = security_msg_queue_alloc(msq);\n\tif (retval) {\n\t\tipc_rcu_putref(msq, ipc_rcu_free);\n\t\treturn retval;\n\t}\n\n\t/* ipc_addid() locks msq upon success. */\n\tid = ipc_addid(&msg_ids(ns), &msq->q_perm, ns->msg_ctlmni);\n\tif (id < 0) {\n\t\tipc_rcu_putref(msq, msg_rcu_free);\n\t\treturn id;\n\t}\n\n\tmsq->q_stime = msq->q_rtime = 0;\n\tmsq->q_ctime = get_seconds();\n\tmsq->q_cbytes = msq->q_qnum = 0;\n\tmsq->q_qbytes = ns->msg_ctlmnb;\n\tmsq->q_lspid = msq->q_lrpid = 0;\n\tINIT_LIST_HEAD(&msq->q_messages);\n\tINIT_LIST_HEAD(&msq->q_receivers);\n\tINIT_LIST_HEAD(&msq->q_senders);\n\n\tipc_unlock_object(&msq->q_perm);\n\trcu_read_unlock();\n\n\treturn msq->q_perm.id;\n}", "label_name": "Class", "label": 2} @@ -1273,7 +1242,6 @@ {"code": " def auth_type(self):\n return self.appbuilder.get_app.config[\"AUTH_TYPE\"]", "label_name": "Class", "label": 2} {"code": "def _is_javascript_scheme(s):\n if _is_image_dataurl(s):\n return None\n return _is_possibly_malicious_scheme(s)", "label_name": "Base", "label": 1} {"code": " def test_get_response_requests_exception(self, mock_get):\n mock_response = mock.Mock()\n mock_response.status_code = 500\n mock_response.text = \"Server Error\"\n exception_message = \"Some requests exception\"\n requests_exception = requests.RequestException(exception_message)\n mock_response.raise_for_status.side_effect = requests_exception\n mock_get.return_value = mock_response\n\n url = \"https://example.com/\"\n query_runner = BaseHTTPQueryRunner({})\n response, error = query_runner.get_response(url)\n mock_get.assert_called_once_with(\"get\", url, auth=None)\n self.assertIsNotNone(error)\n self.assertEqual(exception_message, error)", "label_name": "Base", "label": 1} -{"code": " def delete(self):\n shutil.rmtree(self._path)\n os.remove(self._props_path)", "label_name": "CWE-21", "label": "CWE-21"} {"code": " def test_big_arrays(self):\n L = (1 << 31) + 100000\n tmp = mktemp(suffix='.npz')\n a = np.empty(L, dtype=np.uint8)\n np.savez(tmp, a=a)\n del a\n npfile = np.load(tmp)\n a = npfile['a']\n npfile.close()\n os.remove(tmp)", "label_name": "Base", "label": 1} {"code": " def receivePing():\n vrequest = request.form['id']\n db.sentences_victim('report_online', [vrequest])\n return json.dumps({'status' : 'OK', 'vId' : vrequest});", "label_name": "Base", "label": 1} {"code": "def accounts_home_from_multiuse_invite(request: HttpRequest, confirmation_key: str) -> HttpResponse:\n multiuse_object = None\n try:\n multiuse_object = get_object_from_key(confirmation_key, [Confirmation.MULTIUSE_INVITE])\n # Required for OAuth 2\n except ConfirmationKeyException as exception:\n realm = get_realm_from_request(request)\n if realm is None or realm.invite_required:\n return render_confirmation_key_error(request, exception)\n return accounts_home(\n request, multiuse_object_key=confirmation_key, multiuse_object=multiuse_object\n )", "label_name": "Class", "label": 2} @@ -1322,7 +1290,6 @@ {"code": "def _is_javascript_scheme(s):\n if _is_image_dataurl(s):\n return None\n return _is_possibly_malicious_scheme(s)", "label_name": "Class", "label": 2} {"code": " def test_reset_student_attempts_missingmodule(self):\n \"\"\" Test reset for non-existant problem. \"\"\"\n url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})\n response = self.client.get(url, {\n 'problem_to_reset': 'robot-not-a-real-module',\n 'unique_student_identifier': self.student.email,\n })\n self.assertEqual(response.status_code, 400)", "label_name": "Compound", "label": 4} {"code": "def save_cover_from_url(url, book_path):\n try:\n if not cli.allow_localhost:\n # 127.0.x.x, localhost, [::1], [::ffff:7f00:1]\n ip = socket.getaddrinfo(urlparse(url).hostname, 0)[0][4][0]\n if ip.startswith(\"127.\") or ip.startswith('::ffff:7f') or ip == \"::1\":\n log.error(\"Localhost was accessed for cover upload\")\n return False, _(\"You are not allowed to access localhost for cover uploads\")\n img = requests.get(url, timeout=(10, 200)) # ToDo: Error Handling\n img.raise_for_status()\n return save_cover(img, book_path)\n except (socket.gaierror,\n requests.exceptions.HTTPError,\n requests.exceptions.ConnectionError,\n requests.exceptions.Timeout) as ex:\n log.info(u'Cover Download Error %s', ex)\n return False, _(\"Error Downloading Cover\")\n except MissingDelegateError as ex:\n log.info(u'File Format Error %s', ex)\n return False, _(\"Cover Format Error\")", "label_name": "Base", "label": 1} -{"code": " def __init__(self, env):\n Storage.__init__(self)\n self.env = Storage(env)\n self.env.web2py_path = global_settings.applications_parent\n self.env.update(global_settings)\n self.cookies = Cookie.SimpleCookie()\n self._get_vars = None\n self._post_vars = None\n self._vars = None\n self._body = None\n self.folder = None\n self.application = None\n self.function = None\n self.args = List()\n self.extension = 'html'\n self.now = datetime.datetime.now()\n self.utcnow = datetime.datetime.utcnow()\n self.is_restful = False\n self.is_https = False\n self.is_local = False\n self.global_settings = settings.global_settings\n self._uuid = None", "label_name": "CWE-255", "label": "CWE-255"} {"code": " def __init__(self, *, openapi: GeneratorData) -> None:\n self.openapi: GeneratorData = openapi\n self.env: Environment = Environment(loader=PackageLoader(__package__), trim_blocks=True, lstrip_blocks=True)\n\n self.project_name: str = self.project_name_override or f\"{openapi.title.replace(' ', '-').lower()}-client\"\n self.project_dir: Path = Path.cwd() / self.project_name\n\n self.package_name: str = self.package_name_override or self.project_name.replace(\"-\", \"_\")\n self.package_dir: Path = self.project_dir / self.package_name\n self.package_description: str = f\"A client library for accessing {self.openapi.title}\"\n self.version: str = openapi.version\n\n self.env.filters.update(self.TEMPLATE_FILTERS)", "label_name": "Base", "label": 1} {"code": " def DELETE(self, path, body=None, log_request_body=True):\n return self._request('DELETE', path, body=body, log_request_body=log_request_body)", "label_name": "Base", "label": 1} {"code": "def whitelist(allow_guest=False, xss_safe=False, methods=None):\n\t\"\"\"\n\tDecorator for whitelisting a function and making it accessible via HTTP.\n\tStandard request will be `/api/method/[path.to.method]`\n\n\t:param allow_guest: Allow non logged-in user to access this method.\n\t:param methods: Allowed http method to access the method.\n\n\tUse as:\n\n\t\t@frappe.whitelist()\n\t\tdef myfunc(param1, param2):\n\t\t\tpass\n\t\"\"\"\n\n\tif not methods:\n\t\tmethods = ['GET', 'POST', 'PUT', 'DELETE']\n\n\tdef innerfn(fn):\n\t\tglobal whitelisted, guest_methods, xss_safe_methods, allowed_http_methods_for_whitelisted_func\n\t\twhitelisted.append(fn)\n\n\t\tallowed_http_methods_for_whitelisted_func[fn] = methods\n\n\t\tif allow_guest:\n\t\t\tguest_methods.append(fn)\n\n\t\t\tif xss_safe:\n\t\t\t\txss_safe_methods.append(fn)\n\n\t\treturn fn\n\n\treturn innerfn", "label_name": "Base", "label": 1} @@ -1365,14 +1332,12 @@ {"code": " def _contains_display_name(self, display_name: str) -> bool:\n if not display_name:\n return False\n\n body = self._event.content.get(\"body\", None)\n if not body or not isinstance(body, str):\n return False\n\n # Similar to _glob_matches, but do not treat display_name as a glob.\n r = regex_cache.get((display_name, False, True), None)\n if not r:\n r1 = re.escape(display_name)\n r1 = _re_word_boundary(r1)\n r = re.compile(r1, flags=re.IGNORECASE)\n regex_cache[(display_name, False, True)] = r\n\n return bool(r.search(body))", "label_name": "Base", "label": 1} {"code": "def set_session_tracks(display_obj):\n \"\"\"Save igv tracks as a session object. This way it's easy to verify that a user is requesting one of these files from remote_static view endpoint\n\n Args:\n display_obj(dict): A display object containing case name, list of genes, lucus and tracks\n \"\"\"\n session_tracks = list(display_obj.get(\"reference_track\", {}).values())\n for key, track_items in display_obj.items():\n if key not in [\"tracks\", \"custom_tracks\", \"sample_tracks\"]:\n continue\n for track_item in track_items:\n session_tracks += list(track_item.values())\n\n session[\"igv_tracks\"] = session_tracks", "label_name": "Base", "label": 1} {"code": " def traverse(cls, base, request, path_items):\n \"\"\"See ``zope.app.pagetemplate.engine``.\"\"\"\n\n path_items = list(path_items)\n path_items.reverse()\n\n while path_items:\n name = path_items.pop()\n\n if name == '_':\n warnings.warn('Traversing to the name `_` is deprecated '\n 'and will be removed in Zope 6.',\n DeprecationWarning)\n elif name.startswith('_'):\n raise NotFound(name)\n\n if ITraversable.providedBy(base):\n base = getattr(base, cls.traverse_method)(name)\n else:\n base = traversePathElement(base, name, path_items,\n request=request)\n\n return base", "label_name": "Base", "label": 1} -{"code": " def save(self, text):\n self._create_dirs()\n with open(self._path, \"w\") as fd:\n fd.write(text)", "label_name": "CWE-21", "label": "CWE-21"} {"code": " def test_get_ora2_responses_success(self):\n url = reverse('export_ora2_data', kwargs={'course_id': unicode(self.course.id)})\n\n with patch('instructor_task.api.submit_export_ora2_data') as mock_submit_ora2_task:\n mock_submit_ora2_task.return_value = True\n response = self.client.get(url, {})\n success_status = \"The ORA data report is being generated.\"\n self.assertIn(success_status, response.content)", "label_name": "Compound", "label": 4} {"code": " def test_parse_header_bad_content_length(self):\n data = b\"GET /foobar HTTP/8.4\\ncontent-length: abc\"\n self.parser.parse_header(data)\n self.assertEqual(self.parser.body_rcv, None)", "label_name": "Base", "label": 1} {"code": "def profile():\n languages = calibre_db.speaking_language()\n translations = babel.list_translations() + [LC('en')]\n kobo_support = feature_support['kobo'] and config.config_kobo_sync\n if feature_support['oauth'] and config.config_login_type == 2:\n oauth_status = get_oauth_status()\n local_oauth_check = oauth_check\n else:\n oauth_status = None\n local_oauth_check = {}\n\n if request.method == \"POST\":\n change_profile(kobo_support, local_oauth_check, oauth_status, translations, languages)\n return render_title_template(\"user_edit.html\",\n translations=translations,\n profile=1,\n languages=languages,\n content=current_user,\n kobo_support=kobo_support,\n title=_(u\"%(name)s's profile\", name=current_user.name),\n page=\"me\",\n registered_oauth=local_oauth_check,\n oauth_status=oauth_status)", "label_name": "Base", "label": 1} {"code": " def testFlushFunction(self):\n logdir = self.get_temp_dir()\n with context.eager_mode():\n writer = summary_ops.create_file_writer_v2(\n logdir, max_queue=999999, flush_millis=999999)\n with writer.as_default():\n get_total = lambda: len(events_from_logdir(logdir))\n # Note: First tf.compat.v1.Event is always file_version.\n self.assertEqual(1, get_total())\n summary_ops.write('tag', 1, step=0)\n summary_ops.write('tag', 1, step=0)\n self.assertEqual(1, get_total())\n summary_ops.flush()\n self.assertEqual(3, get_total())\n # Test \"writer\" parameter\n summary_ops.write('tag', 1, step=0)\n self.assertEqual(3, get_total())\n summary_ops.flush(writer=writer)\n self.assertEqual(4, get_total())\n summary_ops.write('tag', 1, step=0)\n self.assertEqual(4, get_total())\n summary_ops.flush(writer=writer._resource) # pylint:disable=protected-access\n self.assertEqual(5, get_total())", "label_name": "Base", "label": 1} {"code": " async def on_send_join_request(\n self, origin: str, content: JsonDict, room_id: str", "label_name": "Class", "label": 2} {"code": "def put_file(path):\n try:\n dest_path = sanitized_join(\n path,\n pathlib.Path(app.config[\"DATA_ROOT\"]),\n )\n except ValueError:\n return flask.Response(\n \"Not Found\",\n 404,\n mimetype=\"text/plain\",\n )\n\n verification_key = flask.request.args.get(\"v\", \"\")\n length = int(flask.request.headers.get(\"Content-Length\", 0))\n hmac_input = \"{} {}\".format(path, length).encode(\"utf-8\")\n key = app.config[\"SECRET_KEY\"]\n mac = hmac.new(key, hmac_input, hashlib.sha256)\n digest = mac.hexdigest()\n\n if not hmac.compare_digest(digest, verification_key):\n return flask.Response(\n \"Invalid verification key\",\n 403,\n mimetype=\"text/plain\",\n )\n\n content_type = flask.request.headers.get(\n \"Content-Type\",\n \"application/octet-stream\",\n )\n\n dest_path.parent.mkdir(parents=True, exist_ok=True, mode=0o770)\n data_file, metadata_file = get_paths(dest_path)\n\n try:\n with write_file(data_file) as fout:\n stream_file(flask.request.stream, fout, length)\n\n with metadata_file.open(\"x\") as f:\n json.dump(\n {\n \"headers\": {\"Content-Type\": content_type},\n },\n f,\n )\n except EOFError:\n return flask.Response(\n \"Bad Request\",\n 400,\n mimetype=\"text/plain\",\n )\n except OSError as exc:\n if exc.errno == errno.EEXIST:\n return flask.Response(\n \"Conflict\",\n 409,\n mimetype=\"text/plain\",\n )\n raise\n\n return flask.Response(\n \"Created\",\n 201,\n mimetype=\"text/plain\",\n )", "label_name": "Base", "label": 1} -{"code": " def aesDecrypt(data, key):\n cipher = AES.new(key)\n\n return cipher.decrypt(data).rstrip()", "label_name": "CWE-310", "label": "CWE-310"} {"code": "def runserverobj(method, docs=None, dt=None, dn=None, arg=None, args=None):\n\tfrappe.desk.form.run_method.runserverobj(method, docs=docs, dt=dt, dn=dn, arg=arg, args=args)", "label_name": "Base", "label": 1} {"code": "def job_log(request, client_id, project_name, spider_name, job_id):\n \"\"\"\n get log of jog\n :param request: request object\n :param client_id: client id\n :param project_name: project name\n :param spider_name: spider name\n :param job_id: job id\n :return: log of job\n \"\"\"\n if request.method == 'GET':\n client = Client.objects.get(id=client_id)\n # get log url\n url = log_url(client.ip, client.port, project_name, spider_name, job_id)\n try:\n # get last 1000 bytes of log\n response = requests.get(url, timeout=5, headers={\n 'Range': 'bytes=-1000'\n }, auth=(client.username, client.password) if client.auth else None)\n # Get encoding\n encoding = response.apparent_encoding\n # log not found\n if response.status_code == 404:\n return JsonResponse({'message': 'Log Not Found'}, status=404)\n # bytes to string\n text = response.content.decode(encoding, errors='replace')\n return HttpResponse(text)\n except requests.ConnectionError:\n return JsonResponse({'message': 'Load Log Error'}, status=500)", "label_name": "Base", "label": 1} {"code": "def feed_publisher(book_id):\n off = request.args.get(\"offset\") or 0\n entries, __, pagination = calibre_db.fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), 0,\n db.Books,\n db.Books.publishers.any(db.Publishers.id == book_id),\n [db.Books.timestamp.desc()])\n return render_xml_template('feed.xml', entries=entries, pagination=pagination)", "label_name": "Base", "label": 1} @@ -1402,7 +1367,6 @@ {"code": " def testRuntimeError(self,\n inputs,\n exception=errors.InvalidArgumentError,\n message=None):", "label_name": "Base", "label": 1} {"code": "def toggle_archived(book_id):\n is_archived = change_archived_books(book_id, message=\"Book {} archivebit toggled\".format(book_id))\n if is_archived:\n remove_synced_book(book_id)\n return \"\"", "label_name": "Base", "label": 1} {"code": " public ClassPathResource(String path, ClassLoader classLoader) {\n Assert.notNull(path, \"Path must not be null\");\n Assert.state(doesNotContainFileColon(path), \"Path must not contain 'file:'\");\n\n String pathToUse = StringUtils.cleanPath(path);\n\n if (pathToUse.startsWith(\"/\")) {\n pathToUse = pathToUse.substring(1);\n }\n\n this.path = pathToUse;\n this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());\n }", "label_name": "Base", "label": 1} -{"code": " public SslClientCertificateCredential(File certificate, String password) throws IOException {\n this.password = Scrambler.scramble(password);\n this.certificate = Secret.fromString(new String(Base64.encode(FileUtils.readFileToByteArray(certificate))));\n }", "label_name": "CWE-255", "label": "CWE-255"} {"code": " public void cleanup() {\n }", "label_name": "Class", "label": 2} {"code": " void doubleQuote() {\n final PathAndQuery res = PathAndQuery.parse(\"/\\\"?\\\"\");\n assertThat(res).isNotNull();\n assertThat(res.path()).isEqualTo(\"/%22\");\n assertThat(res.query()).isEqualTo(\"%22\");\n }", "label_name": "Base", "label": 1} {"code": " protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n String encoding = request.getHeader(\"Accept-Encoding\");\n boolean supportsGzip = (encoding != null && encoding.toLowerCase().indexOf(\"gzip\") > -1);\n SessionTerminal st = (SessionTerminal) request.getSession(true).getAttribute(\"terminal\");\n if (st == null || st.isClosed()) {\n st = new SessionTerminal(getCommandProcessor(), getThreadIO());\n request.getSession().setAttribute(\"terminal\", st);\n }\n String str = request.getParameter(\"k\");\n String f = request.getParameter(\"f\");\n String dump = st.handle(str, f != null && f.length() > 0);\n if (dump != null) {\n if (supportsGzip) {\n response.setHeader(\"Content-Encoding\", \"gzip\");\n response.setHeader(\"Content-Type\", \"text/html\");\n try {\n GZIPOutputStream gzos = new GZIPOutputStream(response.getOutputStream());\n gzos.write(dump.getBytes());\n gzos.close();\n } catch (IOException ie) {\n LOG.info(\"Exception writing response: \", ie);\n }\n } else {\n response.getOutputStream().write(dump.getBytes());\n }\n }\n }", "label_name": "Class", "label": 2} @@ -1410,7 +1374,6 @@ {"code": " public static void init(final InitialContext applicationContext) {\n synchronized (GeoTools.class) {\n context = applicationContext;\n }\n fireConfigurationChanged();\n }", "label_name": "Class", "label": 2} {"code": " public void existingDocumentFromUIDeprecatedCheckEscaping() throws Exception\n {\n // current document = xwiki:Main.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"Main\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(false);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Submit from the UI space=X.Y&page=Z\n when(mockRequest.getParameter(\"space\")).thenReturn(\"X.Y\");\n when(mockRequest.getParameter(\"page\")).thenReturn(\"Z\");\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note1: The space parameter was previously considered as space name, not space reference, so it is escaped.\n // Note2: We are creating X\\.Y.Z since the deprecated parameters were creating terminal documents by default.\n verify(mockURLFactory).createURL(\"X\\\\.Y\", \"Z\", \"edit\", \"template=&parent=Main.WebHome&title=Z\", null, \"xwiki\",\n context);\n }", "label_name": "Class", "label": 2} {"code": " for (final ReservedChar reservedChar : ReservedChar.values()) {\n RAW_CHAR_TO_MARKER[reservedChar.rawChar] = reservedChar.marker;\n MARKER_TO_PERCENT_ENCODED_CHAR[reservedChar.marker] = reservedChar.percentEncodedChar;\n }", "label_name": "Base", "label": 1} -{"code": " public OldECIESwithAESCBC()\n {\n super(new CBCBlockCipher(new AESEngine()), 16);\n }", "label_name": "CWE-310", "label": "CWE-310"} {"code": " public String getStringParameterSQL(String param) {\n return \"'\" + param + \"'\";\n }", "label_name": "Base", "label": 1} {"code": " static void setAttribute(TransformerFactory transformerFactory, String attributeName) {\n try {\n transformerFactory.setAttribute(attributeName, \"\");\n } catch (IllegalArgumentException iae) {\n if (Boolean.getBoolean(SYSTEM_PROPERTY_IGNORE_XXE_PROTECTION_FAILURES)) {\n LOGGER.warning(\"Enabling XXE protection failed. The attribute \" + attributeName\n + \" is not supported by the TransformerFactory. The \" + SYSTEM_PROPERTY_IGNORE_XXE_PROTECTION_FAILURES\n + \" system property is used so the XML processing continues in the UNSECURE mode\"\n + \" with XXE protection disabled!!!\");\n } else {\n LOGGER.severe(\"Enabling XXE protection failed. The attribute \" + attributeName\n + \" is not supported by the TransformerFactory. This usually mean an outdated XML processor\"\n + \" is present on the classpath (e.g. Xerces, Xalan). If you are not able to resolve the issue by\"\n + \" fixing the classpath, the \" + SYSTEM_PROPERTY_IGNORE_XXE_PROTECTION_FAILURES\n + \" system property can be used to disable XML External Entity protections.\"\n + \" We don't recommend disabling the XXE as such the XML processor configuration is unsecure!!!\", iae);\n throw iae;\n }\n }\n }", "label_name": "Base", "label": 1} {"code": "\tpublic static void writeObject(XStream xStream, OutputStream os, Object obj) {\n\t\ttry(OutputStreamWriter osw = new OutputStreamWriter(os, ENCODING)) {\n\t\t\tString data = xStream.toXML(obj);\n\t\t\tdata = \"\\n\"\n\t\t\t\t\t+ data; // give a decent header with the encoding used\n\t\t\tosw.write(data);\n\t\t\tosw.flush();\n\t\t} catch (Exception e) {\n\t\t\tthrow new OLATRuntimeException(XStreamHelper.class, \"Could not write object to stream.\", e);\n\t\t}\n\t}", "label_name": "Base", "label": 1} @@ -1419,12 +1382,9 @@ {"code": " public void newDocumentWebHomeButTerminalFromURL() throws Exception\n {\n // new document = xwiki:X.Y.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"X\", \"Y\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(true);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Pass the tocreate=terminal request parameter\n when(mockRequest.getParameter(\"tocreate\")).thenReturn(\"terminal\");\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note: We are creating X.Y instead of X.Y.WebHome because the tocreate parameter says \"terminal\".\n verify(mockURLFactory).createURL(\"X\", \"Y\", \"edit\", \"template=&parent=Main.WebHome&title=Y\", null, \"xwiki\",\n context);\n }", "label_name": "Class", "label": 2} {"code": " parse_io(ThreadContext context,\n IRubyObject klazz,\n IRubyObject data,\n IRubyObject enc)\n {\n //int encoding = (int)enc.convertToInteger().getLongValue();\n final Ruby runtime = context.runtime;\n XmlSaxParserContext ctx = newInstance(runtime, (RubyClass) klazz);\n ctx.initialize(runtime);\n ctx.setIOInputSource(context, data, runtime.getNil());\n return ctx;\n }", "label_name": "Base", "label": 1} {"code": " public void setUp(@TempDir Path tempDir) throws IOException {\n serverRepo = TempDirUtils.createTempDirectoryIn(tempDir, \"testHgServerRepo\").toFile();\n clientRepo = TempDirUtils.createTempDirectoryIn(tempDir, \"testHgClientRepo\").toFile();\n secondBranchWorkingCopy = TempDirUtils.createTempDirectoryIn(tempDir, \"second\").toFile();\n\n setUpServerRepoFromHgBundle(serverRepo, new File(\"../common/src/test/resources/data/hgrepo.hgbundle\"));\n workingDirectory = new File(clientRepo.getPath());\n hgCommand = new HgCommand(null, workingDirectory, \"default\", serverRepo.getAbsolutePath(), null);\n hgCommand.clone(outputStreamConsumer, new UrlArgument(serverRepo.getAbsolutePath()));\n }", "label_name": "Class", "label": 2} -{"code": " static String getVIMID()\n {\n if (vimIDConstructor != null)\n {\n Object vimID = null;\n try\n {\n vimID = vimIDConstructor.newInstance();\n }\n catch (Exception i)\n {\n // might happen, fall through if it does\n }\n if (vimID != null)\n {\n return vimID.toString();\n }\n }\n\n return \"No VIM ID\"; // TODO: maybe there is a system property we can use here.\n }", "label_name": "CWE-310", "label": "CWE-310"} {"code": " public Map handleCorsPreflightRequest(String pOrigin, String pRequestHeaders) {\n Map ret = new HashMap();\n if (pOrigin != null && backendManager.isCorsAccessAllowed(pOrigin)) {\n // CORS is allowed, we set exactly the origin in the header, so there are no problems with authentication\n ret.put(\"Access-Control-Allow-Origin\",\"null\".equals(pOrigin) ? \"*\" : pOrigin);\n if (pRequestHeaders != null) {\n ret.put(\"Access-Control-Allow-Headers\",pRequestHeaders);\n }\n // Fix for CORS with authentication (#104)\n ret.put(\"Access-Control-Allow-Credentials\",\"true\");\n // Allow for one year. Changes in access.xml are reflected directly in the cors request itself\n ret.put(\"Access-Control-Allow-Max-Age\",\"\" + 3600 * 24 * 365);\n }\n return ret;\n }", "label_name": "Compound", "label": 4} {"code": " public void simpleGetWithUnsupportedGetParameterMapCall() throws ServletException, IOException {\n prepareStandardInitialisation();\n StringWriter sw = initRequestResponseMocks(\n new Runnable() {\n public void run() {\n expect(request.getHeader(\"Origin\")).andReturn(null);\n expect(request.getRemoteHost()).andReturn(\"localhost\");\n expect(request.getRemoteAddr()).andReturn(\"127.0.0.1\");\n expect(request.getRequestURI()).andReturn(\"/jolokia/\");\n expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST);\n expect(request.getParameterMap()).andThrow(new UnsupportedOperationException(\"\"));\n Vector params = new Vector();\n params.add(\"debug\");\n expect(request.getParameterNames()).andReturn(params.elements());\n expect(request.getParameterValues(\"debug\")).andReturn(new String[] {\"false\"});\n }\n },\n getStandardResponseSetup());\n expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn(null);\n replay(request,response);\n\n servlet.doGet(request,response);\n servlet.destroy();\n }", "label_name": "Compound", "label": 4} -{"code": " private void updateSecureSessionFlag() {\n try {\n ServletContext context = Jenkins.getInstance().servletContext;\n Method m;\n try {\n m = context.getClass().getMethod(\"getSessionCookieConfig\");\n } catch (NoSuchMethodException x) { // 3.0+\n LOGGER.log(Level.FINE, \"Failed to set secure cookie flag\", x);\n return;\n }\n Object sessionCookieConfig = m.invoke(context);\n\n // not exposing session cookie to JavaScript to mitigate damage caused by XSS\n Class scc = Class.forName(\"javax.servlet.SessionCookieConfig\");\n Method setHttpOnly = scc.getMethod(\"setHttpOnly\",boolean.class);\n setHttpOnly.invoke(sessionCookieConfig,true);\n\n Method setSecure = scc.getMethod(\"setSecure\",boolean.class);\n boolean v = fixNull(jenkinsUrl).startsWith(\"https\");\n setSecure.invoke(sessionCookieConfig,v);\n } catch (Exception e) {\n LOGGER.log(Level.WARNING, \"Failed to set secure cookie flag\", e);\n }\n }", "label_name": "CWE-254", "label": "CWE-254"} {"code": " public void annotatedSubClassExample() throws Exception {\n assertThat(ConstraintViolations.format(validator.validate(new AnnotatedSubclassExample())))\n .containsExactlyInAnyOrder(\n FAILED_RESULT,\n FAILED_RESULT+\"subclass\"\n );\n assertThat(TestLoggerFactory.getAllLoggingEvents())\n .isEmpty();\n }", "label_name": "Class", "label": 2} -{"code": " protected void engineInit(\n byte[] params)\n throws IOException\n {\n try\n {\n ASN1Sequence s = (ASN1Sequence)ASN1Primitive.fromByteArray(params);\n\n if (s.size() == 1)\n {\n this.currentSpec = new IESParameterSpec(null, null, ASN1Integer.getInstance(s.getObjectAt(0)).getValue().intValue());\n }\n else if (s.size() == 2)\n {\n ASN1TaggedObject tagged = ASN1TaggedObject.getInstance(s.getObjectAt(0));\n\n if (tagged.getTagNo() == 0)\n {\n this.currentSpec = new IESParameterSpec(ASN1OctetString.getInstance(tagged, false).getOctets(), null, ASN1Integer.getInstance(s.getObjectAt(1)).getValue().intValue());\n }\n else\n {\n this.currentSpec = new IESParameterSpec(null, ASN1OctetString.getInstance(tagged, false).getOctets(), ASN1Integer.getInstance(s.getObjectAt(1)).getValue().intValue());\n }\n }\n else\n {\n ASN1TaggedObject tagged1 = ASN1TaggedObject.getInstance(s.getObjectAt(0));\n ASN1TaggedObject tagged2 = ASN1TaggedObject.getInstance(s.getObjectAt(1));\n\n this.currentSpec = new IESParameterSpec(ASN1OctetString.getInstance(tagged1, false).getOctets(), ASN1OctetString.getInstance(tagged2, false).getOctets(), ASN1Integer.getInstance(s.getObjectAt(2)).getValue().intValue());\n }\n }\n catch (ClassCastException e)\n {\n throw new IOException(\"Not a valid IES Parameter encoding.\");\n }\n catch (ArrayIndexOutOfBoundsException e)\n {\n throw new IOException(\"Not a valid IES Parameter encoding.\");\n }\n }", "label_name": "CWE-310", "label": "CWE-310"} {"code": " public void setUp() throws Exception {\n super.setUp();\n TestUtil.createTempTable(con, \"xmltab\",\"x xml\");\n }", "label_name": "Base", "label": 1} {"code": " public void translate(ServerUpdateScorePacket packet, GeyserSession session) {\n WorldCache worldCache = session.getWorldCache();\n Scoreboard scoreboard = worldCache.getScoreboard();\n int pps = worldCache.increaseAndGetScoreboardPacketsPerSecond();\n\n Objective objective = scoreboard.getObjective(packet.getObjective());\n if (objective == null && packet.getAction() != ScoreboardAction.REMOVE) {\n logger.info(LanguageUtils.getLocaleStringLog(\"geyser.network.translator.score.failed_objective\", packet.getObjective()));\n return;\n }\n\n switch (packet.getAction()) {\n case ADD_OR_UPDATE:\n objective.setScore(packet.getEntry(), packet.getValue());\n break;\n case REMOVE:\n if (objective != null) {\n objective.removeScore(packet.getEntry());\n } else {\n for (Objective objective1 : scoreboard.getObjectives().values()) {\n objective1.removeScore(packet.getEntry());\n }\n }\n break;\n }\n\n // ScoreboardUpdater will handle it for us if the packets per second\n // (for score and team packets) is higher then the first threshold\n if (pps < ScoreboardUpdater.FIRST_SCORE_PACKETS_PER_SECOND_THRESHOLD) {\n scoreboard.onUpdate();\n }\n }", "label_name": "Class", "label": 2} {"code": "\tpublic void reportJobCaches(byte[] cacheInstanceBytes) {\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tCollection cacheInstances = (Collection) SerializationUtils\n\t\t\t\t.deserialize(cacheInstanceBytes);\n\t\tjobManager.reportJobCaches(getJobToken(), cacheInstances);\n\t}", "label_name": "Base", "label": 1} @@ -1436,14 +1396,12 @@ {"code": " public String getEncoding() {\n return encoding;\n }", "label_name": "Base", "label": 1} {"code": " private static File newFile() throws IOException {\n File file = File.createTempFile(\"netty-\", \".tmp\");\n file.deleteOnExit();\n\n final FileOutputStream out = new FileOutputStream(file);\n out.write(data);\n out.close();\n return file;\n }", "label_name": "Base", "label": 1} {"code": " public void newDocumentWebHomeTopLevelSpaceButTerminalFromURL() throws Exception\n {\n // new document = xwiki:X.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"X\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(true);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Pass the tocreate=terminal request parameter\n when(mockRequest.getParameter(\"tocreate\")).thenReturn(\"terminal\");\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify that the create template is rendered, so the UI is displayed for the user to enter the missing values.\n assertEquals(\"create\", result);\n\n // Note: We can not create the \"X\" terminal document, since it is already at the top level of the hierarchy and\n // none was able to be deducted from the given information. The user needs to specify more info in order to\n // continue.\n // We should not get this far so no redirect should be done, just the template will be rendered.\n verify(mockURLFactory, never()).createURL(any(), any(), any(), any(), any(),\n any(), any(XWikiContext.class));\n }", "label_name": "Class", "label": 2} -{"code": " public OldECIESwithDESede()\n {\n super(new DESedeEngine());\n }", "label_name": "CWE-310", "label": "CWE-310"} {"code": " private void renderState(FacesContext context) throws IOException {\n // Get the view state and write it to the response..\n PartialViewContext pvc = context.getPartialViewContext();\n PartialResponseWriter writer = pvc.getPartialResponseWriter();\n String viewStateId = Util.getViewStateId(context);\n\n writer.startUpdate(viewStateId);\n String state = context.getApplication().getStateManager().getViewState(context);\n writer.write(state);\n writer.endUpdate();\n\n ClientWindow window = context.getExternalContext().getClientWindow();\n if (null != window) {\n String clientWindowId = Util.getClientWindowId(context);\n writer.startUpdate(clientWindowId);\n writer.write(window.getId());\n writer.endUpdate();\n }\n }", "label_name": "Base", "label": 1} {"code": " public void warning(SAXParseException e) {\n }", "label_name": "Base", "label": 1} {"code": " public void testGetChunk() throws Exception {\n TestHttpData test = new TestHttpData(\"test\", UTF_8, 0);\n try {\n File tmpFile = File.createTempFile(UUID.randomUUID().toString(), \".tmp\");\n tmpFile.deleteOnExit();\n FileOutputStream fos = new FileOutputStream(tmpFile);\n byte[] bytes = new byte[4096];\n PlatformDependent.threadLocalRandom().nextBytes(bytes);\n try {\n fos.write(bytes);\n fos.flush();\n } finally {\n fos.close();\n }\n test.setContent(tmpFile);\n ByteBuf buf1 = test.getChunk(1024);\n assertEquals(buf1.readerIndex(), 0);\n assertEquals(buf1.writerIndex(), 1024);\n ByteBuf buf2 = test.getChunk(1024);\n assertEquals(buf2.readerIndex(), 0);\n assertEquals(buf2.writerIndex(), 1024);\n assertFalse(\"Arrays should not be equal\",\n Arrays.equals(ByteBufUtil.getBytes(buf1), ByteBufUtil.getBytes(buf2)));\n } finally {\n test.delete();\n }\n }", "label_name": "Base", "label": 1} {"code": "\tpublic String displayCategoryWithReference(@PathVariable final String friendlyUrl, @PathVariable final String ref, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {\n\t\t\n\t\t\n\t\t\n\t\treturn this.displayCategory(friendlyUrl,ref,model,request,response,locale);\n\t}", "label_name": "Base", "label": 1} {"code": " public void getWithDefaultValueWorks() {\n final HttpHeadersBase headers = newEmptyHeaders();\n headers.add(\"name1\", \"value1\");\n\n assertThat(headers.get(\"name1\", \"defaultvalue\")).isEqualTo(\"value1\");\n assertThat(headers.get(\"noname\", \"defaultvalue\")).isEqualTo(\"defaultvalue\");\n }", "label_name": "Class", "label": 2} {"code": "\tfinal protected Style getStyle() {\n\t\treturn getStyleSignature().getMergedStyle(skinParam.getCurrentStyleBuilder());\n\n\t}", "label_name": "Base", "label": 1} -{"code": " public Poly1305()\n {\n super(new org.bouncycastle.crypto.macs.Poly1305(new AESFastEngine()));\n }", "label_name": "CWE-310", "label": "CWE-310"} {"code": " public boolean verify(String token) {\n JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET))\n .withIssuer(ISSUER)\n .build();\n try {\n verifier.verify(token);\n return true;\n } catch (JWTVerificationException e) {\n log.warn(\"verify jwt token failed \" + e.getMessage());\n return false;\n }\n }", "label_name": "Class", "label": 2} {"code": " public void write(byte[] b, int offset, int length) throws IOException {\n if (b == null) {\n throw new NullPointerException();\n }\n\n if (offset < 0 || offset + length > b.length) {\n throw new ArrayIndexOutOfBoundsException();\n }\n\n write(fd, b, offset, length);\n }", "label_name": "Base", "label": 1} {"code": "\t\tprotected Class getClassForNode(Node node) {\r\n\t\t\tClass type = node.getType();\r\n\t\t\tif (type.getAnnotation(Editable.class) != null && !ClassUtils.isConcrete(type)) {\r\n\t\t\t\tImplementationRegistry registry = OneDev.getInstance(ImplementationRegistry.class);\r\n\t\t\t\tfor (Class implementationClass: registry.getImplementations(node.getType())) {\r\n\t\t\t\t\tString implementationTag = new Tag(\"!\" + implementationClass.getSimpleName()).getValue();\r\n\t\t\t\t\tif (implementationTag.equals(node.getTag().getValue()))\r\n\t\t\t\t\t\treturn implementationClass;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\treturn super.getClassForNode(node);\r\n\t\t}\r", "label_name": "Base", "label": 1} @@ -1451,7 +1409,6 @@ {"code": " public PropertiesRequest getRequestedFields( InputStream in ) {\r\n\t\tfinal Set set = new LinkedHashSet();\r\n try { \r\n ByteArrayOutputStream bout = new ByteArrayOutputStream();\r\n StreamUtils.readTo( in, bout, false, true );\r\n byte[] arr = bout.toByteArray();\r\n if( arr.length > 1 ) {\r\n ByteArrayInputStream bin = new ByteArrayInputStream( arr );\r\n XMLReader reader = XMLReaderFactory.createXMLReader();\r\n\t\t\t\treader.setFeature(\"http://xml.org/sax/features/external-parameter-entities\", false);\r\n PropFindSaxHandler handler = new PropFindSaxHandler();\r\n reader.setContentHandler( handler );\r\n try {\r\n reader.parse( new InputSource( bin ) );\r\n if( handler.isAllProp() ) {\r\n return new PropertiesRequest();\r\n } else {\r\n set.addAll( handler.getAttributes().keySet() );\r\n }\r\n } catch( IOException e ) {\r\n log.warn( \"exception parsing request body\", e );\r\n // ignore\r\n } catch( SAXException e ) {\r\n log.warn( \"exception parsing request body\", e );\r\n // ignore\r\n }\r\n } \r\n } catch( Exception ex ) {\r\n\t\t\t// There's a report of an exception being thrown here by IT Hit Webdav client\r\n\t\t\t// Perhaps we can just log the error and return an empty set. Usually this\r\n\t\t\t// class is wrapped by the MsPropFindRequestFieldParser which will use a default\r\n\t\t\t// set of properties if this returns an empty set\r\n\t\t\tlog.warn(\"Exception parsing PROPFIND request fields. Returning empty property set\", ex);\r\n //throw new RuntimeException( ex );\r\n }\r\n\t\treturn PropertiesRequest.toProperties(set);\r\n }\r", "label_name": "Base", "label": 1} {"code": " void validSaveRequestImageUploadAndConflictCheck() throws Exception\n {\n when(mockDocument.getRCSVersion()).thenReturn(new Version(\"1.2\"));\n when(mockClonedDocument.getRCSVersion()).thenReturn(new Version(\"1.2\"));\n when(mockClonedDocument.getComment()).thenReturn(\"My Changes\");\n when(mockClonedDocument.getLock(this.context)).thenReturn(mock(XWikiLock.class));\n when(mockForm.getTemplate()).thenReturn(\"\");\n when(this.propertiesConf.getProperty(\"edit.conflictChecking.enabled\")).thenReturn(true);\n when(mockRequest.getParameter(\"previousVersion\")).thenReturn(\"1.1\");\n context.put(\"ajax\", true);\n when(mockRequest.getParameter(\"forceSave\")).thenReturn(\"\");\n when(mockRequest.getParameter(\"isNew\")).thenReturn(\"true\");\n\n when(mockDocument.getDate()).thenReturn(new Date(42));\n when(mockRequest.getParameter(\"editingVersionDate\")).thenReturn(\"43\");\n when(this.documentRevisionProvider.getRevision(mockDocument, \"1.1\")).thenReturn(mock(XWikiDocument.class));\n when(mockDocument.getContentDiff(\"1.1\", \"1.2\", context)).thenReturn(Collections.emptyList());\n when(mockDocument.getMetaDataDiff(\"1.1\", \"1.2\", context)).thenReturn(Collections.emptyList());\n when(mockDocument.getObjectDiff(\"1.1\", \"1.2\", context)).thenReturn(Collections.emptyList());\n\n assertFalse(saveAction.save(this.context));\n assertEquals(new Version(\"1.2\"), this.context.get(\"SaveAction.savedObjectVersion\"));\n\n verify(mockClonedDocument).readFromTemplate(\"\", this.context);\n verify(mockClonedDocument).setAuthor(\"XWiki.FooBar\");\n verify(mockClonedDocument).setMetaDataDirty(true);\n verify(this.xWiki).checkSavingDocument(USER_REFERENCE, mockClonedDocument, \"My Changes\", false, this.context);\n verify(this.xWiki).saveDocument(mockClonedDocument, \"My Changes\", false, this.context);\n verify(mockClonedDocument).removeLock(this.context);\n\n }", "label_name": "Class", "label": 2} {"code": " public BCXMSSPrivateKey(PrivateKeyInfo keyInfo)\n throws IOException\n {\n XMSSKeyParams keyParams = XMSSKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters());\n this.treeDigest = keyParams.getTreeDigest().getAlgorithm();\n\n XMSSPrivateKey xmssPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey());\n\n try\n {\n XMSSPrivateKeyParameters.Builder keyBuilder = new XMSSPrivateKeyParameters\n .Builder(new XMSSParameters(keyParams.getHeight(), DigestUtil.getDigest(treeDigest)))\n .withIndex(xmssPrivateKey.getIndex())\n .withSecretKeySeed(xmssPrivateKey.getSecretKeySeed())\n .withSecretKeyPRF(xmssPrivateKey.getSecretKeyPRF())\n .withPublicSeed(xmssPrivateKey.getPublicSeed())\n .withRoot(xmssPrivateKey.getRoot());\n\n if (xmssPrivateKey.getBdsState() != null)\n {\n keyBuilder.withBDSState((BDS)XMSSUtil.deserialize(xmssPrivateKey.getBdsState()));\n }\n\n this.keyParams = keyBuilder.build();\n }\n catch (ClassNotFoundException e)\n {\n throw new IOException(\"ClassNotFoundException processing BDS state: \" + e.getMessage());\n }\n }", "label_name": "Base", "label": 1} -{"code": " public PBEWithAESCBC()\n {\n super(new CBCBlockCipher(new AESFastEngine()));\n }", "label_name": "CWE-310", "label": "CWE-310"} {"code": " public Document read(File file) throws DocumentException {\n try {\n /*\n * We cannot convert the file to an URL because if the filename\n * contains '#' characters, there will be problems with the URL in\n * the InputSource (because a URL like\n * http://myhost.com/index#anchor is treated the same as\n * http://myhost.com/index) Thanks to Christian Oetterli\n */\n InputSource source = new InputSource(new FileInputStream(file));\n if (this.encoding != null) {\n source.setEncoding(this.encoding);\n }\n String path = file.getAbsolutePath();\n\n if (path != null) {\n // Code taken from Ant FileUtils\n StringBuffer sb = new StringBuffer(\"file://\");\n\n // add an extra slash for filesystems with drive-specifiers\n if (!path.startsWith(File.separator)) {\n sb.append(\"/\");\n }\n\n path = path.replace('\\\\', '/');\n sb.append(path);\n\n source.setSystemId(sb.toString());\n }\n\n return read(source);\n } catch (FileNotFoundException e) {\n throw new DocumentException(e.getMessage(), e);\n }\n }", "label_name": "Base", "label": 1} {"code": " public DefaultArgument(Class type, String name, AnnotationMetadata annotationMetadata, Argument... genericTypes) {\n this.type = type;\n this.name = name;\n this.annotationMetadata = annotationMetadata != null ? annotationMetadata : AnnotationMetadata.EMPTY_METADATA;\n this.typeParameters = initializeTypeParameters(genericTypes);\n this.typeParameterArray = genericTypes;\n }", "label_name": "Class", "label": 2} {"code": " public DocumentFactory getDocumentFactory() {\n if (factory == null) {\n factory = DocumentFactory.getInstance();\n }\n\n return factory;\n }", "label_name": "Base", "label": 1} @@ -1459,15 +1416,12 @@ {"code": " public void translate(ServerEntityPositionRotationPacket packet, GeyserSession session) {\n Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());\n if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {\n entity = session.getPlayerEntity();\n }\n if (entity == null) return;\n\n entity.updatePositionAndRotation(session, packet.getMoveX(), packet.getMoveY(), packet.getMoveZ(), packet.getYaw(), packet.getPitch(), packet.isOnGround());\n }", "label_name": "Class", "label": 2} {"code": " private boolean pull(ConsoleOutputStreamConsumer outputStreamConsumer) {\n CommandLine hg = hg(\"pull\", \"-b\", branch, \"--config\", String.format(\"paths.default=%s\", url));\n return execute(hg, outputStreamConsumer) == 0;\n }", "label_name": "Class", "label": 2} {"code": " public static void encryptPlayerConnection(GeyserConnector connector, GeyserSession session, LoginPacket loginPacket) {\n JsonNode certData;\n try {\n certData = JSON_MAPPER.readTree(loginPacket.getChainData().toByteArray());\n } catch (IOException ex) {\n throw new RuntimeException(\"Certificate JSON can not be read.\");\n }\n\n JsonNode certChainData = certData.get(\"chain\");\n if (certChainData.getNodeType() != JsonNodeType.ARRAY) {\n throw new RuntimeException(\"Certificate data is not valid\");\n }\n\n encryptConnectionWithCert(connector, session, loginPacket.getSkinData().toString(), certChainData);\n }", "label_name": "Class", "label": 2} -{"code": " public PBEWithSHA1AESCBC256()\n {\n super(new CBCBlockCipher(new AESFastEngine()), PKCS12, SHA1, 256, 16);\n }", "label_name": "CWE-310", "label": "CWE-310"} {"code": "\tpublic String displayCategoryWithReference(@PathVariable final String friendlyUrl, @PathVariable final String ref, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {\n\t\t\n\t\t\n\t\t\n\t\treturn this.displayCategory(friendlyUrl,ref,model,request,response,locale);\n\t}", "label_name": "Base", "label": 1} {"code": "\tpublic static byte[] transcodeSignatureToConcat(final byte[] derSignature, int outputLength)\n\t\tthrows JOSEException {\n\n\t\tif (derSignature.length < 8 || derSignature[0] != 48) {\n\t\t\tthrow new JOSEException(\"Invalid ECDSA signature format\");\n\t\t}\n\n\t\tint offset;\n\t\tif (derSignature[1] > 0) {\n\t\t\toffset = 2;\n\t\t} else if (derSignature[1] == (byte) 0x81) {\n\t\t\toffset = 3;\n\t\t} else {\n\t\t\tthrow new JOSEException(\"Invalid ECDSA signature format\");\n\t\t}\n\n\t\tbyte rLength = derSignature[offset + 1];\n\n\t\tint i;\n\t\tfor (i = rLength; (i > 0) && (derSignature[(offset + 2 + rLength) - i] == 0); i--) {\n\t\t\t// do nothing\n\t\t}\n\n\t\tbyte sLength = derSignature[offset + 2 + rLength + 1];\n\n\t\tint j;\n\t\tfor (j = sLength; (j > 0) && (derSignature[(offset + 2 + rLength + 2 + sLength) - j] == 0); j--) {\n\t\t\t// do nothing\n\t\t}\n\n\t\tint rawLen = Math.max(i, j);\n\t\trawLen = Math.max(rawLen, outputLength / 2);\n\n\t\tif ((derSignature[offset - 1] & 0xff) != derSignature.length - offset\n\t\t\t|| (derSignature[offset - 1] & 0xff) != 2 + rLength + 2 + sLength\n\t\t\t|| derSignature[offset] != 2\n\t\t\t|| derSignature[offset + 2 + rLength] != 2) {\n\t\t\tthrow new JOSEException(\"Invalid ECDSA signature format\");\n\t\t}\n\n\t\tfinal byte[] concatSignature = new byte[2 * rawLen];\n\n\t\tSystem.arraycopy(derSignature, (offset + 2 + rLength) - i, concatSignature, rawLen - i, i);\n\t\tSystem.arraycopy(derSignature, (offset + 2 + rLength + 2 + sLength) - j, concatSignature, 2 * rawLen - j, j);\n\n\t\treturn concatSignature;\n\t}", "label_name": "Base", "label": 1} {"code": " /*package*/ static Secret tryDecrypt(Cipher cipher, byte[] in) throws UnsupportedEncodingException {\n try {\n String plainText = new String(cipher.doFinal(in), \"UTF-8\");\n if(plainText.endsWith(MAGIC))\n return new Secret(plainText.substring(0,plainText.length()-MAGIC.length()));\n return null;\n } catch (GeneralSecurityException e) {\n return null; // if the key doesn't match with the bytes, it can result in BadPaddingException\n }\n }", "label_name": "Class", "label": 2} -{"code": " public OldECIES()\n {\n super(new OldIESEngine(new ECDHBasicAgreement(),\n new KDF2BytesGenerator(new SHA1Digest()),\n new HMac(new SHA1Digest())));\n }", "label_name": "CWE-310", "label": "CWE-310"} {"code": " public Optional convert(Object object, Class targetType, ConversionContext context) {\n CorsOriginConfiguration configuration = new CorsOriginConfiguration();\n if (object instanceof Map) {\n Map mapConfig = (Map) object;\n ConvertibleValues convertibleValues = new ConvertibleValuesMap<>(mapConfig);\n\n convertibleValues\n .get(ALLOWED_ORIGINS, Argument.listOf(String.class))\n .ifPresent(configuration::setAllowedOrigins);\n\n convertibleValues\n .get(ALLOWED_METHODS, Argument.listOf(HttpMethod.class))\n .ifPresent(configuration::setAllowedMethods);\n\n convertibleValues\n .get(ALLOWED_HEADERS, Argument.listOf(String.class))\n .ifPresent(configuration::setAllowedHeaders);\n\n convertibleValues\n .get(EXPOSED_HEADERS, Argument.listOf(String.class))\n .ifPresent(configuration::setExposedHeaders);\n\n convertibleValues\n .get(ALLOW_CREDENTIALS, Boolean.class)\n .ifPresent(configuration::setAllowCredentials);\n\n convertibleValues\n .get(MAX_AGE, Long.class)\n .ifPresent(configuration::setMaxAge);\n }\n return Optional.of(configuration);\n }", "label_name": "Class", "label": 2} {"code": "\tpublic static ResourceEvaluation evaluate(File file, String filename) {\n\t\tResourceEvaluation eval = new ResourceEvaluation();\n\t\ttry {\n\t\t\tImsManifestFileFilter visitor = new ImsManifestFileFilter();\n\t\t\tPath fPath = PathUtils.visit(file, filename, visitor);\n\t\t\tif(visitor.isValid()) {\n\t\t\t\tPath realManifestPath = visitor.getManifestPath();\n\t\t\t\tPath manifestPath = fPath.resolve(realManifestPath);\n\t\t\t\t\n\t\t\t\tRootSearcher rootSearcher = new RootSearcher();\n\t\t\t\tFiles.walkFileTree(fPath, rootSearcher);\n\t\t\t\tif(rootSearcher.foundRoot()) {\n\t\t\t\t\tmanifestPath = rootSearcher.getRoot().resolve(IMS_MANIFEST);\n\t\t\t\t} else {\n\t\t\t\t\tmanifestPath = fPath.resolve(IMS_MANIFEST);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tQTI21ContentPackage\tcp = new QTI21ContentPackage(manifestPath);\n\t\t\t\tif(validateImsManifest(cp, new PathResourceLocator(manifestPath.getParent()))) {\n\t\t\t\t\teval.setValid(true);\n\t\t\t\t} else {\n\t\t\t\t\teval.setValid(false);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\teval.setValid(false);\n\t\t\t}\n\t\t\tPathUtils.closeSubsequentFS(fPath);\n\t\t} catch (IOException | IllegalArgumentException e) {\n\t\t\tlog.error(\"\", e);\n\t\t\teval.setValid(false);\n\t\t}\n\t\treturn eval;\n\t}", "label_name": "Base", "label": 1} {"code": " public void corsNoTags() {\n InputStream is = getClass().getResourceAsStream(\"/access-sample1.xml\");\n PolicyRestrictor restrictor = new PolicyRestrictor(is);\n\n assertTrue(restrictor.isCorsAccessAllowed(\"http://bla.com\"));\n assertTrue(restrictor.isCorsAccessAllowed(\"http://www.jolokia.org\"));\n assertTrue(restrictor.isCorsAccessAllowed(\"https://www.consol.de\"));\n }", "label_name": "Compound", "label": 4} -{"code": " public OldIES()\n {\n super(new OldIESEngine(new DHBasicAgreement(),\n new KDF2BytesGenerator(new SHA1Digest()),\n new HMac(new SHA1Digest())));\n }", "label_name": "CWE-310", "label": "CWE-310"} {"code": " protected XWikiDocument prepareEditedDocument(XWikiContext context) throws XWikiException\n {\n // Determine the edited document (translation).\n XWikiDocument editedDocument = getEditedDocument(context);\n EditForm editForm = (EditForm) context.getForm();\n\n // Update the edited document based on the template specified on the request.\n editedDocument.readFromTemplate(editForm, context);\n\n // The default values from the template can be overwritten by additional request parameters.\n updateDocumentTitleAndContentFromRequest(editedDocument, context);\n editedDocument.readObjectsFromForm(editForm, context);\n\n // Set the current user as creator, author and contentAuthor when the edited document is newly created to avoid\n // using XWikiGuest instead (because those fields were not previously initialized).\n if (editedDocument.isNew()) {\n editedDocument.setCreatorReference(context.getUserReference());\n editedDocument.setAuthorReference(context.getUserReference());\n editedDocument.setContentAuthorReference(context.getUserReference());\n }\n\n // Expose the edited document on the XWiki context and the Velocity context.\n putDocumentOnContext(editedDocument, context);\n\n return editedDocument;\n }", "label_name": "Class", "label": 2} {"code": "\tpublic static HColor noGradient(HColor color) {\n\t\tif (color instanceof HColorGradient) {\n\t\t\treturn ((HColorGradient) color).getColor1();\n\t\t}\n\t\treturn color;\n\t}", "label_name": "Base", "label": 1} {"code": " public void preflightCheck() {\n String origin = \"http://bla.com\";\n String headers =\"X-Data: Test\";\n expect(backend.isCorsAccessAllowed(origin)).andReturn(true);\n replay(backend);\n\n Map ret = handler.handleCorsPreflightRequest(origin, headers);\n assertEquals(ret.get(\"Access-Control-Allow-Origin\"),origin);\n }", "label_name": "Compound", "label": 4} @@ -1479,7 +1433,6 @@ {"code": " void doubleDots() {\n assertThat(PathAndQuery.parse(\"/..\")).isNull();\n assertThat(PathAndQuery.parse(\"/../\")).isNull();\n assertThat(PathAndQuery.parse(\"/../foo\")).isNull();\n assertThat(PathAndQuery.parse(\"/foo/..\")).isNull();\n assertThat(PathAndQuery.parse(\"/foo/../\")).isNull();\n assertThat(PathAndQuery.parse(\"/foo/../bar\")).isNull();\n\n // Escaped\n assertThat(PathAndQuery.parse(\"/.%2e\")).isNull();\n assertThat(PathAndQuery.parse(\"/%2E./\")).isNull();\n assertThat(PathAndQuery.parse(\"/foo/.%2e\")).isNull();\n assertThat(PathAndQuery.parse(\"/foo/%2E./\")).isNull();\n\n // Not the double dots we are looking for.\n final PathAndQuery res = PathAndQuery.parse(\"/..a\");\n assertThat(res).isNotNull();\n assertThat(res.path()).isEqualTo(\"/..a\");\n final PathAndQuery res2 = PathAndQuery.parse(\"/a..\");\n assertThat(res2).isNotNull();\n assertThat(res2.path()).isEqualTo(\"/a..\");\n }", "label_name": "Base", "label": 1} {"code": "\tprivate Style getStyleState() {\n\t\treturn StyleSignatureBasic.of(SName.root, SName.element, SName.stateDiagram, SName.state).withTOBECHANGED(group.getStereotype())\n\t\t\t\t.getMergedStyle(diagram.getSkinParam().getCurrentStyleBuilder());\n\t}", "label_name": "Base", "label": 1} {"code": " public void subClassExample() throws Exception {\n assertThat(ConstraintViolations.format(validator.validate(new SubclassExample())))\n .containsExactlyInAnyOrder(\n FAILED_RESULT,\n FAILED_RESULT+\"subclass\"\n );\n assertThat(TestLoggerFactory.getAllLoggingEvents())\n .isEmpty();\n }", "label_name": "Class", "label": 2} -{"code": " public OldECIESwithAES()\n {\n super(new AESEngine());\n }", "label_name": "CWE-310", "label": "CWE-310"} {"code": " public static Object deserialize(byte[] data)\n throws IOException, ClassNotFoundException\n {\n ByteArrayInputStream in = new ByteArrayInputStream(data);\n ObjectInputStream is = new ObjectInputStream(in);\n return is.readObject();\n }", "label_name": "Base", "label": 1} {"code": " public void encodeDeepBinaryJSONWithNullValue() throws JSONException {\n JSONObject data = new JSONObject(\"{a: \\\"b\\\", c: 4, e: {g: null}, h: null}\");\n data.put(\"h\", new byte[9]);\n\n Packet packet = new Packet<>(Parser.BINARY_EVENT);\n packet.data = data;\n packet.nsp = \"/\";\n packet.id = 600;\n Helpers.testBin(packet);\n }", "label_name": "Base", "label": 1} {"code": " private String buildRedirectAuthnRequest(AuthnRequestType authnRequest, String relayState, boolean sign,\n PrivateKey key, Algorithm algorithm) throws SAMLException {\n try {\n byte[] xml = marshallToBytes(PROTOCOL_OBJECT_FACTORY.createAuthnRequest(authnRequest), AuthnRequestType.class);\n String encodedResult = deflateAndEncode(xml);\n String parameters = \"SAMLRequest=\" + URLEncoder.encode(encodedResult, \"UTF-8\");\n if (relayState != null) {\n parameters += \"&RelayState=\" + URLEncoder.encode(relayState, \"UTF-8\");\n }\n\n if (sign && key != null && algorithm != null) {\n Signature signature;\n parameters += \"&SigAlg=\" + URLEncoder.encode(algorithm.uri, \"UTF-8\");\n signature = Signature.getInstance(algorithm.name);\n signature.initSign(key);\n signature.update(parameters.getBytes(StandardCharsets.UTF_8));\n\n String signatureParameter = Base64.getEncoder().encodeToString(signature.sign());\n parameters += \"&Signature=\" + URLEncoder.encode(signatureParameter, \"UTF-8\");\n }\n\n return parameters;\n } catch (Exception e) {\n // Not possible but freak out\n throw new SAMLException(e);\n }\n }", "label_name": "Base", "label": 1} @@ -1495,13 +1448,11 @@ {"code": "\tpublic void onTurnEnded(TurnEndedEvent event) {\n\t\tsuper.onTurnEnded(event);\n\n\t\tfinal String out = event.getTurnSnapshot().getRobots()[0].getOutputStreamSnapshot();\n\n\t\tif (out.contains(\"access denied (java.net.SocketPermission\")\n\t\t\t\t|| out.contains(\"access denied (\\\"java.net.SocketPermission\\\"\")) {\n\t\t\tmessagedAccessDenied = true;\t\n\t\t}\t\n\t}", "label_name": "Class", "label": 2} {"code": " private String attributeToString(Object attribute) {\n if (attribute == null) {\n return null;\n }\n\n if (attribute instanceof Number) {\n return attribute.toString();\n } else if (attribute instanceof String) {\n return (String) attribute;\n } else if (attribute instanceof Element) {\n return ((Element) attribute).getTextContent();\n } else {\n logger.warn(\"This library currently doesn't handle attributes of type [\" + attribute.getClass() + \"]\");\n }\n\n return null;\n }", "label_name": "Base", "label": 1} {"code": " public AbstractXmlConfigRootTagRecognizer(String expectedRootNode) throws Exception {\n this.expectedRootNode = expectedRootNode;\n SAXParserFactory factory = SAXParserFactory.newInstance();\n saxParser = factory.newSAXParser();\n }", "label_name": "Base", "label": 1} -{"code": " private void testEnc()\n throws Exception\n {\n KeyFactory kFact = KeyFactory.getInstance(\"DH\", \"BC\");\n\n Key k = kFact.generatePrivate(new PKCS8EncodedKeySpec(samplePrivEnc));\n\n if (!Arrays.areEqual(samplePrivEnc, k.getEncoded()))\n {\n fail(\"private key re-encode failed\");\n }\n\n k = kFact.generatePublic(new X509EncodedKeySpec(samplePubEnc));\n\n if (!Arrays.areEqual(samplePubEnc, k.getEncoded()))\n {\n fail(\"public key re-encode failed\");\n }\n\n k = kFact.generatePublic(new X509EncodedKeySpec(oldPubEnc));\n\n if (!Arrays.areEqual(oldPubEnc, k.getEncoded()))\n {\n fail(\"old public key re-encode failed\");\n }\n\n k = kFact.generatePublic(new X509EncodedKeySpec(oldFullParams));\n\n if (!Arrays.areEqual(oldFullParams, k.getEncoded()))\n {\n fail(\"old full public key re-encode failed\");\n }\n }", "label_name": "CWE-310", "label": "CWE-310"} {"code": " setImmediate(() => {\n if (!this.pendingPublishRequestCount) {\n return;\n }\n const starving_subscription = this._find_starving_subscription();\n if (starving_subscription) {\n doDebug && debugLog(chalk.bgWhite.red(\"feeding most late subscription subscriptionId = \"), starving_subscription.id);\n starving_subscription.process_subscription();\n }\n });", "label_name": "Base", "label": 1} {"code": "\tpublic static Path visit(File file, String filename, FileVisitor visitor) \n\tthrows IOException, IllegalArgumentException {\n\t\tif(!StringHelper.containsNonWhitespace(filename)) {\n\t\t\tfilename = file.getName();\n\t\t}\n\t\t\n\t\tPath fPath = null;\n\t\tif(file.isDirectory()) {\n\t\t\tfPath = file.toPath();\n\t\t} else if(filename != null && filename.toLowerCase().endsWith(\".zip\")) {\n\t\t\ttry {\n\t\t\t\tfPath = FileSystems.newFileSystem(file.toPath(), null).getPath(\"/\");\n\t\t\t} catch (ProviderNotFoundException | ServiceConfigurationError e) {\n\t\t\t\tthrow new IOException(\"Unreadable file with .zip extension: \" + file, e);\n\t\t\t}\n\t\t} else {\n\t\t\tfPath = file.toPath();\n\t\t}\n\t\tif(fPath != null) {\n\t\t Files.walkFileTree(fPath, visitor);\n\t\t}\n\t\treturn fPath;\n\t}", "label_name": "Base", "label": 1} {"code": "\tpublic int decryptWithAd(byte[] ad, byte[] ciphertext,\n\t\t\tint ciphertextOffset, byte[] plaintext, int plaintextOffset,\n\t\t\tint length) throws ShortBufferException, BadPaddingException {\n\t\tint space;\n\t\tif (ciphertextOffset > ciphertext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = ciphertext.length - ciphertextOffset;\n\t\tif (length > space)\n\t\t\tthrow new ShortBufferException();\n\t\tif (plaintextOffset > plaintext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = plaintext.length - plaintextOffset;\n\t\tif (!haskey) {\n\t\t\t// The key is not set yet - return the ciphertext as-is.\n\t\t\tif (length > space)\n\t\t\t\tthrow new ShortBufferException();\n\t\t\tif (plaintext != ciphertext || plaintextOffset != ciphertextOffset)\n\t\t\t\tSystem.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);\n\t\t\treturn length;\n\t\t}\n\t\tif (length < 16)\n\t\t\tNoise.throwBadTagException();\n\t\tint dataLen = length - 16;\n\t\tif (dataLen > space)\n\t\t\tthrow new ShortBufferException();\n\t\tsetup(ad);\n\t\tghash.update(ciphertext, ciphertextOffset, dataLen);\n\t\tghash.pad(ad != null ? ad.length : 0, dataLen);\n\t\tghash.finish(enciv, 0, 16);\n\t\tint temp = 0;\n\t\tfor (int index = 0; index < 16; ++index)\n\t\t\ttemp |= (hashKey[index] ^ enciv[index] ^ ciphertext[ciphertextOffset + dataLen + index]);\n\t\tif ((temp & 0xFF) != 0)\n\t\t\tNoise.throwBadTagException();\n\t\tencryptCTR(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen);\n\t\treturn dataLen;\n\t}", "label_name": "Base", "label": 1} {"code": "\tprivate Document parseXml(String xmlContent) {\n\t\ttry {\n\t\t\tDocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();\n\t\t\tDocument document = builder.parse(new InputSource(new StringReader(xmlContent)));\n\n\t\t\tdocument.getDocumentElement().normalize();\n\n\t\t\treturn document;\n\t\t} catch (Exception e) {\n\t\t\tthrow new JadxRuntimeException(\"Can not parse xml content\", e);\n\t\t}\n\t}", "label_name": "Base", "label": 1} {"code": " public void testPullCount() throws IOException {\n initializeSsl();\n String url = RepoUtils.getRemoteRepoURL() + \"/modules/info/\" + orgName + \"/\" + moduleName + \"/*/\";\n HttpURLConnection conn = createHttpUrlConnection(convertToUrl(url), \"\", 0, \"\", \"\");\n conn.setInstanceFollowRedirects(false);\n setRequestMethod(conn, Utils.RequestMethod.GET);\n\n int statusCode = conn.getResponseCode();\n if (statusCode == 200) {\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),\n Charset.defaultCharset()))) {\n StringBuilder result = new StringBuilder();\n String line;\n while ((line = reader.readLine()) != null) {\n result.append(line);\n }\n Object payload = JSONParser.parse(result.toString());\n if (payload instanceof MapValue) {\n long pullCount = ((MapValue) payload).getIntValue(\"totalPullCount\");\n Assert.assertEquals(pullCount, totalPullCount);\n } else {\n Assert.fail(\"error: invalid response received\");\n }\n }\n } else {\n Assert.fail(\"error: could not connect to remote repository to find the latest version of module\");\n }\n }", "label_name": "Base", "label": 1} -{"code": " private BigInteger validate(BigInteger y, DHParameters dhParams)\n {\n if (dhParams.getQ() != null)\n {\n if (BigInteger.ONE.equals(y.modPow(dhParams.getQ(), dhParams.getP())))\n {\n return y;\n }\n\n throw new IllegalArgumentException(\"Y value does not appear to be in correct group\");\n }\n else\n {\n return y; // we can't validate without Q.\n }\n }", "label_name": "CWE-320", "label": "CWE-320"} {"code": " public boolean deleteSynchronously(String mediaPackageId) throws SearchException, UnauthorizedException,\n NotFoundException {\n SearchResult result;\n try {\n result = solrRequester.getForWrite(new SearchQuery().withId(mediaPackageId));\n if (result.getItems().length == 0) {\n logger.warn(\n \"Can not delete mediapackage {}, which is not available for the current user to delete from the search index.\",\n mediaPackageId);\n return false;\n }\n logger.info(\"Removing mediapackage {} from search index\", mediaPackageId);\n\n Date now = new Date();\n try {\n persistence.deleteMediaPackage(mediaPackageId, now);\n logger.info(\"Removed mediapackage {} from search persistence\", mediaPackageId);\n } catch (NotFoundException e) {\n // even if mp not found in persistence, it might still exist in search index.\n logger.info(\"Could not find mediapackage with id {} in persistence, but will try remove it from index, anyway.\",\n mediaPackageId);\n } catch (SearchServiceDatabaseException e) {\n logger.error(\"Could not delete media package with id {} from persistence storage\", mediaPackageId);\n throw new SearchException(e);\n }\n\n return indexManager.delete(mediaPackageId, now);\n } catch (SolrServerException e) {\n logger.info(\"Could not delete media package with id {} from search index\", mediaPackageId);\n throw new SearchException(e);\n }\n }", "label_name": "Class", "label": 2} {"code": "\tpublic static boolean copyResource(File file, String filename, File targetDirectory, PathMatcher filter) {\n\t\ttry {\n\t\t\tPath path = getResource(file, filename);\n\t\t\tif(path == null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tPath destDir = targetDirectory.toPath();\n\t\t\tFiles.walkFileTree(path, new CopyVisitor(path, destDir, filter));\n\t\t\tPathUtils.closeSubsequentFS(path);\n\t\t\treturn true;\n\t\t} catch (IOException e) {\n\t\t\tlog.error(\"\", e);\n\t\t\treturn false;\n\t\t}\n\t}", "label_name": "Base", "label": 1} {"code": " public void setupRoutes() {\n path(controllerBasePath(), () -> {\n before(\"\", mimeType, this::setContentType);\n\n\n // change the line below to enable appropriate security\n before(\"\", mimeType, this.apiAuthenticationHelper::checkAdminUserAnd403);\n\n get(\"\", mimeType, this::show);\n\n post(\"\", mimeType, this::createOrUpdate);\n put(\"\", mimeType, this::createOrUpdate);\n\n delete(\"\", mimeType, this::deleteBackupConfig);\n });\n }", "label_name": "Compound", "label": 4} @@ -1516,7 +1467,6 @@ {"code": "\tprivate static void checkCEKLength(final SecretKey cek, final EncryptionMethod enc)\n\t\tthrows KeyLengthException {\n\n\t\tif (enc.cekBitLength() != ByteUtils.bitLength(cek.getEncoded())) {\n\t\t\tthrow new KeyLengthException(\"The Content Encryption Key (CEK) length for \" + enc + \" must be \" + enc.cekBitLength() + \" bits\");\n\t\t}\n\t}", "label_name": "Class", "label": 2} {"code": " public void spliceToFile() throws Throwable {\n EventLoopGroup group = new EpollEventLoopGroup(1);\n File file = File.createTempFile(\"netty-splice\", null);\n file.deleteOnExit();\n\n SpliceHandler sh = new SpliceHandler(file);\n ServerBootstrap bs = new ServerBootstrap();\n bs.channel(EpollServerSocketChannel.class);\n bs.group(group).childHandler(sh);\n bs.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);\n Channel sc = bs.bind(NetUtil.LOCALHOST, 0).syncUninterruptibly().channel();\n\n Bootstrap cb = new Bootstrap();\n cb.group(group);\n cb.channel(EpollSocketChannel.class);\n cb.handler(new ChannelInboundHandlerAdapter());\n Channel cc = cb.connect(sc.localAddress()).syncUninterruptibly().channel();\n\n for (int i = 0; i < data.length;) {\n int length = Math.min(random.nextInt(1024 * 64), data.length - i);\n ByteBuf buf = Unpooled.wrappedBuffer(data, i, length);\n cc.writeAndFlush(buf);\n i += length;\n }\n\n while (sh.future2 == null || !sh.future2.isDone() || !sh.future.isDone()) {\n if (sh.exception.get() != null) {\n break;\n }\n try {\n Thread.sleep(50);\n } catch (InterruptedException e) {\n // Ignore.\n }\n }\n\n sc.close().sync();\n cc.close().sync();\n\n if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {\n throw sh.exception.get();\n }\n\n byte[] written = new byte[data.length];\n FileInputStream in = new FileInputStream(file);\n\n try {\n Assert.assertEquals(written.length, in.read(written));\n Assert.assertArrayEquals(data, written);\n } finally {\n in.close();\n group.shutdownGracefully();\n }\n }", "label_name": "Base", "label": 1} {"code": "\tpublic int decryptWithAd(byte[] ad, byte[] ciphertext,\n\t\t\tint ciphertextOffset, byte[] plaintext, int plaintextOffset,\n\t\t\tint length) throws ShortBufferException, BadPaddingException {\n\t\tint space;\n\t\tif (ciphertextOffset > ciphertext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = ciphertext.length - ciphertextOffset;\n\t\tif (length > space)\n\t\t\tthrow new ShortBufferException();\n\t\tif (plaintextOffset > plaintext.length)\n\t\t\tspace = 0;\n\t\telse\n\t\t\tspace = plaintext.length - plaintextOffset;\n\t\tif (keySpec == null) {\n\t\t\t// The key is not set yet - return the ciphertext as-is.\n\t\t\tif (length > space)\n\t\t\t\tthrow new ShortBufferException();\n\t\t\tif (plaintext != ciphertext || plaintextOffset != ciphertextOffset)\n\t\t\t\tSystem.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);\n\t\t\treturn length;\n\t\t}\n\t\tif (length < 16)\n\t\t\tNoise.throwBadTagException();\n\t\tint dataLen = length - 16;\n\t\tif (dataLen > space)\n\t\t\tthrow new ShortBufferException();\n\t\ttry {\n\t\t\tsetup(ad);\n\t\t} catch (InvalidKeyException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t} catch (InvalidAlgorithmParameterException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t}\n\t\tghash.update(ciphertext, ciphertextOffset, dataLen);\n\t\tghash.pad(ad != null ? ad.length : 0, dataLen);\n\t\tghash.finish(iv, 0, 16);\n\t\tint temp = 0;\n\t\tfor (int index = 0; index < 16; ++index)\n\t\t\ttemp |= (hashKey[index] ^ iv[index] ^ ciphertext[ciphertextOffset + dataLen + index]);\n\t\tif ((temp & 0xFF) != 0)\n\t\t\tNoise.throwBadTagException();\n\t\ttry {\n\t\t\tint result = cipher.update(ciphertext, ciphertextOffset, dataLen, plaintext, plaintextOffset);\n\t\t\tcipher.doFinal(plaintext, plaintextOffset + result);\n\t\t} catch (IllegalBlockSizeException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t} catch (BadPaddingException e) {\n\t\t\t// Shouldn't happen.\n\t\t\tthrow new IllegalStateException(e);\n\t\t}\n\t\treturn dataLen;\n\t}", "label_name": "Base", "label": 1} -{"code": "void bn_mul_comba4(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b)\n\t{\n#ifdef BN_LLONG\n\tBN_ULLONG t;\n#else\n\tBN_ULONG bl,bh;\n#endif\n\tBN_ULONG t1,t2;\n\tBN_ULONG c1,c2,c3;\n\n\tc1=0;\n\tc2=0;\n\tc3=0;\n\tmul_add_c(a[0],b[0],c1,c2,c3);\n\tr[0]=c1;\n\tc1=0;\n\tmul_add_c(a[0],b[1],c2,c3,c1);\n\tmul_add_c(a[1],b[0],c2,c3,c1);\n\tr[1]=c2;\n\tc2=0;\n\tmul_add_c(a[2],b[0],c3,c1,c2);\n\tmul_add_c(a[1],b[1],c3,c1,c2);\n\tmul_add_c(a[0],b[2],c3,c1,c2);\n\tr[2]=c3;\n\tc3=0;\n\tmul_add_c(a[0],b[3],c1,c2,c3);\n\tmul_add_c(a[1],b[2],c1,c2,c3);\n\tmul_add_c(a[2],b[1],c1,c2,c3);\n\tmul_add_c(a[3],b[0],c1,c2,c3);\n\tr[3]=c1;\n\tc1=0;\n\tmul_add_c(a[3],b[1],c2,c3,c1);\n\tmul_add_c(a[2],b[2],c2,c3,c1);\n\tmul_add_c(a[1],b[3],c2,c3,c1);\n\tr[4]=c2;\n\tc2=0;\n\tmul_add_c(a[2],b[3],c3,c1,c2);\n\tmul_add_c(a[3],b[2],c3,c1,c2);\n\tr[5]=c3;\n\tc3=0;\n\tmul_add_c(a[3],b[3],c1,c2,c3);\n\tr[6]=c1;\n\tr[7]=c2;\n\t}", "label_name": "CWE-310", "label": "CWE-310"} {"code": "\tchar const* parse_int(char const* start, char const* end, char delimiter, boost::int64_t& val)\n\t{\n\t\twhile (start < end && *start != delimiter)\n\t\t{\n\t\t\tif (!is_digit(*start)) { return 0; }\n\t\t\tval *= 10;\n\t\t\tval += *start - '0';\n\t\t\t++start;\n\t\t}\n\t\treturn start;\n\t}", "label_name": "Class", "label": 2} {"code": "RemoteDevicePropertiesWidget::RemoteDevicePropertiesWidget(QWidget *parent)\n : QWidget(parent)\n , modified(false)\n , saveable(false)\n{\n setupUi(this);\n if (qobject_cast(parent)) {\n verticalLayout->setMargin(4);\n }\n type->addItem(tr(\"Samba Share\"), (int)Type_Samba);\n type->addItem(tr(\"Samba Share (Auto-discover host and port)\"), (int)Type_SambaAvahi);\n type->addItem(tr(\"Secure Shell (sshfs)\"), (int)Type_SshFs);\n type->addItem(tr(\"Locally Mounted Folder\"), (int)Type_File);\n}", "label_name": "Base", "label": 1} {"code": "\t\tDeleteRunner(ReferenceHandle& that, Local key_handle) :\n\t\t\t\tkey{ExternalCopy::CopyIfPrimitive(key_handle)},\n\t\t\t\tcontext{that.context},\n\t\t\t\treference{that.reference} {\n\t\t\tthat.CheckDisposed();\n\t\t\tif (!key) {\n\t\t\t\tthrow RuntimeTypeError(\"Invalid `key`\");\n\t\t\t}\n\t\t}", "label_name": "Class", "label": 2} @@ -1621,7 +1571,6 @@ {"code": "bool logToUSDT(const Array& bt) {\n std::lock_guard lock(usdt_mutex);\n\n memset(&bt_slab, 0, sizeof(bt_slab));\n\n int i = 0;\n IterateVNoInc(\n bt.get(),\n [&](TypedValue tv) -> bool {\n\n if (i >= strobelight::kMaxStackframes) {\n return true;\n }\n\n assertx(isArrayLikeType(type(tv)));\n ArrayData* bt_frame = val(tv).parr;\n strobelight::backtrace_frame_t* frame = &bt_slab.frames[i];\n\n auto const line = bt_frame->get(s_line.get());\n if (line.is_init()) {\n assertx(isIntType(type(line)));\n frame->line = val(line).num;\n }\n\n auto const file_name = bt_frame->get(s_file.get());\n if (file_name.is_init()) {\n assertx(isStringType(type(file_name)));\n strncpy(frame->file_name,\n val(file_name).pstr->data(),\n std::min(val(file_name).pstr->size(), strobelight::kFileNameMax));\n frame->file_name[strobelight::kFileNameMax - 1] = '\\0';\n }\n\n auto const class_name = bt_frame->get(s_class.get());\n if (class_name.is_init()) {\n assertx(isStringType(type(class_name)));\n strncpy(frame->class_name,\n val(class_name).pstr->data(),\n std::min(val(class_name).pstr->size(), strobelight::kClassNameMax));\n frame->class_name[strobelight::kClassNameMax - 1] = '\\0';\n }\n\n auto const function_name = bt_frame->get(s_function.get());\n if (function_name.is_init()) {\n assertx(isStringType(type(function_name)));\n strncpy(frame->function,\n val(function_name).pstr->data(),\n std::min(val(function_name).pstr->size(),\n strobelight::kFunctionMax));\n frame->function[strobelight::kFunctionMax - 1] = '\\0';\n }\n\n i++;\n return false;\n }\n );\n bt_slab.len = i;\n\n // Allow BPF to read the now-formatted stacktrace\n FOLLY_SDT_WITH_SEMAPHORE(hhvm, hhvm_stack, &bt_slab);\n\n return true;\n}", "label_name": "Base", "label": 1} {"code": "MONGO_EXPORT bson_type bson_iterator_next( bson_iterator *i ) {\n int ds;\n\n if ( i->first ) {\n i->first = 0;\n return ( bson_type )( *i->cur );\n }\n\n switch ( bson_iterator_type( i ) ) {\n case BSON_EOO:\n return BSON_EOO; /* don't advance */\n case BSON_UNDEFINED:\n case BSON_NULL:\n ds = 0;\n break;\n case BSON_BOOL:\n ds = 1;\n break;\n case BSON_INT:\n ds = 4;\n break;\n case BSON_LONG:\n case BSON_DOUBLE:\n case BSON_TIMESTAMP:\n case BSON_DATE:\n ds = 8;\n break;\n case BSON_OID:\n ds = 12;\n break;\n case BSON_STRING:\n case BSON_SYMBOL:\n case BSON_CODE:\n ds = 4 + bson_iterator_int_raw( i );\n break;\n case BSON_BINDATA:\n ds = 5 + bson_iterator_int_raw( i );\n break;\n case BSON_OBJECT:\n case BSON_ARRAY:\n case BSON_CODEWSCOPE:\n ds = bson_iterator_int_raw( i );\n break;\n case BSON_DBREF:\n ds = 4+12 + bson_iterator_int_raw( i );\n break;\n case BSON_REGEX: {\n const char *s = bson_iterator_value( i );\n const char *p = s;\n p += strlen( p )+1;\n p += strlen( p )+1;\n ds = p-s;\n break;\n }\n\n default: {\n char msg[] = \"unknown type: 000000000000\";\n bson_numstr( msg+14, ( unsigned )( i->cur[0] ) );\n bson_fatal_msg( 0, msg );\n return 0;\n }\n }\n\n i->cur += 1 + strlen( i->cur + 1 ) + 1 + ds;\n\n return ( bson_type )( *i->cur );\n}", "label_name": "Base", "label": 1} {"code": " explicit DataFormatDimMapOp(OpKernelConstruction* context)\n : OpKernel(context) {\n string src_format;\n OP_REQUIRES_OK(context, context->GetAttr(\"src_format\", &src_format));\n string dst_format;\n OP_REQUIRES_OK(context, context->GetAttr(\"dst_format\", &dst_format));\n OP_REQUIRES(context, src_format.size() == 4 || src_format.size() == 5,\n errors::InvalidArgument(strings::StrCat(\n \"Source format must of length 4 or 5, received \"\n \"src_format = \",\n src_format)));\n OP_REQUIRES(\n context, dst_format.size() == 4 || dst_format.size() == 5,\n errors::InvalidArgument(strings::StrCat(\n \"Destination format must of length 4 or 5, received dst_format = \",\n dst_format)));\n dst_idx_ = Tensor(DT_INT32, {static_cast(src_format.size())});\n for (int i = 0; i < src_format.size(); ++i) {\n for (int j = 0; j < dst_format.size(); ++j) {\n if (dst_format[j] == src_format[i]) {\n dst_idx_.vec()(i) = j;\n break;\n }\n }\n }\n }", "label_name": "Base", "label": 1} -{"code": "void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg)\n{\n Q_UNUSED(bufferInfo);\n if (!msg.contains(' '))\n return;\n\n QString target = msg.section(' ', 0, 0);\n QByteArray encMsg = userEncode(target, msg.section(' ', 1));\n\n#ifdef HAVE_QCA2\n putPrivmsg(serverEncode(target), encMsg, network()->cipher(target));\n#else\n putPrivmsg(serverEncode(target), encMsg);\n#endif\n}", "label_name": "CWE-399", "label": "CWE-399"} {"code": "DSA_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/,\n const std::string& params,\n const std::string& provider) const\n {\n if(provider == \"base\" || provider.empty())\n return std::unique_ptr(new DSA_Signature_Operation(*this, params));\n throw Provider_Not_Found(algo_name(), provider);\n }", "label_name": "Class", "label": 2} {"code": "void QuickOpen::Load(uint64 BlockPos)\n{\n if (!Loaded) // If loading the first time, perform additional intialization.\n {\n SeekPos=Arc->Tell();\n UnsyncSeekPos=false;\n\n SaveFilePos SavePos(*Arc);\n Arc->Seek(BlockPos,SEEK_SET);\n if (Arc->ReadHeader()==0 || Arc->GetHeaderType()!=HEAD_SERVICE ||\n !Arc->SubHead.CmpName(SUBHEAD_TYPE_QOPEN))\n return;\n QLHeaderPos=Arc->CurBlockPos;\n RawDataStart=Arc->Tell();\n RawDataSize=Arc->SubHead.UnpSize;\n\n Loaded=true; // Set only after all file processing calls like Tell, Seek, ReadHeader.\n }\n\n if (Arc->SubHead.Encrypted)\n {\n RAROptions *Cmd=Arc->GetRAROptions();\n#ifndef RAR_NOCRYPT\n if (Cmd->Password.IsSet())\n Crypt.SetCryptKeys(false,CRYPT_RAR50,&Cmd->Password,Arc->SubHead.Salt,\n Arc->SubHead.InitV,Arc->SubHead.Lg2Count,\n Arc->SubHead.HashKey,Arc->SubHead.PswCheck);\n else\n#endif\n return;\n }\n\n RawDataPos=0;\n ReadBufSize=0;\n ReadBufPos=0;\n LastReadHeader.Reset();\n LastReadHeaderPos=0;\n\n ReadBuffer();\n}", "label_name": "Base", "label": 1} {"code": "HexOutStream::overrun(int itemSize, int nItems) {\n if (itemSize > bufSize)\n throw Exception(\"HexOutStream overrun: max itemSize exceeded\");\n\n writeBuffer();\n\n if (itemSize * nItems > end - ptr)\n nItems = (end - ptr) / itemSize;\n\n return nItems;\n}", "label_name": "Base", "label": 1} @@ -1663,7 +1612,6 @@ {"code": " def self.applied_paid_hlds(user_id, start_date, end_date)\n\n SqlHelper.validate_token([user_id, start_date, end_date])\n\n sql = \"SELECT COUNT(*) FROM timecards WHERE user_id = #{user_id} AND date >= '#{start_date}' AND date <= '#{end_date}'\"\n\n sum = 0.0\n self.workcodes.each do |key, params|\n paidhld_rate = params[WKCODE_PARAM_PAIDHLD]\n if paidhld_rate > 0.0\n num = Timecard.count_by_sql(sql + \" AND workcode='#{key}'\")\n sum += num * paidhld_rate\n end\n end\n\n return sum\n end", "label_name": "Base", "label": 1} {"code": " def first\n session.simple_query(operation)\n end", "label_name": "Class", "label": 2} {"code": " def sanitize_key(key)\n case key\n when Symbol then \"--#{key.to_s.tr(\"_\", \"-\")}\"\n else key\n end", "label_name": "Base", "label": 1} -{"code": " def tok(s)\n case s[0]\n when ?{ then ['{', s[0,1], s[0,1]]\n when ?} then ['}', s[0,1], s[0,1]]\n when ?: then [':', s[0,1], s[0,1]]\n when ?, then [',', s[0,1], s[0,1]]\n when ?[ then ['[', s[0,1], s[0,1]]\n when ?] then [']', s[0,1], s[0,1]]\n when ?n then nulltok(s)\n when ?t then truetok(s)\n when ?f then falsetok(s)\n when ?\" then strtok(s)\n when Spc, ?\\t, ?\\n, ?\\r then [:space, s[0,1], s[0,1]]\n else\n numtok(s)\n end\n end\n\n\n def nulltok(s); s[0,4] == 'null' ? [:val, 'null', nil] : [] end\n def truetok(s); s[0,4] == 'true' ? [:val, 'true', true] : [] end\n def falsetok(s); s[0,5] == 'false' ? [:val, 'false', false] : [] end\n\n\n def numtok(s)\n m = /-?([1-9][0-9]+|[0-9])([.][0-9]+)?([eE][+-]?[0-9]+)?/.match(s)\n if m && m.begin(0) == 0\n if !m[2] && !m[3]\n [:val, m[0], Integer(m[0])]\n elsif m[2]\n [:val, m[0], Float(m[0])]\n else\n [:val, m[0], Integer(m[1])*(10**m[3][1..-1].to_i(10))]\n end\n else\n []\n end\n end\n\n\n def strtok(s)\n m = /\"([^\"\\\\]|\\\\[\"\\/\\\\bfnrt]|\\\\u[0-9a-fA-F]{4})*\"/.match(s)\n if ! m\n raise Error, \"invalid string literal at #{abbrev(s)}\"\n end\n [:str, m[0], unquote(m[0])]\n end", "label_name": "CWE-399", "label": "CWE-399"} {"code": " def crop_command\n target = @attachment.instance\n\n if target.cropping?(@attachment.name)\n w = target.send :\"#{@attachment.name}_crop_w\"\n h = target.send :\"#{@attachment.name}_crop_h\"\n x = target.send :\"#{@attachment.name}_crop_x\"\n y = target.send :\"#{@attachment.name}_crop_y\"\n [\"-crop\", \"#{w}x#{h}+#{x}+#{y}\"]\n end\n end", "label_name": "Class", "label": 2} {"code": " def self.prepare_rdoc root\n debug, verbose = false, false\n\n prepare_script = Pathname.new(Rails.root) + \"script/rdoc_prepare_script.rb\"\n if prepare_script.executable?\n dirs = Environment.puppetEnvs.values.join(\":\").split(\":\").uniq.sort.join(\" \")\n puts \"Running #{prepare_script} #{dirs}\" if debug\n location = %x{#{prepare_script} #{dirs}}\n if $? == 0\n root = location.chomp\n puts \"Relocated modules to #{root}\" if verbose\n end\n else\n puts \"No executable #{prepare_script} found so using the uncopied module sources\" if verbose\n end\n root\n end\n\n def as_json(options={})\n super({:only => [:name, :id], :include => [:lookup_keys]})\n end\n\n def self.search_by_host(key, operator, value)\n conditions = \"hosts.name #{operator} '#{value_to_sql(operator, value)}'\"\n direct = Puppetclass.all(:conditions => conditions, :joins => :hosts, :select => 'puppetclasses.id').map(&:id).uniq\n hostgroup = Hostgroup.joins(:hosts).where(conditions).first\n indirect = HostgroupClass.where(:hostgroup_id => hostgroup.path_ids).pluck(:puppetclass_id).uniq\n return { :conditions => \"1=0\" } if direct.blank? && indirect.blank?\n\n puppet_classes = (direct + indirect).uniq\n { :conditions => \"puppetclasses.id IN(#{puppet_classes.join(',')})\" }\n end\n\n\n def self.value_to_sql(operator, value)\n return value if operator !~ /LIKE/i\n return value.tr_s('%*', '%') if (value ~ /%|\\*/)\n\n return \"%#{value}%\"\n end\n\nend", "label_name": "Base", "label": 1} {"code": " def to_s\n @@string_format % data\n end", "label_name": "Class", "label": 2}