prompt
stringclasses
1 value
completions
listlengths
1
63.8k
labels
listlengths
1
63.8k
source
stringclasses
1 value
other_info
stringlengths
2.06k
101k
index
int64
0
6.83k
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "##################################################\n#\n# Copyright (c) 2004-2016 OIC Group, Inc.\n#\n# This file is part of Exponent\n#\n# Exponent is free software; you can redistribute\n# it and/or modify it under the terms of the GNU\n# General Public License as published by the Free\n# Software Foundation; either version 2 of the\n# License, or (at your option) any later version.\n#\n# GPL: http://www.gnu.org/licenses/gpl.txt\n#\n##################################################", "/**\n * @subpackage Controllers\n * @package Modules\n */\n/** @define \"BASE\" \"../../../..\" */", "class usersController extends expController {\n public $basemodel_name = 'user';", " protected $add_permissions = array(", " 'toggle_extension' => 'Activate Extensions',\n 'kill_session' => 'End Sessions',\n 'boot_user' => 'Boot Users',\n 'userperms' => 'User Permissions',\n 'groupperms' => 'Group Permissions',\n 'import' => 'Import Users',\n 'export' => 'Export Users',", " );\n protected $remove_permissions = array(\n 'create',\n 'edit'", " );", " static function displayname() {\n return gt(\"User Manager\");\n }", " static function description() {\n return gt(\"This is the user management module. It allows for creating user, editing user, etc.\");\n }", " static function hasSources() {\n return false;\n }", " static function hasContent() {\n return false;\n }", " static function canImportData() {\n return true;\n }", " public function manage() {\n global $user;", " expHistory::set('manageable', $this->params);\n// $limit = empty($this->config['limit']) ? 10 : $this->config['limit'];\n// $order = empty($this->config['order']) ? 'username' : $this->config['order'];\n if ($user->is_system_user == 1) {\n// $filter = 1; //'1';\n $where = '';\n } elseif ($user->isSuperAdmin()) {\n// $filter = 2; //\"is_system_user != 1\";\n $where = \"is_system_user != 1\";\n } else {\n// $filter = 3; //\"is_admin != 1\";\n $where = \"is_admin != 1\";\n }\n $page = new expPaginator(array(\n 'model'=>'user',\n 'where'=>$where,\n// 'limit'=>$limit,\n// 'order'=>$order,\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->baseclassname,\n 'action'=>$this->params['action'],\n 'columns'=>array(\n gt('Username')=>'username',\n gt('First Name')=>'firstname',\n gt('Last Name')=>'lastname',\n gt('Is Admin')=>'is_acting_admin',\n )\n ));", " assign_to_template(array('page'=>$page));\n// assign_to_template(array(\n// 'filter' => $filter\n// ));\n }", " public function create() {\n redirect_to(array('controller' => 'users', 'action' => 'edituser'));\n// $this->edituser();\n }", " public function edituser() {\n global $user, $db;", " // set history\n expHistory::set('editable', $this->params);\n expSession::set(\"userkey\", sha1(microtime()));\n expSession::clearCurrentUserSessionCache();", " $id = !empty($this->params['id']) ? $this->params['id'] : null;", " // check to see if we should be editing. You either need to be an admin, or editing own account.\n if ($user->isAdmin() || ($user->id == $id && !$user->globalPerm('prevent_profile_change'))) {\n $u = new user($id);\n if ($u->isSuperAdmin() && $user->isActingAdmin()) { // prevent regular admin's from editing super-admins\n flash('error', gt('You do not have the proper permissions to edit this user'));\n expHistory::back();\n }\n } else {\n flash('error', gt('You do not have the proper permissions to edit this user'));\n expHistory::back();\n }\n $active_extensions = $db->selectObjects('profileextension', 'active=1', 'rank');", " //If there is no image uploaded, use the default avatar\n if (empty($u->image)) $u->image = PATH_RELATIVE . \"framework/modules/users/assets/images/avatar_not_found.jpg\";", " assign_to_template(array(\n 'edit_user' => $u,\n 'extensions' => $active_extensions,\n \"userkey\" => expSession::get(\"userkey\")\n ));", " if ($user->isAdmin()) {\n $page = new expPaginator(array(\n 'model' => 'group',\n 'where' => 1,\n 'limit' => (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10,\n 'order' => empty($this->config['order']) ? 'name' : $this->config['order'],\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'columns' => array(\n gt('Name') => 'name',\n gt('Description') => 'description',\n ),\n 'controller' => $this->baseclassname,\n 'action' => $this->params['action'],\n ));", " assign_to_template(array(\n 'groups' => $page,\n 'mygroups' => $u->getGroupMemberships(),\n ));\n }\n }", " public function update() {\n global $user, $db;", " // get the id of user we are editing, if there is one\n $id = !empty($this->params['id']) ? $this->params['id'] : null;\n if ((($user->id == $id) || $user->isAdmin()) && $this->params['userkey'] != expSession::get(\"userkey\")) expHistory::back();", " // make sure this user should be updating user accounts\n if (!$user->isLoggedIn() && SITE_ALLOW_REGISTRATION == 0) {\n flash('error', gt('This site does not allow user registrations'));\n expHistory::back();\n } elseif (!$user->isAdmin() && ($user->isLoggedIn() && $user->id != $id)) {\n flash('error', gt('You do not have permission to edit this user account'));\n expHistory::back();\n }\n", " // if this is a new user account we need to check the password. ", " // the password fields wont come thru on an edit. Otherwise we will\n // just update the existing account.\n if (!empty($id)) {\n $u = new user($id);\n $u->update($this->params);\n if ($user->isAdmin() && $user->id != $id) {\n flash('message', gt('Account information for') . ' ' . $u->username . ' ' . gt('has been updated.'));\n } else {\n flash('message', gt('Thank you') . ' ' . $u->firstname . '. ' . gt('Your account information has been updated.'));\n }\n if ($user->id == $id) {\n $_SESSION[SYS_SESSION_KEY]['user'] = $u;\n $user = $u;\n }\n } else {\n $u = new user($this->params);\n $ret = $u->setPassword($this->params['pass1'], $this->params['pass2']);\n if ($ret != true) expValidator::failAndReturnToForm($ret, $this->params);\n $u->save();\n if ($user->isAdmin()) {\n flash('message', gt('Created new user account for') . ' ' . $u->username);\n } else {\n user::login($u->username, $this->params['pass1']);\n flash('message', gt('Thank you') . ' ' . $u->firstname . '. ' . gt('Your new account has been created.'));\n }\n }", " // update the user profiles\n if (!empty($u->id)) {\n $this->params['user_id'] = $u->id;\n // get the active profile extensions and save them out\n $active_extensions = $db->selectObjects('profileextension', 'active=1');\n foreach ($active_extensions as $pe) {\n if (is_file(BASE . $pe->classfile)) {\n include_once(BASE . $pe->classfile);\n $ext = new $pe->classname();\n $db->delete($ext->tablename, 'user_id=' . $u->id);\n $ext->update($this->params);\n }\n }\n }", " // update group membership assignment\n if (!empty($this->params['member'])) {\n $old_groups = $db->selectObjects('groupmembership', 'member_id=' . $u->id);\n// $db->delete('groupmembership', 'member_id=' . $u->id); // start from scratch\n $memb = new stdClass();\n $memb->member_id = $u->id;\n foreach ($this->params['member'] as $grp) {\n $memb->group_id = $grp;\n $memb->is_admin = false;\n foreach ($old_groups as $oldgroup) {\n if ($oldgroup->group_id == $grp) {\n if ($oldgroup->is_admin) $memb->is_admin = true; // retain group admin setting\n }\n }\n $db->insertObject($memb, 'groupmembership');\n }\n if ($u->id == $user->id) expSession::triggerRefresh();\n }\n", " // if this is a new account then we will check to see if we need to send ", " // a welcome message or admin notification of new accounts.\n if (empty($id)) {\n // Calculate Group Memberships for newly created users. Any groups that\n // are marked as 'inclusive' automatically pick up new users. This is the part\n // of the code that goes out, finds those groups, and makes the new user a member\n // of them.\n $memb = new stdClass();\n $memb->member_id = $u->id;\n // Also need to process the groupcodes, for promotional signup\n// $code_where = '';\n// if (isset($this->params['groupcode']) && $this->params['groupcode'] != '') {\n// $code_where = \" OR code='\" . $this->params['groupcode'] . \"'\";\n// }\n // Add to default plus any groupcode groups\n// foreach ($db->selectObjects('group', 'inclusive=1' . $code_where) as $g) {\n foreach ($db->selectObjects('group', 'inclusive=1') as $g) {\n $memb->group_id = $g->id;\n $db->insertObject($memb, 'groupmembership');\n }", " // if we added the user to any group than we need to reload their permissions\n// expPermissions::load($u); //FIXME why are we doing this? this loads the edited user perms over the current user???", " //signup email stuff\n if (USER_REGISTRATION_SEND_WELCOME && !empty($u->email)) {\n $msg = $u->firstname . \", \\n\\n\";\n $msg .= sprintf(USER_REGISTRATION_WELCOME_MSG, $u->firstname, $u->lastname, $u->username);", " $mail = new expMail();\n $mail->quickSend(array(\n 'text_message' => $msg,\n 'to' => array(trim($u->email) => trim(user::getUserAttribution($u->id))),\n 'from' => array(trim(SMTP_FROMADDRESS) => trim(ORGANIZATION_NAME)),\n 'subject' => USER_REGISTRATION_WELCOME_SUBJECT,\n ));", " flash('message', gt('A welcome email has been sent to') . ' ' . $u->email);\n }", " // send and email notification to the admin of the site.\n if (USER_REGISTRATION_SEND_NOTIF && !$user->isAdmin()) {\n $msg = gt(\"When\") . \": \" . date(\"F j, Y, g:i a\") . \"\\n\\n\";\n $msg .= gt(\"Their name is\") . \": \" . $u->firstname . \" \" . $u->lastname . \"\\n\\n\";", " $mail = new expMail();\n $mail->quickSend(array(\n 'text_message' => $msg,\n 'to' => trim(USER_REGISTRATION_ADMIN_EMAIL),\n 'from' => array(trim(SMTP_FROMADDRESS) => trim(ORGANIZATION_NAME)),\n 'subject' => USER_REGISTRATION_NOTIF_SUBJECT,\n ));\n }\n }", " // we need to reload our updated profile if we just edited our own account\n if ($id == $user->id) {\n $user->getUserProfile();\n// expPermissions::load($user); // not sure this is necessary since we can't add groups here\n }", " expHistory::back();\n }", " public function delete() {\n global $user, $db;\n if (!$user->isAdmin()) {\n flash('error', gt('You do not have permission to delete user accounts'));\n expHistory::back();\n }", " if (empty($this->params['id'])) {\n flash('error', gt('No user selected.'));\n expHistory::back();\n }", " // remove group memeberships\n $db->delete('groupmembership', 'member_id=' . $this->params['id']);", " // remove user permissions\n $db->delete('userpermission', 'uid=' . $this->params['id']);", " //remove user profiles\n $active_extensions = $db->selectObjects('profileextension', 'active=1');\n foreach ($active_extensions as $pe) {\n if (is_file(BASE . $pe->classfile)) {\n include_once(BASE . $pe->classfile);\n $ext = new $pe->classname();\n $db->delete($ext->table, 'user_id=' . $this->params['id']);\n }\n }", " // remove user address\n $address = new address();\n $db->delete($address->table, 'user_id=' . $this->params['id']);", " parent::delete();\n }", " public function manage_sessions() {\n// global $db, $user;\n global $db;", " expHistory::set('manageable', $this->params);", " //cleans up any old sessions\n if (SESSION_TIMEOUT_ENABLE == true) {\n $db->delete('sessionticket', 'last_active < ' . (time() - SESSION_TIMEOUT));\n// } else {\n// $db->delete('sessionticket', '1');\n }", " if (isset($this->params['id']) && $this->params['id'] == 0) {\n $sessions = $db->selectObjects('sessionticket', \"uid<>0\");\n $filtered = 1;\n } else {\n $sessions = $db->selectObjects('sessionticket');\n $filtered = 0;\n }", "//\t $sessions = $db->selectObjects('sessionticket');\n for ($i = 0, $iMax = count($sessions); $i < $iMax; $i++) {\n $sessions[$i]->user = new user($sessions[$i]->uid);\n if ($sessions[$i]->uid == 0) {\n $sessions[$i]->user->id = 0;\n }\n $sessions[$i]->duration = expDateTime::duration($sessions[$i]->last_active, $sessions[$i]->start_time);\n }", " assign_to_template(array(\n 'sessions' => $sessions,\n 'filter' => $filtered\n ));\n }", " public function kill_session() {\n global $user, $db;\n $ticket = $db->selectObject('sessionticket', \"ticket='\" . preg_replace('/[^A-Za-z0-9.]/', '', $this->params['ticket']) . \"'\");\n if ($ticket) {\n $u = new user($ticket->uid);\n if ($user->isSuperAdmin() || ($user->isActingAdmin() && !$u->isAdmin())) {\n // We can only kick the user if they are A) not an acting admin, or\n // B) The current user is a super user and the kicked user is not.\n $db->delete('sessionticket', \"ticket='\" . $ticket->ticket . \"'\");\n }\n }\n expHistory::back();\n }", " public function boot_user() {\n global $user, $db;\n if (!empty($this->params['id'])) {\n $u = new user($this->params['id']);\n if ($user->isSuperAdmin() || ($user->isActingAdmin() && !$u->isAdmin())) {\n // We can only kick the user if they are A) not an acting admin, or\n // B) The current user is a super user and the kicked user is not.\n $db->delete('sessionticket', 'uid=' . $u->id);\n }\n }\n expHistory::back();\n }", " /**\n  * This function scans two directories and searches for php files to add to the extensions database.\n * If you have added new extensions since the last time you have visited the page, it will add them to the database\n * in effect enabling your new extension to be tacked onto users profiles. You then have to enable it in the menu, but at least\n * now it is in the system and when the user goes to edit his profile, it will check for extensions and this one will be in!\n *\n  * @global string This function uses the global $db save information through the Exponenet database connection.\n  */\n public function manage_extensions() {\n global $db;", " // set history\n expHistory::set('manageable', $this->params);", " // Lets find all the user profiles availabe and then see if they are\n // in the database yet. If not we will add them.\n $ext_dirs = array(\n 'framework/modules/users/extensions',\n 'themes/' . DISPLAY_THEME . '/modules/users/extensions'\n );\n foreach ($ext_dirs as $dir) {\n if (is_readable(BASE . $dir)) {\n $dh = opendir(BASE . $dir);\n while (($file = readdir($dh)) !== false) {\n if (is_file(BASE . \"$dir/$file\") && is_readable(BASE . \"$dir/$file\") && substr($file, 0, 1) != '_' && substr($file, 0, 1) != '.') {\n include_once(BASE . \"$dir/$file\");\n $classname = substr($file, 0, -4);\n $class = new $classname();\n $extension = $db->selectObject('profileextension', \"title='\" . $class->name() . \"'\");\n if (empty($extension->id)) {\n $pe = new profileextension();\n $pe->title = $class->name();\n $pe->body = $class->description();\n $pe->classfile = \"$dir/$file\";\n $pe->classname = $classname;\n $pe->save();\n }\n }\n }\n }\n }", " $page = new expPaginator(array(\n 'model' => 'profileextension',\n 'where' => 1,\n 'limit' => 25,\n 'order' => 'title',\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'columns' => array(\n gt('Name') => 'title',\n gt('Description') => 'body',\n gt('Active') => 'active'\n ),\n 'controller' => $this->baseclassname,\n 'action' => $this->params['action'],\n ));", " assign_to_template(array(\n 'page' => $page\n ));\n }", " public function manage_groups() {\n expHistory::set('manageable', $this->params);\n $page = new expPaginator(array(\n 'model' => 'group',\n 'where' => 1,\n// 'limit' => (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10,\n 'order' => empty($this->config['order']) ? 'name' : $this->config['order'],\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'columns' => array(\n gt('Name') => 'name',\n gt('Description') => 'description',\n gt('Type') => 'inclusive',\n ),\n 'controller' => $this->baseclassname,\n 'action' => $this->params['action'],\n ));", " foreach ($page->records as $key=>$group) {\n $page->records[$key]->members = group::getUsersInGroup($group->id);\n }", " assign_to_template(array(\n 'page' => $page,\n ));\n }", " public function reset_password() {\n expHistory::set('editable', $this->params);\n }", " public function send_new_password() {\n global $db;", " // find the user", "", " $u = user::getUserByName($this->params['username']);\n if (empty($u)) {\n $u = user::getUserByEmail($this->params['username']);\n if (!empty($u) && $u->count > 1) {\n expValidator::failAndReturnToForm(gt('That email address applies to more than one user account, please enter your username instead.'));\n }\n }\n $u = new user($u->id);", " if (!expValidator::check_antispam($this->params)) {\n expValidator::failAndReturnToForm(gt('Anti-spam verification failed. Please try again.'), $this->params);\n } elseif (empty($u->id)) {\n expValidator::failAndReturnToForm(gt('We were unable to find an account with that username/email'), $this->params);\n } elseif (empty($u->email)) {\n expValidator::failAndReturnToForm(gt('Your account does not appear to have an email address. Please contact the site administrators to reset your password'), $this->params);\n } elseif ($u->isAdmin()) {\n expValidator::failAndReturnToForm(gt('You cannot reset passwords for an administrator account.'), $this->params);\n }", " $tok = new stdClass();\n $tok->uid = $u->id;\n $tok->expires = time() + 2 * 3600;\n $tok->token = md5(time()) . uniqid('');", " $email = $template = expTemplate::get_template_for_action($this, 'email/password_reset_email', $this->loc);\n $email->assign('token', $tok);\n $email->assign('username', $u->username);\n $msg = $email->render();\n $mail = new expMail();\n $mail->quickSend(array(\n 'html_message' => $msg,\n 'to' => array(trim($u->email) => trim(user::getUserAttribution($u->id))),\n 'from' => array(trim(SMTP_FROMADDRESS) => trim(ORGANIZATION_NAME)),\n 'subject' => gt('Password Reset Requested'),\n ));", " $db->delete('passreset_token', 'uid=' . $u->id);\n $db->insertObject($tok, 'passreset_token');\n flash('message', gt('An email has been sent to you with instructions on how to finish resetting your password.') . '<br><br>' .\n gt('This new password request is only valid for 2 hours. If you have not completed the password reset process within 2 hours, the new password request will expire.'));", " expHistory::back();\n }", " public function confirm_password_reset() {\n global $db;", " $db->delete('passreset_token', 'expires < ' . time());", " $tok = $db->selectObject('passreset_token', 'uid=' . $this->params['uid'] . \" AND token='\" . preg_replace('/[^A-Za-z0-9]/', '', $this->params['token']) . \"'\");", " if ($tok == null) {\n flash('error', gt('Your password reset request has expired. Please try again.'));\n expHistory::back();\n }", " // create the password\n $newpass = '';\n for ($i = 0, $iMax = mt_rand(12, 20); $i < $iMax; $i++) {\n $num = mt_rand(48, 122);\n if (($num > 97 && $num < 122) || ($num > 65 && $num < 90) || ($num > 48 && $num < 57)) $newpass .= chr($num);\n else $i--;\n }", " // look up the user\n $u = new user($tok->uid);", " // get the email message body and render it\n $email = $template = expTemplate::get_template_for_action($this, 'email/confirm_password_email', $this->loc);\n $email->assign('newpass', $newpass);\n $email->assign('username', $u->username);\n $msg = $email->render();", " // send the new password to the user\n $mail = new expMail();\n $mail->quickSend(array(\n 'html_message' => $msg,\n 'to' => array(trim($u->email) => trim(user::getUserAttribution($u->id))),\n 'from' => array(trim(SMTP_FROMADDRESS) => trim(ORGANIZATION_NAME)),\n 'subject' => gt('The account password for') . ' ' . HOSTNAME . ' ' . gt('was reset'),\n ));", " // Save new password\n $u->update(array('password' => user::encryptPassword($newpass)));", " // cleanup the reset token\n $db->delete('passreset_token', 'uid=' . $tok->uid);", " flash('message', gt('Your password has been reset and the new password has been emailed to you.'));", " // send the user the login page.\n redirect_to(array('controller' => 'login', 'action' => 'loginredirect'));\n }", " public function change_password() {\n global $user;", " expHistory::set('editable', $this->params);\n $id = isset($this->params['id']) ? $this->params['id'] : $user->id;", " if ($user->isAdmin() || ($user->id == $id)) {\n $isuser = ($user->id == $id) ? 1 : 0;\n $u = new user($id);\n } else {\n flash('error', gt('You do not have the proper permissions to do that'));\n expHistory::back();\n }\n assign_to_template(array(\n 'u' => $u,\n 'isuser' => $isuser\n ));\n }", " public function save_change_password() {\n global $user;", " $isuser = ($this->params['uid'] == $user->id) ? 1 : 0;", " if (!$user->isAdmin() && !$isuser) {\n flash('error', gt('You do not have permissions to change this users password.'));\n expHistory::back();\n }", " if (($isuser && empty($this->params['password'])) || (!empty($this->params['password']) && $user->password != user::encryptPassword($this->params['password']))) {\n flash('error', gt('The current password you entered is not correct.'));\n expHistory::returnTo('editable');\n }\n //eDebug($user);", " $u = new user($this->params['uid']);", "\n $ret = $u->setPassword($this->params['new_password1'], $this->params['new_password2']);\n //eDebug($u, true);\n if (is_string($ret)) {\n flash('error', $ret);\n expHistory::returnTo('editable');\n } else {\n $params = array();\n $params['is_admin'] = !empty($u->is_admin);\n $params['is_acting_admin'] = !empty($u->is_acting_admin);\n $u->update($params);\n }", " if (!$isuser) {\n flash('message', gt('The password for') . ' ' . $u->username . ' ' . gt('has been changed.'));\n } else {\n $user->password = $u->password;\n flash('message', gt('Your password has been changed.'));\n }\n expHistory::back();\n }", " public function edit_userpassword() {\n expHistory::set('editable', $this->params);\n if (empty($this->params['id'])) {\n flash('error', gt('You must specify the user whose password you want to change'));\n expHistory::back();\n }", " $u = new user($this->params['id']);\n assign_to_template(array(\n 'u' => $u\n ));\n }", " public function update_userpassword() {", "", " if (empty($this->params['id'])) {\n expValidator::failAndReturnToForm(gt('You must specify the user whose password you want to change'), $this->params);\n }", " if (empty($this->params['new_password1'])) {\n expValidator::setErrorField('new_password1');\n expValidator::failAndReturnToForm(gt('You must specify a new password for this user.'), $this->params);\n }", " if (empty($this->params['new_password2'])) {\n expValidator::setErrorField('new_password2');\n expValidator::failAndReturnToForm(gt('You must confirm the password.'), $this->params);", " }", " $u = new user($this->params['id']);\n $ret = $u->setPassword($this->params['new_password1'], $this->params['new_password2']);\n if (is_string($ret)) {\n expValidator::setErrorField('new_password1');\n $this->params['new_password1'] = '';\n $this->params['new_password2'] = '';\n expValidator::failAndReturnToForm($ret, $this->params);\n } else {\n $u->save(true);\n }", " flash('message', gt('Password reset for user') . ' ' . $u->username);\n expHistory::back();\n }", " public function edit_group() {\n global $db;", " expHistory::set('editable', $this->params);\n $id = isset($this->params['id']) ? $this->params['id'] : null;\n $group = new group($id);\n $group->redirect = $db->selectValue('section', 'id', \"sef_name='\" . $group->redirect . \"'\");\n assign_to_template(array(\n 'record' => $group\n ));\n }", " public function manage_group_memberships() {\n global $db, $user;\n// expHistory::set('manageable', $this->params);", " $memb = $db->selectObject('groupmembership', 'member_id=' . $user->id . ' AND group_id=' . $this->params['id'] . ' AND is_admin=1');", " $perm_level = 0;\n if ($memb) $perm_level = 1;\n if (expPermissions::check('user_management', expCore::makeLocation('administrationmodule'))) $perm_level = 2;", " $group = $db->selectObject('group', 'id=' . $this->params['id']);\n $users = user::getAllUsers(0);", " $members = array();\n $admins = array();\n foreach ($db->selectObjects('groupmembership', 'group_id=' . $group->id) as $m) {\n $members[] = $m->member_id;\n if ($m->is_admin == 1) {\n $admins[] = $m->member_id;\n }\n }", " for ($i = 0, $iMax = count($users); $i < $iMax; $i++) {\n if (in_array($users[$i]->id, $members)) {\n $users[$i]->is_member = 1;\n } else {\n $users[$i]->is_member = 0;\n }", " if (in_array($users[$i]->id, $admins)) {\n $users[$i]->is_admin = 1;\n } else {\n $users[$i]->is_admin = 0;\n }\n }", " //$limit = empty($this->config['limit']) ? 10 : $this->config['limit'];\n $page = new expPaginator(array(\n// 'model'=>'user',\n 'records' => $users,\n 'where' => 1,\n// 'limit'=>9999, // unless we're showing all users on a page at once, there's no way to\n // add all users to a group, since it's rebuilding the group on save...\n 'order' => empty($this->config['order']) ? 'username' : $this->config['order'],\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'columns' => array(\n gt('Username') => 'username',\n gt('First Name') => 'firstname',\n gt('Last Name') => 'lastname',\n gt('Is Member') => 'is_member',\n gt('Is Admin') => 'is_admin',\n ),\n 'controller' => $this->baseclassname,\n 'action' => $this->params['action'],\n ));", " assign_to_template(array(\n 'page' => $page,\n 'group' => $group,\n 'users' => $users,\n 'canAdd' => (count($members) < count($users) ? 1 : 0),\n 'hasMember' => (count($members) > 0 ? 1 : 0),\n 'perm_level' => $perm_level,\n ));\n }", " public function update_group() {\n global $db;", " $group = new group();\n if (!empty($this->params['redirect'])) {\n $this->params['redirect'] = $db->selectValue('section', 'sef_name', 'id=' . $this->params['redirect']);\n }\n $group->update($this->params);\n expHistory::back();\n }", " public function delete_group() {\n global $user, $db;\n if (!$user->isAdmin()) {\n flash('error', gt('You do not have permission to delete user groups'));\n expHistory::back();\n }", " if (empty($this->params['id'])) {\n flash('error', gt('No group selected.'));\n expHistory::back();\n }", " // remove group members\n $db->delete('groupmembership', 'group_id=' . $this->params['id']);", " // remove group permissions\n $db->delete('grouppermission', 'gid=' . $this->params['id']);", " // remove group\n $db->delete('group', 'id=' . $this->params['id']);\n expHistory::back();\n }", " public function toggle_extension() {\n global $db;\n if (isset($this->params['id'])) $db->toggle('profileextension', 'active', 'id=' . $this->params['id']);\n expHistory::back();\n }", " public function update_memberships() {\n// global $user, $db;\n global $db;", " //$memb = $db->selectObject('groupmembership','member_id='.$user->id.' AND group_id='.$this->params['id'].' AND is_admin=1');\n $group = $db->selectObject('group', 'id=' . $this->params['id']);", " $db->delete('groupmembership', 'group_id=' . $group->id);\n $memb = new stdClass();\n $memb->group_id = $group->id;\n if ($this->params['memdata'] != \"\") {\n foreach ($this->params['memdata'] as $u => $str) {\n $memb->member_id = $u;\n $memb->is_admin = $str['is_admin'];\n $db->insertObject($memb, 'groupmembership');\n }\n }\n expSession::triggerRefresh();\n expHistory::back();\n }", " public function getUsersByJSON() {\n $modelname = $this->basemodel_name;\n $results = 25; // default get 25\n $startIndex = 0; // default start at 0\n $sort = null; // default don't sort\n $dir = 'asc'; // default sort dir is asc\n $sort_dir = SORT_ASC;", " // How many records to get?\n if (strlen($this->params['results']) > 0) {\n $results = $this->params['results'];\n }", " // Start at which record?\n if (strlen($this->params['startIndex']) > 0) {\n $startIndex = $this->params['startIndex'];\n }", " // Sorted?\n if (strlen($this->params['sort']) > 0) {\n $sort = $this->params['sort'];\n if ($sort = 'id') $sort = 'username';\n }", " if (!empty($this->params['filter'])) {\n switch ($this->params['filter']) {\n case '1' :\n $filter = '';\n break;\n case '2' :\n $filter = \"is_system_user != 1\";\n break;\n case '3' :\n $filter = \"is_admin != 1\";\n }\n }", "// if (!empty($_GET['filter'])) {\n// switch ($_GET['filter']) {\n// case '1' :\n// $filter = '';\n// break;\n// case '2' :\n// $filter = \"is_system_user != 1\";\n// break;\n// case '3' :\n// $filter = \"is_admin != 1\";\n// }\n// }", " // Sort dir?\n if ((strlen($this->params['dir']) > 0) && ($this->params['dir'] == 'desc')) {\n $dir = 'desc';\n $sort_dir = SORT_DESC;\n } else {\n $dir = 'asc';\n $sort_dir = SORT_ASC;\n }", " if (!empty($this->params['query'])) {", "// $this->params['query'] = $this->params['query'];\n $totalrecords = $this->$modelname->find('count', (empty($filter) ? '' : $filter . \" AND \") . \"(username LIKE '%\" . $this->params['query'] . \"%' OR firstname LIKE '%\" . $this->params['query'] . \"%' OR lastname LIKE '%\" . $this->params['query'] . \"%' OR email LIKE '%\" . $this->params['query'] . \"%')\");", " $users = $this->$modelname->find('all', (empty($filter) ? '' : $filter . \" AND \") . \"(username LIKE '%\" . $this->params['query'] . \"%' OR firstname LIKE '%\" . $this->params['query'] . \"%' OR lastname LIKE '%\" . $this->params['query'] . \"%' OR email LIKE '%\" . $this->params['query'] . \"%')\", $sort . ' ' . $dir, $results, $startIndex);", " for ($i = 0, $iMax = count($users); $i < $iMax; $i++) {\n if (ECOM == 1) {\n $users[$i]->usernamelabel = \"<a href='viewuser/{$users[$i]->id}' class='fileinfo'>{$users[$i]->username}</a>\";\n } else {\n $users[$i]->usernamelabel = $users[$i]->username;\n }\n }", " $returnValue = array(\n 'recordsReturned' => count($users),\n 'totalRecords' => $totalrecords,\n 'startIndex' => $startIndex,\n 'sort' => $sort,\n 'dir' => $dir,\n 'pageSize' => $results,\n 'records' => $users\n );\n } else {", " $totalrecords = $this->$modelname->find('count', $filter);", " $users = $this->$modelname->find('all', $filter, $sort . ' ' . $dir, $results, $startIndex);", " for ($i = 0, $iMax = count($users); $i < $iMax; $i++) {\n if (ECOM == 1) {\n $users[$i]->usernamelabel = \"<a href='viewuser/{$users[$i]->id}' class='fileinfo'>{$users[$i]->username}</a>\";\n } else {\n $users[$i]->usernamelabel = $users[$i]->username;\n }\n }", " $returnValue = array(\n 'recordsReturned' => count($users),\n 'totalRecords' => $totalrecords,\n 'startIndex' => $startIndex,\n 'sort' => $sort,\n 'dir' => $dir,\n 'pageSize' => $results,\n 'records' => $users\n );", " }", " echo json_encode($returnValue);\n }", " public function viewuser() {\n global $user;", " if (!empty($this->params['id'])) {\n $u = new user($this->params['id']);\n } elseif (!empty($user->id)) {\n $u = $user;\n } else {\n flash('error', gt('You may not view this user'));\n expHistory::back();\n }\n $address = new address();", " $billings = $address->find('all', 'user_id=' . $u->id . ' AND is_billing = 1');\n $shippings = $address->find('all', 'user_id=' . $u->id . ' AND is_shipping = 1');", " // build out a SQL query that gets all the data we need and is sortable.\n $sql = 'SELECT o.*, b.firstname as firstname, b.billing_cost as total, b.middlename as middlename, b.lastname as lastname, os.title as status, ot.title as order_type ';\n $sql .= 'FROM ' . DB_TABLE_PREFIX . '_orders o, ' . DB_TABLE_PREFIX . '_billingmethods b, ';\n $sql .= DB_TABLE_PREFIX . '_order_status os, ';\n $sql .= DB_TABLE_PREFIX . '_order_type ot ';\n $sql .= 'WHERE o.id = b.orders_id AND o.order_status_id = os.id AND o.order_type_id = ot.id AND o.purchased > 0 AND user_id =' . $u->id;", " $limit = (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10;\n $order = !empty($this->params['order']) ? $this->params['order'] : 'purchased';\n $dir = !empty($this->params['dir']) ? $this->params['dir'] : 'DESC';\n //eDebug($sql, true);\n $orders = new expPaginator(array(\n //'model'=>'order',\n 'sql' => $sql,\n 'limit' => $limit,\n 'order' => $order,\n 'dir' => $dir,\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'columns' => array(\n gt('Order #') => 'invoice_id',\n gt('Total') => 'total',\n gt('Date Purchased') => 'purchased',\n// gt('Type') => 'order_type_id',\n gt('Status') => 'order_status_id',\n gt('Ref') => 'orig_referrer',\n ),\n 'controller' => $this->params['controller'],\n 'action' => $this->params['action'],\n ));", " assign_to_template(array(\n 'u' => $u,\n 'billings' => $billings,\n 'shippings' => $shippings,\n 'orders' => $orders,\n ));\n }", " public function userperms() {\n global $user;", " if (!empty($this->params['mod']) && $user->isAdmin()) {\n $loc = expCore::makeLocation($this->params['mod'], isset($this->params['src']) ? $this->params['src'] : null, isset($this->params['int']) ? $this->params['int'] : null);\n $users = array();\n $modclass = expModules::getModuleClassName(($loc->mod));\n $mod = new $modclass();\n $perms = $mod->permissions($loc->int);\n $have_users = 0;\n foreach (user::getAllUsers(false) as $u) {\n $have_users = 1;\n foreach ($perms as $perm => $name) {\n// \t\t\t$var = 'perms_'.$perm;\n if (expPermissions::checkUser($u, $perm, $loc, true)) {\n $u->$perm = 1;\n } else if (expPermissions::checkUser($u, $perm, $loc)) {\n $u->$perm = 2;\n } else {\n $u->$perm = 0;\n }\n }\n $users[] = $u;\n }", " $p[gt(\"User Name\")] = 'username';\n $p[gt(\"First Name\")] = 'firstname';\n $p[gt(\"Last Name\")] = 'lastname';\n foreach ($mod->permissions() as $value) {\n // $p[gt($value)]=$key;\n $p[gt($value)] = 'no-sort';\n }", "// if (SEF_URLS == 1) {\n $page = new expPaginator(array(\n //'model'=>'user',\n// 'limit' => (isset($this->params['limit']) ? $this->params['limit'] : 20),\n 'records' => $users,\n //'sql'=>$sql,\n 'order' => (isset($this->params['order']) ? $this->params['order'] : 'username'),\n 'dir' => (isset($this->params['dir']) ? $this->params['dir'] : 'ASC'),\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller' => $this->params['controller'],\n 'action' => $this->params['action'],\n 'columns' => $p,\n ));\n// } else {\n// $page = new expPaginator(array(\n// //'model'=>'user',\n//// 'limit' => (isset($this->params['limit']) ? $this->params['limit'] : 20),\n// 'records' => $users,\n// //'sql'=>$sql,\n// 'order' => (isset($this->params['order']) ? $this->params['order'] : 'username'),\n// 'dir' => (isset($this->params['dir']) ? $this->params['dir'] : 'ASC'),\n// 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n// 'controller' => $this->params['module'],\n// 'action' => $this->params['action'],\n// 'columns' => $p,\n// ));\n// }", " assign_to_template(array(\n 'user_form' => 1,\n 'have_users' => $have_users,\n 'users' => $users,\n 'page' => $page,\n 'perms' => $perms,\n 'loc' => $loc,\n// 'title'=>($modclass != 'navigationController' || ($modclass == 'navigationController' && !empty($loc->src))) ? $mod->name().' '.($modclass != 'containermodule' ? gt('module') : '').' ' : gt('Page'),\n 'title' => ($loc->mod != 'navigation' || ($loc->mod == 'navigation' && !empty($loc->src))) ? $mod->name() . ' ' . ($loc->mod != 'container' ? gt('module') : '') . ' ' : gt('Page'),\n ));\n } else {\n// echo SITE_403_HTML;\n notfoundController::handle_not_authorized();\n }\n }", " public function userperms_save() {\n global $user;", " $loc = expCore::makeLocation($this->params['mod'], isset($this->params['src']) ? $this->params['src'] : null, isset($this->params['int']) ? $this->params['int'] : null);\n foreach ($this->params['users'] as $u) {\n expPermissions::revokeAll($u, $loc);\n }\n foreach ($this->params['permdata'] as $k => $user_str) {\n $perms = array_keys($user_str);\n $u = user::getUserById($k);\n for ($i = 0, $iMax = count($perms); $i < $iMax; $i++) {\n expPermissions::grant($u, $perms[$i], $loc);\n }", " if ($k == $user->id) {\n expPermissions::load($user);\n }\n }\n expSession::triggerRefresh();\n expHistory::back();\n }", " public function groupperms() {\n global $user;", " if (!empty($this->params['mod']) && $user->isAdmin()) {\n $loc = expCore::makeLocation($this->params['mod'], isset($this->params['src']) ? $this->params['src'] : null, isset($this->params['int']) ? $this->params['int'] : null);\n $users = array(); // users = groups\n $modclass = expModules::getModuleClassName($loc->mod);\n $mod = new $modclass();\n $perms = $mod->permissions($loc->int);", " foreach (group::getAllGroups() as $g) {\n foreach ($perms as $perm => $name) {\n// \t\t\t$var = 'perms_'.$perm;\n if (expPermissions::checkGroup($g, $perm, $loc, true)) {\n $g->$perm = 1;\n } else if (expPermissions::checkGroup($g, $perm, $loc)) {\n $g->$perm = 2;\n } else {\n $g->$perm = 0;\n }\n }\n $users[] = $g;\n }", " $p[gt(\"Group\")] = 'username';\n foreach ($mod->permissions() as $value) {\n // $p[gt($value)]=$key;\n $p[gt($value)] = 'no-sort';\n }", "// if (SEF_URLS == 1) {\n $page = new expPaginator(array(\n //'model'=>'user',\n// 'limit' => (isset($this->params['limit']) ? $this->params['limit'] : 20),\n 'records' => $users,\n //'sql'=>$sql,\n 'order' => (isset($this->params['order']) ? $this->params['order'] : 'name'),\n 'dir' => (isset($this->params['dir']) ? $this->params['dir'] : 'ASC'),\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller' => $this->params['controller'],\n 'action' => $this->params['action'],\n 'columns' => $p,\n ));\n// } else {\n// $page = new expPaginator(array(\n// //'model'=>'user',\n//// 'limit' => (isset($this->params['limit']) ? $this->params['limit'] : 20),\n// 'records' => $users,\n// //'sql'=>$sql,\n// 'order' => (isset($this->params['order']) ? $this->params['order'] : 'name'),\n// 'dir' => (isset($this->params['dir']) ? $this->params['dir'] : 'ASC'),\n// 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n// 'controller' => $this->params['module'],\n// 'action' => $this->params['action'],\n// 'columns' => $p,\n// ));\n// }", " assign_to_template(array(\n 'user_form' => 0,\n 'is_group' => 1,\n 'have_users' => count($users) > 0, // users = groups\n 'users' => $users,\n 'page' => $page,\n 'perms' => $perms,\n 'loc' => $loc,\n// 'title'=>($modclass != 'navigationController' || ($modclass == 'navigationController' && !empty($loc->src))) ? $mod->name().' '.($modclass != 'containermodule' ? gt('module') : '').' ' : gt('Page'),\n 'title' => ($loc->mod != 'navigation' || ($loc->mod == 'navigation' && !empty($loc->src))) ? $mod->name() . ' ' . ($loc->mod != 'container' ? gt('module') : '') . ' ' : gt('Page'),\n ));\n } else {\n// echo SITE_403_HTML;\n notfoundController::handle_not_authorized();\n }\n }", " public function groupperms_save() {\n $loc = expCore::makeLocation($this->params['mod'], isset($this->params['src']) ? $this->params['src'] : null, isset($this->params['int']) ? $this->params['int'] : null);\n foreach ($this->params['users'] as $g) {\n expPermissions::revokeAllGroup($g, $loc);\n }\n foreach ($this->params['permdata'] as $k => $group_str) {\n $perms = array_keys($group_str);\n $g = group::getGroupById($k);\n for ($i = 0, $iMax = count($perms); $i < $iMax; $i++) {\n expPermissions::grantGroup($g, $perms[$i], $loc);\n }\n }\n expSession::triggerRefresh();\n expHistory::back();\n }", " public function import() {\n if (expFile::canCreate(BASE . \"tmp/test\") != SYS_FILES_SUCCESS) {\n assign_to_template(array(\n \"error\" => \"The /tmp directory is not writable. Please contact your administrator.\",\n ));\n } else {\n //Setup the arrays with the name/value pairs for the dropdown menus\n $delimiterArray = Array(\n ',' => gt('Comma'),\n ';' => gt('Semicolon'),\n ':' => gt('Colon'),\n ' ' => gt('Space'));", "// //Setup the mete data (hidden values)\n// $form = new form();\n// $form->meta(\"controller\", \"users\");\n// $form->meta(\"action\", \"import_users_mapper\");\n//\n// //Register the dropdown menus\n// $form->register(\"delimiter\", gt('Delimiter Character'), new dropdowncontrol(\",\", $delimiterArray));\n// $form->register(\"upload\", gt('CSV File to Upload'), new uploadcontrol());\n// $form->register(\"use_header\", gt('First Row is a Header'), new checkboxcontrol(0, 0));\n// $form->register(\"rowstart\", gt('User Data begins in Row'), new textcontrol(\"1\", 1, 0, 6));\n// $form->register(\"submit\", \"\", new buttongroupcontrol(gt('Next'), \"\", gt('Cancel')));", " assign_to_template(array(\n// \"form_html\" => $form->tohtml(),\n 'delimiters' => $delimiterArray,\n ));\n }\n }", " public function import_users_mapper() {\n //Check to make sure the user filled out the required input.\n //FIXME needs to be the newer fail form\n if (!is_numeric($this->params[\"rowstart\"])) {\n unset($this->params[\"rowstart\"]);\n $this->params['_formError'] = gt('The starting row must be a number.');\n expSession::set(\"last_POST\", $this->params);\n header(\"Location: \" . $_SERVER['HTTP_REFERER']);\n exit('Redirecting...');\n }", " //Get the temp directory to put the uploaded file\n $directory = \"tmp\";", " //Get the file save it to the temp directory\n if ($_FILES[\"upload\"][\"error\"] == UPLOAD_ERR_OK) {\n //\t$file = file::update(\"upload\",$directory,null,time().\"_\".$_FILES['upload']['name']);\n $file = expFile::fileUpload(\"upload\", false, false, time() . \"_\" . $_FILES['upload']['name'], $directory.'/');\n if ($file == null) {\n switch ($_FILES[\"upload\"][\"error\"]) {\n case UPLOAD_ERR_INI_SIZE:\n case UPLOAD_ERR_FORM_SIZE:\n $this->params['_formError'] = gt('The file you attempted to upload is too large. Contact your system administrator if this is a problem.');\n break;\n case UPLOAD_ERR_PARTIAL:\n $this->params['_formError'] = gt('The file was only partially uploaded.');\n break;\n case UPLOAD_ERR_NO_FILE:\n $this->params['_formError'] = gt('No file was uploaded.');\n break;\n default:\n $this->params['_formError'] = gt('A strange internal error has occurred. Please contact the Exponent Developers.');\n break;\n }\n expSession::set(\"last_POST\", $this->params);\n header(\"Location: \" . $_SERVER['HTTP_REFERER']);\n exit(\"\");\n }\n }\n /*\n if (mime_content_type(BASE.$directory.\"/\".$file->filename) != \"text/plain\"){\n $this->params['_formError'] = \"File is not a delimited text file.\";\n expSession::set(\"last_POST\",$this->params);\n header(\"Location: \" . $_SERVER['HTTP_REFERER']);\n exit(\"\");\n }\n */", " //split the line into its columns\n $headerinfo = null;\n $line_end = ini_get('auto_detect_line_endings');\n ini_set('auto_detect_line_endings',TRUE);\n $fh = fopen(BASE . $directory . \"/\" . $file->filename, \"r\");\n if (!empty($this->params[\"use_header\"])) $this->params[\"rowstart\"]++;\n for ($x = 0; $x < $this->params[\"rowstart\"]; $x++) {\n $lineInfo = fgetcsv($fh, 2000, $this->params[\"delimiter\"]);\n if ($x == 0 && !empty($this->params[\"use_header\"])) $headerinfo = $lineInfo;\n }", " $colNames = array(\n \"none\" => gt('--Disregard this column--'),\n \"username\" => gt('Username'),\n \"password\" => gt('Password'),\n \"firstname\" => gt('First Name'),\n \"lastname\" => gt('Last Name'),\n \"email\" => gt('Email Address')\n );", " //Check to see if the line got split, otherwise throw an error\n if ($lineInfo == null) {\n $this->params['_formError'] = sprintf(gt('This file does not appear to be delimited by \"%s\". <br />Please specify a different delimiter.<br /><br />'), $this->params[\"delimiter\"]);\n expSession::set(\"last_POST\", $this->params);\n header(\"Location: \" . $_SERVER['HTTP_REFERER']);\n exit(\"\");\n } else {\n //Setup the meta data (hidden values)\n $form = new form();\n $form->meta(\"controller\", \"users\");\n $form->meta(\"action\", \"import_users_process\");\n $form->meta(\"rowstart\", $this->params[\"rowstart\"]);\n $form->meta(\"use_header\", $this->params[\"use_header\"]);\n $form->meta(\"filename\", $directory . \"/\" . $file->filename);\n $form->meta(\"delimiter\", $this->params[\"delimiter\"]);\n for ($i = 0, $iMax = count($lineInfo); $i < $iMax; $i++) {\n if ($headerinfo != null) {\n $title = $headerinfo[$i] . ' (' . $lineInfo[$i] .')';\n if (array_key_exists($headerinfo[$i], $colNames)) {\n $default = $headerinfo[$i];\n } else {\n $default = \"none\";\n }\n } else {\n $title = $lineInfo[$i];\n $default = \"none\";\n }\n $form->register(\"column[$i]\", $title, new dropdowncontrol($default, $colNames));\n }\n $form->register(\"submit\", \"\", new buttongroupcontrol(gt('Next'), \"\", gt('Cancel')));", " assign_to_template(array(\n \"form_html\" => $form->tohtml(),\n ));\n }\n }", " public function import_users_process() {\n if (in_array(\"username\", $this->params[\"column\"]) == false) {\n $unameOptions = array(\n \"FILN\" => gt('First Initial / Last Name'),\n \"FILNNUM\" => gt('First Initial / Last Name / Random Number'),\n \"EMAIL\" => gt('Email Address'),\n \"FNLN\" => gt('First Name / Last Name'));\n } else {\n $unameOptions = array(\"INFILE\" => gt('Username Specified in CSV File'));\n }", " if (in_array(\"password\", $this->params[\"column\"]) == false) {\n $pwordOptions = array(\n \"RAND\" => gt('Generate Random Passwords'),\n \"DEFPASS\" => gt('Use the Default Password Supplied Below'));\n } else {\n $pwordOptions = array(\"INFILE\" => gt('Password Specified in CSV File'));\n }\n if (count($pwordOptions) == 1) {\n $disabled = true;\n } else {\n $disabled = false;\n }", "// $form = new form();\n// $form->meta(\"controller\", \"users\");\n// $form->meta(\"action\", \"import_users_display\");\n// $form->meta(\"column\", $this->params[\"column\"]);\n// $form->meta(\"delimiter\", $this->params[\"delimiter\"]);\n// $form->meta(\"use_header\", $this->params[\"use_header\"]);\n// $form->meta(\"filename\", $this->params[\"filename\"]);\n// $form->meta(\"rowstart\", $this->params[\"rowstart\"]);\n//\n// $form->register(\"unameOptions\", gt('User Name Generations Options'), new dropdowncontrol(\"INFILE\", $unameOptions));\n// $form->register(\"pwordOptions\", gt('Password Generation Options'), new dropdowncontrol(\"defpass\", $pwordOptions));\n// $form->register(\"pwordText\", gt('Default Password'), new textcontrol(\"\", 10, $disabled));\n// $form->register(\"update\", gt('Update users already in database, instead of creating new user?'), new checkboxcontrol(0, 0));\n// $form->register(\"submit\", \"\", new buttongroupcontrol(gt('Next'), \"\", gt('Cancel')));", " assign_to_template(array(\n// \"form_html\" => $form->tohtml(),\n 'uname_options' => $unameOptions,\n 'pword_options' => $pwordOptions,\n 'pword_disabled' => $disabled,\n 'params' => $this->params\n ));\n }", " public function import_users_display() {\n $line_end = ini_get('auto_detect_line_endings');\n ini_set('auto_detect_line_endings',TRUE);\n $file = fopen(BASE . $this->params[\"filename\"], \"r\");\n $userinfo = array();\n $userarray = array();\n $usersdone = array();\n $linenum = 1;", " while (($filedata = fgetcsv($file, 2000, $this->params[\"delimiter\"])) != false) {", " if ($linenum >= $this->params[\"rowstart\"]) {\n $i = 0;", " $userinfo['username'] = \"\";\n $userinfo['firstname'] = \"\";\n $userinfo['lastname'] = \"\";\n $userinfo['is_admin'] = 0;\n $userinfo['is_acting_admin'] = 0;\n// $userinfo['is_locked'] = 0;\n $userinfo['email'] = '';\n $userinfo['changed'] = \"\";", " foreach ($filedata as $field) {\n if (!empty($this->params[\"column\"][$i]) && $this->params[\"column\"][$i] != \"none\") {\n $colname = $this->params[\"column\"][$i];\n $userinfo[$colname] = trim($field);\n } else {\n unset($this->params['column'][$i]);\n }\n $i++;\n }", " switch ($this->params[\"unameOptions\"]) {\n case \"FILN\":\n if (($userinfo['firstname'] != \"\") && ($userinfo['lastname'] != \"\")) {\n $userinfo['username'] = str_replace(\" \", \"\", strtolower($userinfo['firstname']{0} . $userinfo['lastname']));\n } else {\n $userinfo['username'] = \"\";\n// $userinfo['clearpassword'] = \"\";\n $userinfo['changed'] = \"skipped\";\n }\n break;\n case \"FILNNUM\":\n if (($userinfo['firstname'] != \"\") && ($userinfo['lastname'] != \"\")) {\n $userinfo['username'] = str_replace(\" \", \"\", strtolower($userinfo['firstname']{0} . $userinfo['lastname'] . mt_rand(100, 999)));\n } else {\n $userinfo['username'] = \"\";\n// $userinfo['clearpassword'] = \"\";\n $userinfo['changed'] = \"skipped\";\n }\n break;\n case \"EMAIL\":\n if ($userinfo['email'] != \"\") {\n $userinfo['username'] = str_replace(\" \", \"\", strtolower($userinfo['email']));\n } else {\n $userinfo['username'] = \"\";\n// $userinfo['clearpassword'] = \"\";\n $userinfo['changed'] = \"skipped\";\n }\n break;\n case \"FNLN\":\n if (($userinfo['firstname'] != \"\") && ($userinfo['lastname'] != \"\")) {\n $userinfo['username'] = str_replace(\" \", \"\", strtolower($userinfo['firstname'] . $userinfo['lastname']));\n } else {\n $userinfo['username'] = \"\";\n// $userinfo['clearpassword'] = \"\";\n $userinfo['changed'] = \"skipped\";\n }\n break;\n case \"INFILE\":\n if ($userinfo['username'] != \"\") {\n $userinfo['username'] = str_replace(\" \", \"\", $userinfo['username']);\n } else {\n $userinfo['username'] = \"\";\n// $userinfo['clearpassword'] = \"\";\n $userinfo['changed'] = \"skipped\";\n }\n break;\n }", " if ((!isset($userinfo['changed'])) || ($userinfo['changed'] != \"skipped\")) {\n// switch ($this->params[\"pwordOptions\"]) {\n// case \"RAND\":\n// $newpass = \"\";\n// for ($i = 0; $i < mt_rand(12, 20); $i++) {\n// $num = mt_rand(48, 122);\n// if (($num > 97 && $num < 122) || ($num > 65 && $num < 90) || ($num > 48 && $num < 57)) $newpass .= chr($num);\n// else $i--;\n// }\n// $userinfo['clearpassword'] = $newpass;\n// break;\n// case \"DEFPASS\":\n// $userinfo['clearpassword'] = str_replace(\" \", \"\", trim($this->params[\"pwordText\"]));\n// break;\n// }\n//\n// $userinfo['password'] = user::encryptPassword($userinfo['clearpassword']);", " $suffix = \"\";\n while (user::getUserByName($userinfo['username'] . $suffix) != null) { //username already exists\n if (!empty($this->params[\"update\"])) {\n if (in_array($userinfo['username'], $usersdone)) {\n $suffix = '-rand-' . mt_rand(100, 999);\n } else {\n $tmp = user::getUserByName($userinfo['username'] . $suffix);\n $userinfo['id'] = $tmp->id;\n $userinfo['changed'] = 1;\n break;\n }\n } else {\n $suffix = '-rand-' . mt_rand(100, 999);\n }\n }", " $userinfo['username'] = $userinfo['username'] . $suffix;\n $userinfo['linenum'] = $linenum;\n $userarray[] = $userinfo;\n $usersdone[] = $userinfo['username'];\n } else {\n $userinfo['linenum'] = $linenum;\n $userarray[] = $userinfo;\n }\n }\n $linenum++;\n }\n assign_to_template(array(\n \"userarray\" => $userarray,\n \"params\" => $this->params,\n ));\n }", " public function import_users_add() {", "", " $line_end = ini_get('auto_detect_line_endings');\n ini_set('auto_detect_line_endings',TRUE);\n $file = fopen(BASE . $this->params[\"filename\"], \"r\");\n $userinfo = array();\n $userarray = array();\n $usersdone = array();\n $linenum = 1;", " while (($filedata = fgetcsv($file, 2000, $this->params[\"delimiter\"])) != false) {", " if ($linenum >= $this->params[\"rowstart\"] && in_array($linenum,$this->params['importuser'])) {\n $i = 0;", " $userinfo['username'] = \"\";\n $userinfo['firstname'] = \"\";\n $userinfo['lastname'] = \"\";\n $userinfo['is_admin'] = 0;\n $userinfo['is_acting_admin'] = 0;\n// $userinfo['is_locked'] = 0;\n $userinfo['email'] = '';\n $userinfo['changed'] = \"\";", " foreach ($filedata as $field) {\n if ($this->params[\"column\"][$i] != \"none\") {\n $colname = $this->params[\"column\"][$i];\n $userinfo[$colname] = trim($field);\n }\n $i++;\n }", " switch ($this->params[\"unameOptions\"]) {\n case \"FILN\":\n if (($userinfo['firstname'] != \"\") && ($userinfo['lastname'] != \"\")) {\n $userinfo['username'] = str_replace(\" \", \"\", strtolower($userinfo['firstname']{0} . $userinfo['lastname']));\n } else {\n $userinfo['username'] = \"\";\n $userinfo['clearpassword'] = \"\";\n $userinfo['changed'] = \"skipped\";\n }\n break;\n case \"FILNNUM\":\n if (($userinfo['firstname'] != \"\") && ($userinfo['lastname'] != \"\")) {\n $userinfo['username'] = str_replace(\" \", \"\", strtolower($userinfo['firstname']{0} . $userinfo['lastname'] . mt_rand(100, 999)));\n } else {\n $userinfo['username'] = \"\";\n $userinfo['clearpassword'] = \"\";\n $userinfo['changed'] = \"skipped\";\n }\n break;\n case \"EMAIL\":\n if ($userinfo['email'] != \"\") {\n $userinfo['username'] = str_replace(\" \", \"\", strtolower($userinfo['email']));\n } else {\n $userinfo['username'] = \"\";\n $userinfo['clearpassword'] = \"\";\n $userinfo['changed'] = \"skipped\";\n }\n break;\n case \"FNLN\":\n if (($userinfo['firstname'] != \"\") && ($userinfo['lastname'] != \"\")) {\n $userinfo['username'] = str_replace(\" \", \"\", strtolower($userinfo['firstname'] . $userinfo['lastname']));\n } else {\n $userinfo['username'] = \"\";\n $userinfo['clearpassword'] = \"\";\n $userinfo['changed'] = \"skipped\";\n }\n break;\n case \"INFILE\":\n if ($userinfo['username'] != \"\") {\n $userinfo['username'] = str_replace(\" \", \"\", $userinfo['username']);\n } else {\n $userinfo['username'] = \"\";\n $userinfo['clearpassword'] = \"\";\n $userinfo['changed'] = \"skipped\";\n }\n break;\n }", " if ((!isset($userinfo['changed'])) || ($userinfo['changed'] != \"skipped\")) {\n switch ($this->params[\"pwordOptions\"]) {\n case \"RAND\":\n $newpass = \"\";\n for ($i = 0, $iMax = mt_rand(12, 20); $i < $iMax; $i++) {\n $num = mt_rand(48, 122);\n if (($num > 97 && $num < 122) || ($num > 65 && $num < 90) || ($num > 48 && $num < 57)) $newpass .= chr($num);\n else $i--;\n }\n $userinfo['clearpassword'] = $newpass;\n break;\n case \"DEFPASS\":\n $userinfo['clearpassword'] = str_replace(\" \", \"\", trim($this->params[\"pwordText\"]));\n break;\n }", " $userinfo['password'] = user::encryptPassword($userinfo['clearpassword']);", " $suffix = \"\";\n while (user::getUserByName($userinfo['username'] . $suffix) != null) { //username already exists\n if (!empty($this->params[\"update\"])) {\n if (in_array($userinfo['username'], $usersdone)) { // username exists because we already created it\n $suffix = mt_rand(100, 999);\n } else {\n $tmp = user::getUserByName($userinfo['username'] . $suffix);\n $userinfo['id'] = $tmp->id;\n $userinfo['changed'] = 1;\n break;\n }\n } else {\n $suffix = mt_rand(100, 999);\n }\n }", " $userinfo['username'] = $userinfo['username'] . $suffix;\n $newuser = new user($userinfo);\n $newuser->update();\n $userinfo['linenum'] = $linenum;\n $userarray[] = $userinfo;\n $usersdone[] = $userinfo['username'];\n if (USER_REGISTRATION_SEND_WELCOME && $this->params['sendemail'] && !empty($newuser->email)) {\n $msg = $newuser->firstname . \", \\n\\n\";\n $msg .= sprintf(USER_REGISTRATION_WELCOME_MSG, $newuser->firstname, $newuser->lastname, $newuser->username);\n $msg .= \"/n/nYour new password is: \".$userinfo['clearpassword'];\n $mail = new expMail();\n $mail->quickSend(array(\n 'text_message' => $msg,\n 'to' => array(trim($newuser->email) => trim(user::getUserAttribution($newuser->id))),\n 'from' => array(trim(SMTP_FROMADDRESS) => trim(ORGANIZATION_NAME)),\n 'subject' => USER_REGISTRATION_WELCOME_SUBJECT,\n ));\n }\n } else {\n $userinfo['linenum'] = $linenum;\n $userarray[] = $userinfo;\n }\n }\n $linenum++;\n }\n fclose($file);\n ini_set('auto_detect_line_endings',$line_end);\n assign_to_template(array(\n \"userarray\" => $userarray,\n ));\n unlink(BASE . $this->params[\"filename\"]);\n }", " public function sync_LDAPUsers() {\n if (USE_LDAP == 1 && function_exists('ldap_connect')) {\n $ldap = new expLDAP();\n $updated = $ldap->syncLDAPUsers();\n $ldap->close();\n flash('message', $updated.' '.gt('LDAP Users Updated'));\n }\n }", "}", "?>" ]
[ 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1156, 821, 538, 1298, 1110, 656, 639, 481, 1974, 221, 1264, 168, 235, 25, 598, 133, 55, 383, 63, 58, 352, 125, 394, 59, 2152, 117, 137, 259, 537, 2235, 33, 72, 1773, 250, 679, 739, 285, 1941, 540, 62, 528, 25, 1290, 256, 199, 122, 41, 99, 2020, 355, 147, 129, 1499], "buggy_code_start_loc": [44, 288, 107, 354, 1102, 26, 194, 37, 244, 25, 27, 24, 31, 25, 27, 50, 27, 27, 25, 44, 26, 25, 29, 34, 25, 24, 24, 25, 25, 27, 26, 68, 1, 54, 26, 428, 41, 29, 44, 55, 24, 24, 1, 28, 30, 25, 29, 25, 25, 29, 146, 128, 27], "filenames": ["framework/core/controllers/expController.php", "framework/core/expFramework.php", "framework/core/models/expRecord.php", "framework/core/subsystems/database/mysqli.php", "framework/core/subsystems/expDatabase.php", "framework/core/subsystems/expPaginator.php", "framework/core/subsystems/expSettings.php", "framework/core/subsystems/expString.php", "framework/core/subsystems/expTheme.php", "framework/modules/addressbook/controllers/addressController.php", "framework/modules/administration/controllers/administrationController.php", "framework/modules/banners/controllers/bannerController.php", "framework/modules/blog/controllers/blogController.php", "framework/modules/core/controllers/expCatController.php", "framework/modules/core/controllers/expCommentController.php", "framework/modules/core/controllers/expDefinableFieldController.php", "framework/modules/core/controllers/expHTMLEditorController.php", "framework/modules/core/controllers/expSimpleNoteController.php", "framework/modules/core/controllers/expTagController.php", "framework/modules/eaas/controllers/eaasController.php", "framework/modules/ealerts/controllers/ealertController.php", "framework/modules/ecommerce/controllers/billingController.php", "framework/modules/ecommerce/controllers/ecomconfigController.php", "framework/modules/ecommerce/controllers/eventregistrationController.php", "framework/modules/ecommerce/controllers/orderController.php", "framework/modules/ecommerce/controllers/order_statusController.php", "framework/modules/ecommerce/controllers/purchaseOrderController.php", "framework/modules/ecommerce/controllers/shippingController.php", "framework/modules/ecommerce/controllers/storeCategoryController.php", "framework/modules/ecommerce/controllers/storeController.php", "framework/modules/ecommerce/controllers/taxController.php", "framework/modules/ecommerce/products/models/donation.php", "framework/modules/events/controllers/eventController.php", "framework/modules/events/models/event.php", "framework/modules/file/controllers/fileController.php", "framework/modules/file/models/expFile.php", "framework/modules/filedownloads/controllers/filedownloadController.php", "framework/modules/forms/controllers/formsController.php", "framework/modules/help/controllers/helpController.php", "framework/modules/help/models/help_version.php", "framework/modules/importexport/controllers/importexportController.php", "framework/modules/migration/controllers/migrationController.php", "framework/modules/navigation/controllers/navigationController.php", "framework/modules/news/controllers/newsController.php", "framework/modules/photoalbum/controllers/photosController.php", "framework/modules/pixidou/controllers/pixidouController.php", "framework/modules/portfolio/controllers/portfolioController.php", "framework/modules/recyclebin/controllers/recyclebinController.php", "framework/modules/report/controllers/reportController.php", "framework/modules/search/controllers/searchController.php", "framework/modules/simplepoll/controllers/simplePollController.php", "framework/modules/users/controllers/loginController.php", "framework/modules/users/controllers/usersController.php"], "fixing_code_end_loc": [1183, 823, 543, 1298, 1110, 664, 643, 481, 1977, 221, 1263, 171, 234, 29, 599, 133, 59, 383, 69, 52, 358, 126, 397, 57, 2154, 120, 130, 262, 538, 2232, 25, 72, 1774, 255, 685, 741, 285, 1949, 541, 62, 535, 25, 1306, 259, 202, 121, 40, 102, 2025, 356, 147, 129, 1513], "fixing_code_start_loc": [44, 288, 107, 354, 1102, 26, 194, 37, 244, 25, 27, 25, 32, 26, 27, 50, 27, 27, 26, 43, 26, 25, 29, 33, 25, 25, 25, 25, 25, 26, 25, 68, 1, 55, 25, 428, 41, 30, 44, 55, 25, 24, 1, 29, 31, 24, 30, 25, 25, 29, 146, 128, 27], "message": "Exponent CMS version 2.3.9 suffers from a Object Injection vulnerability in framework/modules/core/controllers/expTagController.php related to change_tags.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:exponentcms:exponent_cms:2.3.9:*:*:*:*:*:*:*", "matchCriteriaId": "12FDDF33-2B21-4F8A-AB9A-01857197E810", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Exponent CMS version 2.3.9 suffers from a Object Injection vulnerability in framework/modules/core/controllers/expTagController.php related to change_tags."}, {"lang": "es", "value": "Existe una vulnerabilidad en Exponent CMS versi\u00f3n 2.3.9, sufre de una vulnerabilidad de Inyecci\u00f3n de Objeto en el archivo framework/modules/core/controllers/expTagController.php asociado con el par\u00e1metro change_tags."}], "evaluatorComment": null, "id": "CVE-2016-8900", "lastModified": "2019-05-28T16:01:48.990", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-05-24T17:29:00.913", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Exploit", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2016/09/30/5"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/exponentcms/exponent-cms/commit/fdafb5ec97838e4edbd685f587f28d3174ebb3db"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/exponentcms/exponent-cms/commit/fdafb5ec97838e4edbd685f587f28d3174ebb3db"}, "type": "CWE-74"}
197
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "##################################################\n#\n# Copyright (c) 2004-2016 OIC Group, Inc.\n#\n# This file is part of Exponent\n#\n# Exponent is free software; you can redistribute\n# it and/or modify it under the terms of the GNU\n# General Public License as published by the Free\n# Software Foundation; either version 2 of the\n# License, or (at your option) any later version.\n#\n# GPL: http://www.gnu.org/licenses/gpl.txt\n#\n##################################################", "/**\n * @subpackage Controllers\n * @package Modules\n */\n/** @define \"BASE\" \"../../../..\" */", "class usersController extends expController {\n public $basemodel_name = 'user';", "// protected $remove_permissions = array(\n// 'create',\n// 'edit'\n// );\n protected $manage_permissions = array(", " 'toggle_extension' => 'Activate Extensions',\n 'kill_session' => 'End Sessions',\n 'boot_user' => 'Boot Users',\n 'userperms' => 'User Permissions',\n 'groupperms' => 'Group Permissions',\n 'import' => 'Import Users',\n 'export' => 'Export Users',", " 'update' => 'Update Users',", " );", " static function displayname() {\n return gt(\"User Manager\");\n }", " static function description() {\n return gt(\"This is the user management module. It allows for creating user, editing user, etc.\");\n }", " static function hasSources() {\n return false;\n }", " static function hasContent() {\n return false;\n }", " static function canImportData() {\n return true;\n }", " public function manage() {\n global $user;", " expHistory::set('manageable', $this->params);\n// $limit = empty($this->config['limit']) ? 10 : $this->config['limit'];\n// $order = empty($this->config['order']) ? 'username' : $this->config['order'];\n if ($user->is_system_user == 1) {\n// $filter = 1; //'1';\n $where = '';\n } elseif ($user->isSuperAdmin()) {\n// $filter = 2; //\"is_system_user != 1\";\n $where = \"is_system_user != 1\";\n } else {\n// $filter = 3; //\"is_admin != 1\";\n $where = \"is_admin != 1\";\n }\n $page = new expPaginator(array(\n 'model'=>'user',\n 'where'=>$where,\n// 'limit'=>$limit,\n// 'order'=>$order,\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->baseclassname,\n 'action'=>$this->params['action'],\n 'columns'=>array(\n gt('Username')=>'username',\n gt('First Name')=>'firstname',\n gt('Last Name')=>'lastname',\n gt('Is Admin')=>'is_acting_admin',\n )\n ));", " assign_to_template(array('page'=>$page));\n// assign_to_template(array(\n// 'filter' => $filter\n// ));\n }", " public function create() {\n redirect_to(array('controller' => 'users', 'action' => 'edituser'));\n// $this->edituser();\n }", " public function edituser() {\n global $user, $db;", " // set history\n expHistory::set('editable', $this->params);\n expSession::set(\"userkey\", sha1(microtime()));\n expSession::clearCurrentUserSessionCache();", " $id = !empty($this->params['id']) ? $this->params['id'] : null;", " // check to see if we should be editing. You either need to be an admin, or editing own account.\n if ($user->isAdmin() || ($user->id == $id && !$user->globalPerm('prevent_profile_change'))) {\n $u = new user($id);\n if ($u->isSuperAdmin() && $user->isActingAdmin()) { // prevent regular admin's from editing super-admins\n flash('error', gt('You do not have the proper permissions to edit this user'));\n expHistory::back();\n }\n } else {\n flash('error', gt('You do not have the proper permissions to edit this user'));\n expHistory::back();\n }\n $active_extensions = $db->selectObjects('profileextension', 'active=1', 'rank');", " //If there is no image uploaded, use the default avatar\n if (empty($u->image)) $u->image = PATH_RELATIVE . \"framework/modules/users/assets/images/avatar_not_found.jpg\";", " assign_to_template(array(\n 'edit_user' => $u,\n 'extensions' => $active_extensions,\n \"userkey\" => expSession::get(\"userkey\")\n ));", " if ($user->isAdmin()) {\n $page = new expPaginator(array(\n 'model' => 'group',\n 'where' => 1,\n 'limit' => (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10,\n 'order' => empty($this->config['order']) ? 'name' : $this->config['order'],\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'columns' => array(\n gt('Name') => 'name',\n gt('Description') => 'description',\n ),\n 'controller' => $this->baseclassname,\n 'action' => $this->params['action'],\n ));", " assign_to_template(array(\n 'groups' => $page,\n 'mygroups' => $u->getGroupMemberships(),\n ));\n }\n }", " public function update() {\n global $user, $db;", " // get the id of user we are editing, if there is one\n $id = !empty($this->params['id']) ? $this->params['id'] : null;\n if ((($user->id == $id) || $user->isAdmin()) && $this->params['userkey'] != expSession::get(\"userkey\")) expHistory::back();", " // make sure this user should be updating user accounts\n if (!$user->isLoggedIn() && SITE_ALLOW_REGISTRATION == 0) {\n flash('error', gt('This site does not allow user registrations'));\n expHistory::back();\n } elseif (!$user->isAdmin() && ($user->isLoggedIn() && $user->id != $id)) {\n flash('error', gt('You do not have permission to edit this user account'));\n expHistory::back();\n }\n", " // if this is a new user account we need to check the password.", " // the password fields wont come thru on an edit. Otherwise we will\n // just update the existing account.\n if (!empty($id)) {\n $u = new user($id);\n $u->update($this->params);\n if ($user->isAdmin() && $user->id != $id) {\n flash('message', gt('Account information for') . ' ' . $u->username . ' ' . gt('has been updated.'));\n } else {\n flash('message', gt('Thank you') . ' ' . $u->firstname . '. ' . gt('Your account information has been updated.'));\n }\n if ($user->id == $id) {\n $_SESSION[SYS_SESSION_KEY]['user'] = $u;\n $user = $u;\n }\n } else {\n $u = new user($this->params);\n $ret = $u->setPassword($this->params['pass1'], $this->params['pass2']);\n if ($ret != true) expValidator::failAndReturnToForm($ret, $this->params);\n $u->save();\n if ($user->isAdmin()) {\n flash('message', gt('Created new user account for') . ' ' . $u->username);\n } else {\n user::login($u->username, $this->params['pass1']);\n flash('message', gt('Thank you') . ' ' . $u->firstname . '. ' . gt('Your new account has been created.'));\n }\n }", " // update the user profiles\n if (!empty($u->id)) {\n $this->params['user_id'] = $u->id;\n // get the active profile extensions and save them out\n $active_extensions = $db->selectObjects('profileextension', 'active=1');\n foreach ($active_extensions as $pe) {\n if (is_file(BASE . $pe->classfile)) {\n include_once(BASE . $pe->classfile);\n $ext = new $pe->classname();\n $db->delete($ext->tablename, 'user_id=' . $u->id);\n $ext->update($this->params);\n }\n }\n }", " // update group membership assignment\n if (!empty($this->params['member'])) {\n $old_groups = $db->selectObjects('groupmembership', 'member_id=' . $u->id);\n// $db->delete('groupmembership', 'member_id=' . $u->id); // start from scratch\n $memb = new stdClass();\n $memb->member_id = $u->id;\n foreach ($this->params['member'] as $grp) {\n $memb->group_id = $grp;\n $memb->is_admin = false;\n foreach ($old_groups as $oldgroup) {\n if ($oldgroup->group_id == $grp) {\n if ($oldgroup->is_admin) $memb->is_admin = true; // retain group admin setting\n }\n }\n $db->insertObject($memb, 'groupmembership');\n }\n if ($u->id == $user->id) expSession::triggerRefresh();\n }\n", " // if this is a new account then we will check to see if we need to send", " // a welcome message or admin notification of new accounts.\n if (empty($id)) {\n // Calculate Group Memberships for newly created users. Any groups that\n // are marked as 'inclusive' automatically pick up new users. This is the part\n // of the code that goes out, finds those groups, and makes the new user a member\n // of them.\n $memb = new stdClass();\n $memb->member_id = $u->id;\n // Also need to process the groupcodes, for promotional signup\n// $code_where = '';\n// if (isset($this->params['groupcode']) && $this->params['groupcode'] != '') {\n// $code_where = \" OR code='\" . $this->params['groupcode'] . \"'\";\n// }\n // Add to default plus any groupcode groups\n// foreach ($db->selectObjects('group', 'inclusive=1' . $code_where) as $g) {\n foreach ($db->selectObjects('group', 'inclusive=1') as $g) {\n $memb->group_id = $g->id;\n $db->insertObject($memb, 'groupmembership');\n }", " // if we added the user to any group than we need to reload their permissions\n// expPermissions::load($u); //FIXME why are we doing this? this loads the edited user perms over the current user???", " //signup email stuff\n if (USER_REGISTRATION_SEND_WELCOME && !empty($u->email)) {\n $msg = $u->firstname . \", \\n\\n\";\n $msg .= sprintf(USER_REGISTRATION_WELCOME_MSG, $u->firstname, $u->lastname, $u->username);", " $mail = new expMail();\n $mail->quickSend(array(\n 'text_message' => $msg,\n 'to' => array(trim($u->email) => trim(user::getUserAttribution($u->id))),\n 'from' => array(trim(SMTP_FROMADDRESS) => trim(ORGANIZATION_NAME)),\n 'subject' => USER_REGISTRATION_WELCOME_SUBJECT,\n ));", " flash('message', gt('A welcome email has been sent to') . ' ' . $u->email);\n }", " // send and email notification to the admin of the site.\n if (USER_REGISTRATION_SEND_NOTIF && !$user->isAdmin()) {\n $msg = gt(\"When\") . \": \" . date(\"F j, Y, g:i a\") . \"\\n\\n\";\n $msg .= gt(\"Their name is\") . \": \" . $u->firstname . \" \" . $u->lastname . \"\\n\\n\";", " $mail = new expMail();\n $mail->quickSend(array(\n 'text_message' => $msg,\n 'to' => trim(USER_REGISTRATION_ADMIN_EMAIL),\n 'from' => array(trim(SMTP_FROMADDRESS) => trim(ORGANIZATION_NAME)),\n 'subject' => USER_REGISTRATION_NOTIF_SUBJECT,\n ));\n }\n }", " // we need to reload our updated profile if we just edited our own account\n if ($id == $user->id) {\n $user->getUserProfile();\n// expPermissions::load($user); // not sure this is necessary since we can't add groups here\n }", " expHistory::back();\n }", " public function delete() {\n global $user, $db;\n if (!$user->isAdmin()) {\n flash('error', gt('You do not have permission to delete user accounts'));\n expHistory::back();\n }", " if (empty($this->params['id'])) {\n flash('error', gt('No user selected.'));\n expHistory::back();\n }", " // remove group memeberships\n $db->delete('groupmembership', 'member_id=' . $this->params['id']);", " // remove user permissions\n $db->delete('userpermission', 'uid=' . $this->params['id']);", " //remove user profiles\n $active_extensions = $db->selectObjects('profileextension', 'active=1');\n foreach ($active_extensions as $pe) {\n if (is_file(BASE . $pe->classfile)) {\n include_once(BASE . $pe->classfile);\n $ext = new $pe->classname();\n $db->delete($ext->table, 'user_id=' . $this->params['id']);\n }\n }", " // remove user address\n $address = new address();\n $db->delete($address->table, 'user_id=' . $this->params['id']);", " parent::delete();\n }", " public function manage_sessions() {\n// global $db, $user;\n global $db;", " expHistory::set('manageable', $this->params);", " //cleans up any old sessions\n if (SESSION_TIMEOUT_ENABLE == true) {\n $db->delete('sessionticket', 'last_active < ' . (time() - SESSION_TIMEOUT));\n// } else {\n// $db->delete('sessionticket', '1');\n }", " if (isset($this->params['id']) && $this->params['id'] == 0) {\n $sessions = $db->selectObjects('sessionticket', \"uid<>0\");\n $filtered = 1;\n } else {\n $sessions = $db->selectObjects('sessionticket');\n $filtered = 0;\n }", "//\t $sessions = $db->selectObjects('sessionticket');\n for ($i = 0, $iMax = count($sessions); $i < $iMax; $i++) {\n $sessions[$i]->user = new user($sessions[$i]->uid);\n if ($sessions[$i]->uid == 0) {\n $sessions[$i]->user->id = 0;\n }\n $sessions[$i]->duration = expDateTime::duration($sessions[$i]->last_active, $sessions[$i]->start_time);\n }", " assign_to_template(array(\n 'sessions' => $sessions,\n 'filter' => $filtered\n ));\n }", " public function kill_session() {\n global $user, $db;\n $ticket = $db->selectObject('sessionticket', \"ticket='\" . preg_replace('/[^A-Za-z0-9.]/', '', $this->params['ticket']) . \"'\");\n if ($ticket) {\n $u = new user($ticket->uid);\n if ($user->isSuperAdmin() || ($user->isActingAdmin() && !$u->isAdmin())) {\n // We can only kick the user if they are A) not an acting admin, or\n // B) The current user is a super user and the kicked user is not.\n $db->delete('sessionticket', \"ticket='\" . $ticket->ticket . \"'\");\n }\n }\n expHistory::back();\n }", " public function boot_user() {\n global $user, $db;\n if (!empty($this->params['id'])) {\n $u = new user($this->params['id']);\n if ($user->isSuperAdmin() || ($user->isActingAdmin() && !$u->isAdmin())) {\n // We can only kick the user if they are A) not an acting admin, or\n // B) The current user is a super user and the kicked user is not.\n $db->delete('sessionticket', 'uid=' . $u->id);\n }\n }\n expHistory::back();\n }", " /**\n  * This function scans two directories and searches for php files to add to the extensions database.\n * If you have added new extensions since the last time you have visited the page, it will add them to the database\n * in effect enabling your new extension to be tacked onto users profiles. You then have to enable it in the menu, but at least\n * now it is in the system and when the user goes to edit his profile, it will check for extensions and this one will be in!\n *\n  * @global string This function uses the global $db save information through the Exponenet database connection.\n  */\n public function manage_extensions() {\n global $db;", " // set history\n expHistory::set('manageable', $this->params);", " // Lets find all the user profiles availabe and then see if they are\n // in the database yet. If not we will add them.\n $ext_dirs = array(\n 'framework/modules/users/extensions',\n 'themes/' . DISPLAY_THEME . '/modules/users/extensions'\n );\n foreach ($ext_dirs as $dir) {\n if (is_readable(BASE . $dir)) {\n $dh = opendir(BASE . $dir);\n while (($file = readdir($dh)) !== false) {\n if (is_file(BASE . \"$dir/$file\") && is_readable(BASE . \"$dir/$file\") && substr($file, 0, 1) != '_' && substr($file, 0, 1) != '.') {\n include_once(BASE . \"$dir/$file\");\n $classname = substr($file, 0, -4);\n $class = new $classname();\n $extension = $db->selectObject('profileextension', \"title='\" . $class->name() . \"'\");\n if (empty($extension->id)) {\n $pe = new profileextension();\n $pe->title = $class->name();\n $pe->body = $class->description();\n $pe->classfile = \"$dir/$file\";\n $pe->classname = $classname;\n $pe->save();\n }\n }\n }\n }\n }", " $page = new expPaginator(array(\n 'model' => 'profileextension',\n 'where' => 1,\n 'limit' => 25,\n 'order' => 'title',\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'columns' => array(\n gt('Name') => 'title',\n gt('Description') => 'body',\n gt('Active') => 'active'\n ),\n 'controller' => $this->baseclassname,\n 'action' => $this->params['action'],\n ));", " assign_to_template(array(\n 'page' => $page\n ));\n }", " public function manage_groups() {\n expHistory::set('manageable', $this->params);\n $page = new expPaginator(array(\n 'model' => 'group',\n 'where' => 1,\n// 'limit' => (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10,\n 'order' => empty($this->config['order']) ? 'name' : $this->config['order'],\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'columns' => array(\n gt('Name') => 'name',\n gt('Description') => 'description',\n gt('Type') => 'inclusive',\n ),\n 'controller' => $this->baseclassname,\n 'action' => $this->params['action'],\n ));", " foreach ($page->records as $key=>$group) {\n $page->records[$key]->members = group::getUsersInGroup($group->id);\n }", " assign_to_template(array(\n 'page' => $page,\n ));\n }", " public function reset_password() {\n expHistory::set('editable', $this->params);\n }", " public function send_new_password() {\n global $db;", " // find the user", " $this->params['username'] = expString::escape($this->params['username']);", " $u = user::getUserByName($this->params['username']);\n if (empty($u)) {\n $u = user::getUserByEmail($this->params['username']);\n if (!empty($u) && $u->count > 1) {\n expValidator::failAndReturnToForm(gt('That email address applies to more than one user account, please enter your username instead.'));\n }\n }\n $u = new user($u->id);", " if (!expValidator::check_antispam($this->params)) {\n expValidator::failAndReturnToForm(gt('Anti-spam verification failed. Please try again.'), $this->params);\n } elseif (empty($u->id)) {\n expValidator::failAndReturnToForm(gt('We were unable to find an account with that username/email'), $this->params);\n } elseif (empty($u->email)) {\n expValidator::failAndReturnToForm(gt('Your account does not appear to have an email address. Please contact the site administrators to reset your password'), $this->params);\n } elseif ($u->isAdmin()) {\n expValidator::failAndReturnToForm(gt('You cannot reset passwords for an administrator account.'), $this->params);\n }", " $tok = new stdClass();\n $tok->uid = $u->id;\n $tok->expires = time() + 2 * 3600;\n $tok->token = md5(time()) . uniqid('');", " $email = $template = expTemplate::get_template_for_action($this, 'email/password_reset_email', $this->loc);\n $email->assign('token', $tok);\n $email->assign('username', $u->username);\n $msg = $email->render();\n $mail = new expMail();\n $mail->quickSend(array(\n 'html_message' => $msg,\n 'to' => array(trim($u->email) => trim(user::getUserAttribution($u->id))),\n 'from' => array(trim(SMTP_FROMADDRESS) => trim(ORGANIZATION_NAME)),\n 'subject' => gt('Password Reset Requested'),\n ));", " $db->delete('passreset_token', 'uid=' . $u->id);\n $db->insertObject($tok, 'passreset_token');\n flash('message', gt('An email has been sent to you with instructions on how to finish resetting your password.') . '<br><br>' .\n gt('This new password request is only valid for 2 hours. If you have not completed the password reset process within 2 hours, the new password request will expire.'));", " expHistory::back();\n }", " public function confirm_password_reset() {\n global $db;", " $db->delete('passreset_token', 'expires < ' . time());", " $tok = $db->selectObject('passreset_token', 'uid=' . intval($this->params['uid']) . \" AND token='\" . preg_replace('/[^A-Za-z0-9]/', '', expString::escape($this->params['token'])) . \"'\");", " if ($tok == null) {\n flash('error', gt('Your password reset request has expired. Please try again.'));\n expHistory::back();\n }", " // create the password\n $newpass = '';\n for ($i = 0, $iMax = mt_rand(12, 20); $i < $iMax; $i++) {\n $num = mt_rand(48, 122);\n if (($num > 97 && $num < 122) || ($num > 65 && $num < 90) || ($num > 48 && $num < 57)) $newpass .= chr($num);\n else $i--;\n }", " // look up the user\n $u = new user($tok->uid);", " // get the email message body and render it\n $email = $template = expTemplate::get_template_for_action($this, 'email/confirm_password_email', $this->loc);\n $email->assign('newpass', $newpass);\n $email->assign('username', $u->username);\n $msg = $email->render();", " // send the new password to the user\n $mail = new expMail();\n $mail->quickSend(array(\n 'html_message' => $msg,\n 'to' => array(trim($u->email) => trim(user::getUserAttribution($u->id))),\n 'from' => array(trim(SMTP_FROMADDRESS) => trim(ORGANIZATION_NAME)),\n 'subject' => gt('The account password for') . ' ' . HOSTNAME . ' ' . gt('was reset'),\n ));", " // Save new password\n $u->update(array('password' => user::encryptPassword($newpass)));", " // cleanup the reset token\n $db->delete('passreset_token', 'uid=' . $tok->uid);", " flash('message', gt('Your password has been reset and the new password has been emailed to you.'));", " // send the user the login page.\n redirect_to(array('controller' => 'login', 'action' => 'loginredirect'));\n }", " public function change_password() {\n global $user;", " expHistory::set('editable', $this->params);\n $id = isset($this->params['id']) ? $this->params['id'] : $user->id;", " if ($user->isAdmin() || ($user->id == $id)) {\n $isuser = ($user->id == $id) ? 1 : 0;\n $u = new user($id);\n } else {\n flash('error', gt('You do not have the proper permissions to do that'));\n expHistory::back();\n }\n assign_to_template(array(\n 'u' => $u,\n 'isuser' => $isuser\n ));\n }", " public function save_change_password() {\n global $user;", " $isuser = ($this->params['uid'] == $user->id) ? 1 : 0;", " if (!$user->isAdmin() && !$isuser) {\n flash('error', gt('You do not have permissions to change this users password.'));\n expHistory::back();\n }", " if (($isuser && empty($this->params['password'])) || (!empty($this->params['password']) && $user->password != user::encryptPassword($this->params['password']))) {\n flash('error', gt('The current password you entered is not correct.'));\n expHistory::returnTo('editable');\n }\n //eDebug($user);", " $u = new user(intval($this->params['uid']));", "\n $ret = $u->setPassword($this->params['new_password1'], $this->params['new_password2']);\n //eDebug($u, true);\n if (is_string($ret)) {\n flash('error', $ret);\n expHistory::returnTo('editable');\n } else {\n $params = array();\n $params['is_admin'] = !empty($u->is_admin);\n $params['is_acting_admin'] = !empty($u->is_acting_admin);\n $u->update($params);\n }", " if (!$isuser) {\n flash('message', gt('The password for') . ' ' . $u->username . ' ' . gt('has been changed.'));\n } else {\n $user->password = $u->password;\n flash('message', gt('Your password has been changed.'));\n }\n expHistory::back();\n }", " public function edit_userpassword() {\n expHistory::set('editable', $this->params);\n if (empty($this->params['id'])) {\n flash('error', gt('You must specify the user whose password you want to change'));\n expHistory::back();\n }", " $u = new user($this->params['id']);\n assign_to_template(array(\n 'u' => $u\n ));\n }", " public function update_userpassword() {", " global $user;", " if (!$user->isAdmin() && $this->params['id'] != $user->id) {\n flash('error', gt('You do not have permissions to change this users password.'));\n expHistory::back();\n }\n", " if (empty($this->params['id'])) {\n expValidator::failAndReturnToForm(gt('You must specify the user whose password you want to change'), $this->params);\n }", " if (empty($this->params['new_password1'])) {\n expValidator::setErrorField('new_password1');\n expValidator::failAndReturnToForm(gt('You must specify a new password for this user.'), $this->params);\n }", " if (empty($this->params['new_password2'])) {\n expValidator::setErrorField('new_password2');\n expValidator::failAndReturnToForm(gt('You must confirm the password.'), $this->params);", " }", " $u = new user($this->params['id']);\n $ret = $u->setPassword($this->params['new_password1'], $this->params['new_password2']);\n if (is_string($ret)) {\n expValidator::setErrorField('new_password1');\n $this->params['new_password1'] = '';\n $this->params['new_password2'] = '';\n expValidator::failAndReturnToForm($ret, $this->params);\n } else {\n $u->save(true);\n }", " flash('message', gt('Password reset for user') . ' ' . $u->username);\n expHistory::back();\n }", " public function edit_group() {\n global $db;", " expHistory::set('editable', $this->params);\n $id = isset($this->params['id']) ? $this->params['id'] : null;\n $group = new group($id);\n $group->redirect = $db->selectValue('section', 'id', \"sef_name='\" . $group->redirect . \"'\");\n assign_to_template(array(\n 'record' => $group\n ));\n }", " public function manage_group_memberships() {\n global $db, $user;\n// expHistory::set('manageable', $this->params);", " $memb = $db->selectObject('groupmembership', 'member_id=' . $user->id . ' AND group_id=' . $this->params['id'] . ' AND is_admin=1');", " $perm_level = 0;\n if ($memb) $perm_level = 1;\n if (expPermissions::check('user_management', expCore::makeLocation('administrationmodule'))) $perm_level = 2;", " $group = $db->selectObject('group', 'id=' . $this->params['id']);\n $users = user::getAllUsers(0);", " $members = array();\n $admins = array();\n foreach ($db->selectObjects('groupmembership', 'group_id=' . $group->id) as $m) {\n $members[] = $m->member_id;\n if ($m->is_admin == 1) {\n $admins[] = $m->member_id;\n }\n }", " for ($i = 0, $iMax = count($users); $i < $iMax; $i++) {\n if (in_array($users[$i]->id, $members)) {\n $users[$i]->is_member = 1;\n } else {\n $users[$i]->is_member = 0;\n }", " if (in_array($users[$i]->id, $admins)) {\n $users[$i]->is_admin = 1;\n } else {\n $users[$i]->is_admin = 0;\n }\n }", " //$limit = empty($this->config['limit']) ? 10 : $this->config['limit'];\n $page = new expPaginator(array(\n// 'model'=>'user',\n 'records' => $users,\n 'where' => 1,\n// 'limit'=>9999, // unless we're showing all users on a page at once, there's no way to\n // add all users to a group, since it's rebuilding the group on save...\n 'order' => empty($this->config['order']) ? 'username' : $this->config['order'],\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'columns' => array(\n gt('Username') => 'username',\n gt('First Name') => 'firstname',\n gt('Last Name') => 'lastname',\n gt('Is Member') => 'is_member',\n gt('Is Admin') => 'is_admin',\n ),\n 'controller' => $this->baseclassname,\n 'action' => $this->params['action'],\n ));", " assign_to_template(array(\n 'page' => $page,\n 'group' => $group,\n 'users' => $users,\n 'canAdd' => (count($members) < count($users) ? 1 : 0),\n 'hasMember' => (count($members) > 0 ? 1 : 0),\n 'perm_level' => $perm_level,\n ));\n }", " public function update_group() {\n global $db;", " $group = new group();\n if (!empty($this->params['redirect'])) {\n $this->params['redirect'] = $db->selectValue('section', 'sef_name', 'id=' . $this->params['redirect']);\n }\n $group->update($this->params);\n expHistory::back();\n }", " public function delete_group() {\n global $user, $db;\n if (!$user->isAdmin()) {\n flash('error', gt('You do not have permission to delete user groups'));\n expHistory::back();\n }", " if (empty($this->params['id'])) {\n flash('error', gt('No group selected.'));\n expHistory::back();\n }", " // remove group members\n $db->delete('groupmembership', 'group_id=' . $this->params['id']);", " // remove group permissions\n $db->delete('grouppermission', 'gid=' . $this->params['id']);", " // remove group\n $db->delete('group', 'id=' . $this->params['id']);\n expHistory::back();\n }", " public function toggle_extension() {\n global $db;\n if (isset($this->params['id'])) $db->toggle('profileextension', 'active', 'id=' . $this->params['id']);\n expHistory::back();\n }", " public function update_memberships() {\n// global $user, $db;\n global $db;", " //$memb = $db->selectObject('groupmembership','member_id='.$user->id.' AND group_id='.$this->params['id'].' AND is_admin=1');\n $group = $db->selectObject('group', 'id=' . $this->params['id']);", " $db->delete('groupmembership', 'group_id=' . $group->id);\n $memb = new stdClass();\n $memb->group_id = $group->id;\n if ($this->params['memdata'] != \"\") {\n foreach ($this->params['memdata'] as $u => $str) {\n $memb->member_id = $u;\n $memb->is_admin = $str['is_admin'];\n $db->insertObject($memb, 'groupmembership');\n }\n }\n expSession::triggerRefresh();\n expHistory::back();\n }", " public function getUsersByJSON() {\n $modelname = $this->basemodel_name;\n $results = 25; // default get 25\n $startIndex = 0; // default start at 0\n $sort = null; // default don't sort\n $dir = 'asc'; // default sort dir is asc\n $sort_dir = SORT_ASC;", " // How many records to get?\n if (strlen($this->params['results']) > 0) {\n $results = $this->params['results'];\n }", " // Start at which record?\n if (strlen($this->params['startIndex']) > 0) {\n $startIndex = $this->params['startIndex'];\n }", " // Sorted?\n if (strlen($this->params['sort']) > 0) {\n $sort = $this->params['sort'];\n if ($sort = 'id') $sort = 'username';\n }", " if (!empty($this->params['filter'])) {\n switch ($this->params['filter']) {\n case '1' :\n $filter = '';\n break;\n case '2' :\n $filter = \"is_system_user != 1\";\n break;\n case '3' :\n $filter = \"is_admin != 1\";\n }\n }", "// if (!empty($_GET['filter'])) {\n// switch ($_GET['filter']) {\n// case '1' :\n// $filter = '';\n// break;\n// case '2' :\n// $filter = \"is_system_user != 1\";\n// break;\n// case '3' :\n// $filter = \"is_admin != 1\";\n// }\n// }", " // Sort dir?\n if ((strlen($this->params['dir']) > 0) && ($this->params['dir'] == 'desc')) {\n $dir = 'desc';\n $sort_dir = SORT_DESC;\n } else {\n $dir = 'asc';\n $sort_dir = SORT_ASC;\n }", " if (!empty($this->params['query'])) {", "// $this->params['query'] = $this->params['query'];\n $totalrecords = $this->$modelname->find('count', (empty($filter) ? '' : $filter . \" AND \") . \"(username LIKE '%\" . $this->params['query'] . \"%' OR firstname LIKE '%\" . $this->params['query'] . \"%' OR lastname LIKE '%\" . $this->params['query'] . \"%' OR email LIKE '%\" . $this->params['query'] . \"%')\");", " $users = $this->$modelname->find('all', (empty($filter) ? '' : $filter . \" AND \") . \"(username LIKE '%\" . $this->params['query'] . \"%' OR firstname LIKE '%\" . $this->params['query'] . \"%' OR lastname LIKE '%\" . $this->params['query'] . \"%' OR email LIKE '%\" . $this->params['query'] . \"%')\", $sort . ' ' . $dir, $results, $startIndex);", " for ($i = 0, $iMax = count($users); $i < $iMax; $i++) {\n if (ECOM == 1) {\n $users[$i]->usernamelabel = \"<a href='viewuser/{$users[$i]->id}' class='fileinfo'>{$users[$i]->username}</a>\";\n } else {\n $users[$i]->usernamelabel = $users[$i]->username;\n }\n }", " $returnValue = array(\n 'recordsReturned' => count($users),\n 'totalRecords' => $totalrecords,\n 'startIndex' => $startIndex,\n 'sort' => $sort,\n 'dir' => $dir,\n 'pageSize' => $results,\n 'records' => $users\n );\n } else {", " $totalrecords = $this->$modelname->find('count', $filter);", " $users = $this->$modelname->find('all', $filter, $sort . ' ' . $dir, $results, $startIndex);", " for ($i = 0, $iMax = count($users); $i < $iMax; $i++) {\n if (ECOM == 1) {\n $users[$i]->usernamelabel = \"<a href='viewuser/{$users[$i]->id}' class='fileinfo'>{$users[$i]->username}</a>\";\n } else {\n $users[$i]->usernamelabel = $users[$i]->username;\n }\n }", " $returnValue = array(\n 'recordsReturned' => count($users),\n 'totalRecords' => $totalrecords,\n 'startIndex' => $startIndex,\n 'sort' => $sort,\n 'dir' => $dir,\n 'pageSize' => $results,\n 'records' => $users\n );", " }", " echo json_encode($returnValue);\n }", " public function viewuser() {\n global $user;", " if (!empty($this->params['id'])) {\n $u = new user($this->params['id']);\n } elseif (!empty($user->id)) {\n $u = $user;\n } else {\n flash('error', gt('You may not view this user'));\n expHistory::back();\n }\n $address = new address();", " $billings = $address->find('all', 'user_id=' . $u->id . ' AND is_billing = 1');\n $shippings = $address->find('all', 'user_id=' . $u->id . ' AND is_shipping = 1');", " // build out a SQL query that gets all the data we need and is sortable.\n $sql = 'SELECT o.*, b.firstname as firstname, b.billing_cost as total, b.middlename as middlename, b.lastname as lastname, os.title as status, ot.title as order_type ';\n $sql .= 'FROM ' . DB_TABLE_PREFIX . '_orders o, ' . DB_TABLE_PREFIX . '_billingmethods b, ';\n $sql .= DB_TABLE_PREFIX . '_order_status os, ';\n $sql .= DB_TABLE_PREFIX . '_order_type ot ';\n $sql .= 'WHERE o.id = b.orders_id AND o.order_status_id = os.id AND o.order_type_id = ot.id AND o.purchased > 0 AND user_id =' . $u->id;", " $limit = (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10;\n $order = !empty($this->params['order']) ? $this->params['order'] : 'purchased';\n $dir = !empty($this->params['dir']) ? $this->params['dir'] : 'DESC';\n //eDebug($sql, true);\n $orders = new expPaginator(array(\n //'model'=>'order',\n 'sql' => $sql,\n 'limit' => $limit,\n 'order' => $order,\n 'dir' => $dir,\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'columns' => array(\n gt('Order #') => 'invoice_id',\n gt('Total') => 'total',\n gt('Date Purchased') => 'purchased',\n// gt('Type') => 'order_type_id',\n gt('Status') => 'order_status_id',\n gt('Ref') => 'orig_referrer',\n ),\n 'controller' => $this->params['controller'],\n 'action' => $this->params['action'],\n ));", " assign_to_template(array(\n 'u' => $u,\n 'billings' => $billings,\n 'shippings' => $shippings,\n 'orders' => $orders,\n ));\n }", " public function userperms() {\n global $user;", " if (!empty($this->params['mod']) && $user->isAdmin()) {\n $loc = expCore::makeLocation($this->params['mod'], isset($this->params['src']) ? $this->params['src'] : null, isset($this->params['int']) ? $this->params['int'] : null);\n $users = array();\n $modclass = expModules::getModuleClassName(($loc->mod));\n $mod = new $modclass();\n $perms = $mod->permissions($loc->int);\n $have_users = 0;\n foreach (user::getAllUsers(false) as $u) {\n $have_users = 1;\n foreach ($perms as $perm => $name) {\n// \t\t\t$var = 'perms_'.$perm;\n if (expPermissions::checkUser($u, $perm, $loc, true)) {\n $u->$perm = 1;\n } else if (expPermissions::checkUser($u, $perm, $loc)) {\n $u->$perm = 2;\n } else {\n $u->$perm = 0;\n }\n }\n $users[] = $u;\n }", " $p[gt(\"User Name\")] = 'username';\n $p[gt(\"First Name\")] = 'firstname';\n $p[gt(\"Last Name\")] = 'lastname';\n foreach ($mod->permissions() as $value) {\n // $p[gt($value)]=$key;\n $p[gt($value)] = 'no-sort';\n }", "// if (SEF_URLS == 1) {\n $page = new expPaginator(array(\n //'model'=>'user',\n// 'limit' => (isset($this->params['limit']) ? $this->params['limit'] : 20),\n 'records' => $users,\n //'sql'=>$sql,\n 'order' => (isset($this->params['order']) ? $this->params['order'] : 'username'),\n 'dir' => (isset($this->params['dir']) ? $this->params['dir'] : 'ASC'),\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller' => $this->params['controller'],\n 'action' => $this->params['action'],\n 'columns' => $p,\n ));\n// } else {\n// $page = new expPaginator(array(\n// //'model'=>'user',\n//// 'limit' => (isset($this->params['limit']) ? $this->params['limit'] : 20),\n// 'records' => $users,\n// //'sql'=>$sql,\n// 'order' => (isset($this->params['order']) ? $this->params['order'] : 'username'),\n// 'dir' => (isset($this->params['dir']) ? $this->params['dir'] : 'ASC'),\n// 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n// 'controller' => $this->params['module'],\n// 'action' => $this->params['action'],\n// 'columns' => $p,\n// ));\n// }", " assign_to_template(array(\n 'user_form' => 1,\n 'have_users' => $have_users,\n 'users' => $users,\n 'page' => $page,\n 'perms' => $perms,\n 'loc' => $loc,\n// 'title'=>($modclass != 'navigationController' || ($modclass == 'navigationController' && !empty($loc->src))) ? $mod->name().' '.($modclass != 'containermodule' ? gt('module') : '').' ' : gt('Page'),\n 'title' => ($loc->mod != 'navigation' || ($loc->mod == 'navigation' && !empty($loc->src))) ? $mod->name() . ' ' . ($loc->mod != 'container' ? gt('module') : '') . ' ' : gt('Page'),\n ));\n } else {\n// echo SITE_403_HTML;\n notfoundController::handle_not_authorized();\n }\n }", " public function userperms_save() {\n global $user;", " $loc = expCore::makeLocation($this->params['mod'], isset($this->params['src']) ? $this->params['src'] : null, isset($this->params['int']) ? $this->params['int'] : null);\n foreach ($this->params['users'] as $u) {\n expPermissions::revokeAll($u, $loc);\n }\n foreach ($this->params['permdata'] as $k => $user_str) {\n $perms = array_keys($user_str);\n $u = user::getUserById($k);\n for ($i = 0, $iMax = count($perms); $i < $iMax; $i++) {\n expPermissions::grant($u, $perms[$i], $loc);\n }", " if ($k == $user->id) {\n expPermissions::load($user);\n }\n }\n expSession::triggerRefresh();\n expHistory::back();\n }", " public function groupperms() {\n global $user;", " if (!empty($this->params['mod']) && $user->isAdmin()) {\n $loc = expCore::makeLocation($this->params['mod'], isset($this->params['src']) ? $this->params['src'] : null, isset($this->params['int']) ? $this->params['int'] : null);\n $users = array(); // users = groups\n $modclass = expModules::getModuleClassName($loc->mod);\n $mod = new $modclass();\n $perms = $mod->permissions($loc->int);", " foreach (group::getAllGroups() as $g) {\n foreach ($perms as $perm => $name) {\n// \t\t\t$var = 'perms_'.$perm;\n if (expPermissions::checkGroup($g, $perm, $loc, true)) {\n $g->$perm = 1;\n } else if (expPermissions::checkGroup($g, $perm, $loc)) {\n $g->$perm = 2;\n } else {\n $g->$perm = 0;\n }\n }\n $users[] = $g;\n }", " $p[gt(\"Group\")] = 'username';\n foreach ($mod->permissions() as $value) {\n // $p[gt($value)]=$key;\n $p[gt($value)] = 'no-sort';\n }", "// if (SEF_URLS == 1) {\n $page = new expPaginator(array(\n //'model'=>'user',\n// 'limit' => (isset($this->params['limit']) ? $this->params['limit'] : 20),\n 'records' => $users,\n //'sql'=>$sql,\n 'order' => (isset($this->params['order']) ? $this->params['order'] : 'name'),\n 'dir' => (isset($this->params['dir']) ? $this->params['dir'] : 'ASC'),\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller' => $this->params['controller'],\n 'action' => $this->params['action'],\n 'columns' => $p,\n ));\n// } else {\n// $page = new expPaginator(array(\n// //'model'=>'user',\n//// 'limit' => (isset($this->params['limit']) ? $this->params['limit'] : 20),\n// 'records' => $users,\n// //'sql'=>$sql,\n// 'order' => (isset($this->params['order']) ? $this->params['order'] : 'name'),\n// 'dir' => (isset($this->params['dir']) ? $this->params['dir'] : 'ASC'),\n// 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n// 'controller' => $this->params['module'],\n// 'action' => $this->params['action'],\n// 'columns' => $p,\n// ));\n// }", " assign_to_template(array(\n 'user_form' => 0,\n 'is_group' => 1,\n 'have_users' => count($users) > 0, // users = groups\n 'users' => $users,\n 'page' => $page,\n 'perms' => $perms,\n 'loc' => $loc,\n// 'title'=>($modclass != 'navigationController' || ($modclass == 'navigationController' && !empty($loc->src))) ? $mod->name().' '.($modclass != 'containermodule' ? gt('module') : '').' ' : gt('Page'),\n 'title' => ($loc->mod != 'navigation' || ($loc->mod == 'navigation' && !empty($loc->src))) ? $mod->name() . ' ' . ($loc->mod != 'container' ? gt('module') : '') . ' ' : gt('Page'),\n ));\n } else {\n// echo SITE_403_HTML;\n notfoundController::handle_not_authorized();\n }\n }", " public function groupperms_save() {\n $loc = expCore::makeLocation($this->params['mod'], isset($this->params['src']) ? $this->params['src'] : null, isset($this->params['int']) ? $this->params['int'] : null);\n foreach ($this->params['users'] as $g) {\n expPermissions::revokeAllGroup($g, $loc);\n }\n foreach ($this->params['permdata'] as $k => $group_str) {\n $perms = array_keys($group_str);\n $g = group::getGroupById($k);\n for ($i = 0, $iMax = count($perms); $i < $iMax; $i++) {\n expPermissions::grantGroup($g, $perms[$i], $loc);\n }\n }\n expSession::triggerRefresh();\n expHistory::back();\n }", " public function import() {\n if (expFile::canCreate(BASE . \"tmp/test\") != SYS_FILES_SUCCESS) {\n assign_to_template(array(\n \"error\" => \"The /tmp directory is not writable. Please contact your administrator.\",\n ));\n } else {\n //Setup the arrays with the name/value pairs for the dropdown menus\n $delimiterArray = Array(\n ',' => gt('Comma'),\n ';' => gt('Semicolon'),\n ':' => gt('Colon'),\n ' ' => gt('Space'));", "// //Setup the mete data (hidden values)\n// $form = new form();\n// $form->meta(\"controller\", \"users\");\n// $form->meta(\"action\", \"import_users_mapper\");\n//\n// //Register the dropdown menus\n// $form->register(\"delimiter\", gt('Delimiter Character'), new dropdowncontrol(\",\", $delimiterArray));\n// $form->register(\"upload\", gt('CSV File to Upload'), new uploadcontrol());\n// $form->register(\"use_header\", gt('First Row is a Header'), new checkboxcontrol(0, 0));\n// $form->register(\"rowstart\", gt('User Data begins in Row'), new textcontrol(\"1\", 1, 0, 6));\n// $form->register(\"submit\", \"\", new buttongroupcontrol(gt('Next'), \"\", gt('Cancel')));", " assign_to_template(array(\n// \"form_html\" => $form->tohtml(),\n 'delimiters' => $delimiterArray,\n ));\n }\n }", " public function import_users_mapper() {\n //Check to make sure the user filled out the required input.\n //FIXME needs to be the newer fail form\n if (!is_numeric($this->params[\"rowstart\"])) {\n unset($this->params[\"rowstart\"]);\n $this->params['_formError'] = gt('The starting row must be a number.');\n expSession::set(\"last_POST\", $this->params);\n header(\"Location: \" . $_SERVER['HTTP_REFERER']);\n exit('Redirecting...');\n }", " //Get the temp directory to put the uploaded file\n $directory = \"tmp\";", " //Get the file save it to the temp directory\n if ($_FILES[\"upload\"][\"error\"] == UPLOAD_ERR_OK) {\n //\t$file = file::update(\"upload\",$directory,null,time().\"_\".$_FILES['upload']['name']);\n $file = expFile::fileUpload(\"upload\", false, false, time() . \"_\" . $_FILES['upload']['name'], $directory.'/');\n if ($file == null) {\n switch ($_FILES[\"upload\"][\"error\"]) {\n case UPLOAD_ERR_INI_SIZE:\n case UPLOAD_ERR_FORM_SIZE:\n $this->params['_formError'] = gt('The file you attempted to upload is too large. Contact your system administrator if this is a problem.');\n break;\n case UPLOAD_ERR_PARTIAL:\n $this->params['_formError'] = gt('The file was only partially uploaded.');\n break;\n case UPLOAD_ERR_NO_FILE:\n $this->params['_formError'] = gt('No file was uploaded.');\n break;\n default:\n $this->params['_formError'] = gt('A strange internal error has occurred. Please contact the Exponent Developers.');\n break;\n }\n expSession::set(\"last_POST\", $this->params);\n header(\"Location: \" . $_SERVER['HTTP_REFERER']);\n exit(\"\");\n }\n }\n /*\n if (mime_content_type(BASE.$directory.\"/\".$file->filename) != \"text/plain\"){\n $this->params['_formError'] = \"File is not a delimited text file.\";\n expSession::set(\"last_POST\",$this->params);\n header(\"Location: \" . $_SERVER['HTTP_REFERER']);\n exit(\"\");\n }\n */", " //split the line into its columns\n $headerinfo = null;\n $line_end = ini_get('auto_detect_line_endings');\n ini_set('auto_detect_line_endings',TRUE);\n $fh = fopen(BASE . $directory . \"/\" . $file->filename, \"r\");\n if (!empty($this->params[\"use_header\"])) $this->params[\"rowstart\"]++;\n for ($x = 0; $x < $this->params[\"rowstart\"]; $x++) {\n $lineInfo = fgetcsv($fh, 2000, $this->params[\"delimiter\"]);\n if ($x == 0 && !empty($this->params[\"use_header\"])) $headerinfo = $lineInfo;\n }", " $colNames = array(\n \"none\" => gt('--Disregard this column--'),\n \"username\" => gt('Username'),\n \"password\" => gt('Password'),\n \"firstname\" => gt('First Name'),\n \"lastname\" => gt('Last Name'),\n \"email\" => gt('Email Address')\n );", " //Check to see if the line got split, otherwise throw an error\n if ($lineInfo == null) {\n $this->params['_formError'] = sprintf(gt('This file does not appear to be delimited by \"%s\". <br />Please specify a different delimiter.<br /><br />'), $this->params[\"delimiter\"]);\n expSession::set(\"last_POST\", $this->params);\n header(\"Location: \" . $_SERVER['HTTP_REFERER']);\n exit(\"\");\n } else {\n //Setup the meta data (hidden values)\n $form = new form();\n $form->meta(\"controller\", \"users\");\n $form->meta(\"action\", \"import_users_process\");\n $form->meta(\"rowstart\", $this->params[\"rowstart\"]);\n $form->meta(\"use_header\", $this->params[\"use_header\"]);\n $form->meta(\"filename\", $directory . \"/\" . $file->filename);\n $form->meta(\"delimiter\", $this->params[\"delimiter\"]);\n for ($i = 0, $iMax = count($lineInfo); $i < $iMax; $i++) {\n if ($headerinfo != null) {\n $title = $headerinfo[$i] . ' (' . $lineInfo[$i] .')';\n if (array_key_exists($headerinfo[$i], $colNames)) {\n $default = $headerinfo[$i];\n } else {\n $default = \"none\";\n }\n } else {\n $title = $lineInfo[$i];\n $default = \"none\";\n }\n $form->register(\"column[$i]\", $title, new dropdowncontrol($default, $colNames));\n }\n $form->register(\"submit\", \"\", new buttongroupcontrol(gt('Next'), \"\", gt('Cancel')));", " assign_to_template(array(\n \"form_html\" => $form->tohtml(),\n ));\n }\n }", " public function import_users_process() {\n if (in_array(\"username\", $this->params[\"column\"]) == false) {\n $unameOptions = array(\n \"FILN\" => gt('First Initial / Last Name'),\n \"FILNNUM\" => gt('First Initial / Last Name / Random Number'),\n \"EMAIL\" => gt('Email Address'),\n \"FNLN\" => gt('First Name / Last Name'));\n } else {\n $unameOptions = array(\"INFILE\" => gt('Username Specified in CSV File'));\n }", " if (in_array(\"password\", $this->params[\"column\"]) == false) {\n $pwordOptions = array(\n \"RAND\" => gt('Generate Random Passwords'),\n \"DEFPASS\" => gt('Use the Default Password Supplied Below'));\n } else {\n $pwordOptions = array(\"INFILE\" => gt('Password Specified in CSV File'));\n }\n if (count($pwordOptions) == 1) {\n $disabled = true;\n } else {\n $disabled = false;\n }", "// $form = new form();\n// $form->meta(\"controller\", \"users\");\n// $form->meta(\"action\", \"import_users_display\");\n// $form->meta(\"column\", $this->params[\"column\"]);\n// $form->meta(\"delimiter\", $this->params[\"delimiter\"]);\n// $form->meta(\"use_header\", $this->params[\"use_header\"]);\n// $form->meta(\"filename\", $this->params[\"filename\"]);\n// $form->meta(\"rowstart\", $this->params[\"rowstart\"]);\n//\n// $form->register(\"unameOptions\", gt('User Name Generations Options'), new dropdowncontrol(\"INFILE\", $unameOptions));\n// $form->register(\"pwordOptions\", gt('Password Generation Options'), new dropdowncontrol(\"defpass\", $pwordOptions));\n// $form->register(\"pwordText\", gt('Default Password'), new textcontrol(\"\", 10, $disabled));\n// $form->register(\"update\", gt('Update users already in database, instead of creating new user?'), new checkboxcontrol(0, 0));\n// $form->register(\"submit\", \"\", new buttongroupcontrol(gt('Next'), \"\", gt('Cancel')));", " assign_to_template(array(\n// \"form_html\" => $form->tohtml(),\n 'uname_options' => $unameOptions,\n 'pword_options' => $pwordOptions,\n 'pword_disabled' => $disabled,\n 'params' => $this->params\n ));\n }", " public function import_users_display() {\n $line_end = ini_get('auto_detect_line_endings');\n ini_set('auto_detect_line_endings',TRUE);\n $file = fopen(BASE . $this->params[\"filename\"], \"r\");\n $userinfo = array();\n $userarray = array();\n $usersdone = array();\n $linenum = 1;", " while (($filedata = fgetcsv($file, 2000, $this->params[\"delimiter\"])) != false) {", " if ($linenum >= $this->params[\"rowstart\"]) {\n $i = 0;", " $userinfo['username'] = \"\";\n $userinfo['firstname'] = \"\";\n $userinfo['lastname'] = \"\";\n $userinfo['is_admin'] = 0;\n $userinfo['is_acting_admin'] = 0;\n// $userinfo['is_locked'] = 0;\n $userinfo['email'] = '';\n $userinfo['changed'] = \"\";", " foreach ($filedata as $field) {\n if (!empty($this->params[\"column\"][$i]) && $this->params[\"column\"][$i] != \"none\") {\n $colname = $this->params[\"column\"][$i];\n $userinfo[$colname] = trim($field);\n } else {\n unset($this->params['column'][$i]);\n }\n $i++;\n }", " switch ($this->params[\"unameOptions\"]) {\n case \"FILN\":\n if (($userinfo['firstname'] != \"\") && ($userinfo['lastname'] != \"\")) {\n $userinfo['username'] = str_replace(\" \", \"\", strtolower($userinfo['firstname']{0} . $userinfo['lastname']));\n } else {\n $userinfo['username'] = \"\";\n// $userinfo['clearpassword'] = \"\";\n $userinfo['changed'] = \"skipped\";\n }\n break;\n case \"FILNNUM\":\n if (($userinfo['firstname'] != \"\") && ($userinfo['lastname'] != \"\")) {\n $userinfo['username'] = str_replace(\" \", \"\", strtolower($userinfo['firstname']{0} . $userinfo['lastname'] . mt_rand(100, 999)));\n } else {\n $userinfo['username'] = \"\";\n// $userinfo['clearpassword'] = \"\";\n $userinfo['changed'] = \"skipped\";\n }\n break;\n case \"EMAIL\":\n if ($userinfo['email'] != \"\") {\n $userinfo['username'] = str_replace(\" \", \"\", strtolower($userinfo['email']));\n } else {\n $userinfo['username'] = \"\";\n// $userinfo['clearpassword'] = \"\";\n $userinfo['changed'] = \"skipped\";\n }\n break;\n case \"FNLN\":\n if (($userinfo['firstname'] != \"\") && ($userinfo['lastname'] != \"\")) {\n $userinfo['username'] = str_replace(\" \", \"\", strtolower($userinfo['firstname'] . $userinfo['lastname']));\n } else {\n $userinfo['username'] = \"\";\n// $userinfo['clearpassword'] = \"\";\n $userinfo['changed'] = \"skipped\";\n }\n break;\n case \"INFILE\":\n if ($userinfo['username'] != \"\") {\n $userinfo['username'] = str_replace(\" \", \"\", $userinfo['username']);\n } else {\n $userinfo['username'] = \"\";\n// $userinfo['clearpassword'] = \"\";\n $userinfo['changed'] = \"skipped\";\n }\n break;\n }", " if ((!isset($userinfo['changed'])) || ($userinfo['changed'] != \"skipped\")) {\n// switch ($this->params[\"pwordOptions\"]) {\n// case \"RAND\":\n// $newpass = \"\";\n// for ($i = 0; $i < mt_rand(12, 20); $i++) {\n// $num = mt_rand(48, 122);\n// if (($num > 97 && $num < 122) || ($num > 65 && $num < 90) || ($num > 48 && $num < 57)) $newpass .= chr($num);\n// else $i--;\n// }\n// $userinfo['clearpassword'] = $newpass;\n// break;\n// case \"DEFPASS\":\n// $userinfo['clearpassword'] = str_replace(\" \", \"\", trim($this->params[\"pwordText\"]));\n// break;\n// }\n//\n// $userinfo['password'] = user::encryptPassword($userinfo['clearpassword']);", " $suffix = \"\";\n while (user::getUserByName($userinfo['username'] . $suffix) != null) { //username already exists\n if (!empty($this->params[\"update\"])) {\n if (in_array($userinfo['username'], $usersdone)) {\n $suffix = '-rand-' . mt_rand(100, 999);\n } else {\n $tmp = user::getUserByName($userinfo['username'] . $suffix);\n $userinfo['id'] = $tmp->id;\n $userinfo['changed'] = 1;\n break;\n }\n } else {\n $suffix = '-rand-' . mt_rand(100, 999);\n }\n }", " $userinfo['username'] = $userinfo['username'] . $suffix;\n $userinfo['linenum'] = $linenum;\n $userarray[] = $userinfo;\n $usersdone[] = $userinfo['username'];\n } else {\n $userinfo['linenum'] = $linenum;\n $userarray[] = $userinfo;\n }\n }\n $linenum++;\n }\n assign_to_template(array(\n \"userarray\" => $userarray,\n \"params\" => $this->params,\n ));\n }", " public function import_users_add() {", " if (!empty($this->params['filename']) && (strpos($this->params['filename'], 'tmp/') === false || strpos($this->params['folder'], '..') !== false)) {\n header('Location: ' . URL_FULL);\n exit(); // attempt to hack the site\n }", " $line_end = ini_get('auto_detect_line_endings');\n ini_set('auto_detect_line_endings',TRUE);\n $file = fopen(BASE . $this->params[\"filename\"], \"r\");\n $userinfo = array();\n $userarray = array();\n $usersdone = array();\n $linenum = 1;", " while (($filedata = fgetcsv($file, 2000, $this->params[\"delimiter\"])) != false) {", " if ($linenum >= $this->params[\"rowstart\"] && in_array($linenum,$this->params['importuser'])) {\n $i = 0;", " $userinfo['username'] = \"\";\n $userinfo['firstname'] = \"\";\n $userinfo['lastname'] = \"\";\n $userinfo['is_admin'] = 0;\n $userinfo['is_acting_admin'] = 0;\n// $userinfo['is_locked'] = 0;\n $userinfo['email'] = '';\n $userinfo['changed'] = \"\";", " foreach ($filedata as $field) {\n if ($this->params[\"column\"][$i] != \"none\") {\n $colname = $this->params[\"column\"][$i];\n $userinfo[$colname] = trim($field);\n }\n $i++;\n }", " switch ($this->params[\"unameOptions\"]) {\n case \"FILN\":\n if (($userinfo['firstname'] != \"\") && ($userinfo['lastname'] != \"\")) {\n $userinfo['username'] = str_replace(\" \", \"\", strtolower($userinfo['firstname']{0} . $userinfo['lastname']));\n } else {\n $userinfo['username'] = \"\";\n $userinfo['clearpassword'] = \"\";\n $userinfo['changed'] = \"skipped\";\n }\n break;\n case \"FILNNUM\":\n if (($userinfo['firstname'] != \"\") && ($userinfo['lastname'] != \"\")) {\n $userinfo['username'] = str_replace(\" \", \"\", strtolower($userinfo['firstname']{0} . $userinfo['lastname'] . mt_rand(100, 999)));\n } else {\n $userinfo['username'] = \"\";\n $userinfo['clearpassword'] = \"\";\n $userinfo['changed'] = \"skipped\";\n }\n break;\n case \"EMAIL\":\n if ($userinfo['email'] != \"\") {\n $userinfo['username'] = str_replace(\" \", \"\", strtolower($userinfo['email']));\n } else {\n $userinfo['username'] = \"\";\n $userinfo['clearpassword'] = \"\";\n $userinfo['changed'] = \"skipped\";\n }\n break;\n case \"FNLN\":\n if (($userinfo['firstname'] != \"\") && ($userinfo['lastname'] != \"\")) {\n $userinfo['username'] = str_replace(\" \", \"\", strtolower($userinfo['firstname'] . $userinfo['lastname']));\n } else {\n $userinfo['username'] = \"\";\n $userinfo['clearpassword'] = \"\";\n $userinfo['changed'] = \"skipped\";\n }\n break;\n case \"INFILE\":\n if ($userinfo['username'] != \"\") {\n $userinfo['username'] = str_replace(\" \", \"\", $userinfo['username']);\n } else {\n $userinfo['username'] = \"\";\n $userinfo['clearpassword'] = \"\";\n $userinfo['changed'] = \"skipped\";\n }\n break;\n }", " if ((!isset($userinfo['changed'])) || ($userinfo['changed'] != \"skipped\")) {\n switch ($this->params[\"pwordOptions\"]) {\n case \"RAND\":\n $newpass = \"\";\n for ($i = 0, $iMax = mt_rand(12, 20); $i < $iMax; $i++) {\n $num = mt_rand(48, 122);\n if (($num > 97 && $num < 122) || ($num > 65 && $num < 90) || ($num > 48 && $num < 57)) $newpass .= chr($num);\n else $i--;\n }\n $userinfo['clearpassword'] = $newpass;\n break;\n case \"DEFPASS\":\n $userinfo['clearpassword'] = str_replace(\" \", \"\", trim($this->params[\"pwordText\"]));\n break;\n }", " $userinfo['password'] = user::encryptPassword($userinfo['clearpassword']);", " $suffix = \"\";\n while (user::getUserByName($userinfo['username'] . $suffix) != null) { //username already exists\n if (!empty($this->params[\"update\"])) {\n if (in_array($userinfo['username'], $usersdone)) { // username exists because we already created it\n $suffix = mt_rand(100, 999);\n } else {\n $tmp = user::getUserByName($userinfo['username'] . $suffix);\n $userinfo['id'] = $tmp->id;\n $userinfo['changed'] = 1;\n break;\n }\n } else {\n $suffix = mt_rand(100, 999);\n }\n }", " $userinfo['username'] = $userinfo['username'] . $suffix;\n $newuser = new user($userinfo);\n $newuser->update();\n $userinfo['linenum'] = $linenum;\n $userarray[] = $userinfo;\n $usersdone[] = $userinfo['username'];\n if (USER_REGISTRATION_SEND_WELCOME && $this->params['sendemail'] && !empty($newuser->email)) {\n $msg = $newuser->firstname . \", \\n\\n\";\n $msg .= sprintf(USER_REGISTRATION_WELCOME_MSG, $newuser->firstname, $newuser->lastname, $newuser->username);\n $msg .= \"/n/nYour new password is: \".$userinfo['clearpassword'];\n $mail = new expMail();\n $mail->quickSend(array(\n 'text_message' => $msg,\n 'to' => array(trim($newuser->email) => trim(user::getUserAttribution($newuser->id))),\n 'from' => array(trim(SMTP_FROMADDRESS) => trim(ORGANIZATION_NAME)),\n 'subject' => USER_REGISTRATION_WELCOME_SUBJECT,\n ));\n }\n } else {\n $userinfo['linenum'] = $linenum;\n $userarray[] = $userinfo;\n }\n }\n $linenum++;\n }\n fclose($file);\n ini_set('auto_detect_line_endings',$line_end);\n assign_to_template(array(\n \"userarray\" => $userarray,\n ));\n unlink(BASE . $this->params[\"filename\"]);\n }", " public function sync_LDAPUsers() {\n if (USE_LDAP == 1 && function_exists('ldap_connect')) {\n $ldap = new expLDAP();\n $updated = $ldap->syncLDAPUsers();\n $ldap->close();\n flash('message', $updated.' '.gt('LDAP Users Updated'));\n }\n }", "}", "?>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1156, 821, 538, 1298, 1110, 656, 639, 481, 1974, 221, 1264, 168, 235, 25, 598, 133, 55, 383, 63, 58, 352, 125, 394, 59, 2152, 117, 137, 259, 537, 2235, 33, 72, 1773, 250, 679, 739, 285, 1941, 540, 62, 528, 25, 1290, 256, 199, 122, 41, 99, 2020, 355, 147, 129, 1499], "buggy_code_start_loc": [44, 288, 107, 354, 1102, 26, 194, 37, 244, 25, 27, 24, 31, 25, 27, 50, 27, 27, 25, 44, 26, 25, 29, 34, 25, 24, 24, 25, 25, 27, 26, 68, 1, 54, 26, 428, 41, 29, 44, 55, 24, 24, 1, 28, 30, 25, 29, 25, 25, 29, 146, 128, 27], "filenames": ["framework/core/controllers/expController.php", "framework/core/expFramework.php", "framework/core/models/expRecord.php", "framework/core/subsystems/database/mysqli.php", "framework/core/subsystems/expDatabase.php", "framework/core/subsystems/expPaginator.php", "framework/core/subsystems/expSettings.php", "framework/core/subsystems/expString.php", "framework/core/subsystems/expTheme.php", "framework/modules/addressbook/controllers/addressController.php", "framework/modules/administration/controllers/administrationController.php", "framework/modules/banners/controllers/bannerController.php", "framework/modules/blog/controllers/blogController.php", "framework/modules/core/controllers/expCatController.php", "framework/modules/core/controllers/expCommentController.php", "framework/modules/core/controllers/expDefinableFieldController.php", "framework/modules/core/controllers/expHTMLEditorController.php", "framework/modules/core/controllers/expSimpleNoteController.php", "framework/modules/core/controllers/expTagController.php", "framework/modules/eaas/controllers/eaasController.php", "framework/modules/ealerts/controllers/ealertController.php", "framework/modules/ecommerce/controllers/billingController.php", "framework/modules/ecommerce/controllers/ecomconfigController.php", "framework/modules/ecommerce/controllers/eventregistrationController.php", "framework/modules/ecommerce/controllers/orderController.php", "framework/modules/ecommerce/controllers/order_statusController.php", "framework/modules/ecommerce/controllers/purchaseOrderController.php", "framework/modules/ecommerce/controllers/shippingController.php", "framework/modules/ecommerce/controllers/storeCategoryController.php", "framework/modules/ecommerce/controllers/storeController.php", "framework/modules/ecommerce/controllers/taxController.php", "framework/modules/ecommerce/products/models/donation.php", "framework/modules/events/controllers/eventController.php", "framework/modules/events/models/event.php", "framework/modules/file/controllers/fileController.php", "framework/modules/file/models/expFile.php", "framework/modules/filedownloads/controllers/filedownloadController.php", "framework/modules/forms/controllers/formsController.php", "framework/modules/help/controllers/helpController.php", "framework/modules/help/models/help_version.php", "framework/modules/importexport/controllers/importexportController.php", "framework/modules/migration/controllers/migrationController.php", "framework/modules/navigation/controllers/navigationController.php", "framework/modules/news/controllers/newsController.php", "framework/modules/photoalbum/controllers/photosController.php", "framework/modules/pixidou/controllers/pixidouController.php", "framework/modules/portfolio/controllers/portfolioController.php", "framework/modules/recyclebin/controllers/recyclebinController.php", "framework/modules/report/controllers/reportController.php", "framework/modules/search/controllers/searchController.php", "framework/modules/simplepoll/controllers/simplePollController.php", "framework/modules/users/controllers/loginController.php", "framework/modules/users/controllers/usersController.php"], "fixing_code_end_loc": [1183, 823, 543, 1298, 1110, 664, 643, 481, 1977, 221, 1263, 171, 234, 29, 599, 133, 59, 383, 69, 52, 358, 126, 397, 57, 2154, 120, 130, 262, 538, 2232, 25, 72, 1774, 255, 685, 741, 285, 1949, 541, 62, 535, 25, 1306, 259, 202, 121, 40, 102, 2025, 356, 147, 129, 1513], "fixing_code_start_loc": [44, 288, 107, 354, 1102, 26, 194, 37, 244, 25, 27, 25, 32, 26, 27, 50, 27, 27, 26, 43, 26, 25, 29, 33, 25, 25, 25, 25, 25, 26, 25, 68, 1, 55, 25, 428, 41, 30, 44, 55, 25, 24, 1, 29, 31, 24, 30, 25, 25, 29, 146, 128, 27], "message": "Exponent CMS version 2.3.9 suffers from a Object Injection vulnerability in framework/modules/core/controllers/expTagController.php related to change_tags.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:exponentcms:exponent_cms:2.3.9:*:*:*:*:*:*:*", "matchCriteriaId": "12FDDF33-2B21-4F8A-AB9A-01857197E810", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Exponent CMS version 2.3.9 suffers from a Object Injection vulnerability in framework/modules/core/controllers/expTagController.php related to change_tags."}, {"lang": "es", "value": "Existe una vulnerabilidad en Exponent CMS versi\u00f3n 2.3.9, sufre de una vulnerabilidad de Inyecci\u00f3n de Objeto en el archivo framework/modules/core/controllers/expTagController.php asociado con el par\u00e1metro change_tags."}], "evaluatorComment": null, "id": "CVE-2016-8900", "lastModified": "2019-05-28T16:01:48.990", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-05-24T17:29:00.913", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Exploit", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2016/09/30/5"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/exponentcms/exponent-cms/commit/fdafb5ec97838e4edbd685f587f28d3174ebb3db"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/exponentcms/exponent-cms/commit/fdafb5ec97838e4edbd685f587f28d3174ebb3db"}, "type": "CWE-74"}
197
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * card-iasecc.c: Support for IAS/ECC smart cards\n *\n * Copyright (C) 2010 Viktor Tarasov <vtarasov@gmail.com>\n *\t\t\tOpenTrust <www.opentrust.com>\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */", "#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif", "#ifdef ENABLE_OPENSSL /* empty file without openssl */", "#include <string.h>\n#include <stdlib.h>", "#include <openssl/bn.h>\n#include <openssl/evp.h>\n#include <openssl/pem.h>\n#include <openssl/err.h>\n#include <openssl/rand.h>\n#include <openssl/sha.h>\n#include <openssl/rsa.h>\n#include <openssl/pkcs12.h>\n#include <openssl/x509v3.h>", "#include \"internal.h\"\n#include \"asn1.h\"\n#include \"cardctl.h\"\n#include \"opensc.h\"\n/* #include \"sm.h\" */\n#include \"pkcs15.h\"\n/* #include \"hash-strings.h\" */\n#include \"gp.h\"", "#include \"iasecc.h\"", "#define IASECC_CARD_DEFAULT_FLAGS ( 0\t\t\t\\\n\t\t| SC_ALGORITHM_ONBOARD_KEY_GEN\t\t\\\n\t\t| SC_ALGORITHM_RSA_PAD_ISO9796\t\t\\\n\t\t| SC_ALGORITHM_RSA_PAD_PKCS1\t\t\\\n\t\t| SC_ALGORITHM_RSA_HASH_NONE\t\t\\\n\t\t| SC_ALGORITHM_RSA_HASH_SHA1\t\t\\\n\t\t| SC_ALGORITHM_RSA_HASH_SHA256)", "/* generic iso 7816 operations table */\nstatic const struct sc_card_operations *iso_ops = NULL;", "/* our operations table with overrides */\nstatic struct sc_card_operations iasecc_ops;", "static struct sc_card_driver iasecc_drv = {\n\t\"IAS-ECC\",\n\t\"iasecc\",\n\t&iasecc_ops,\n\tNULL, 0, NULL\n};", "static struct sc_atr_table iasecc_known_atrs[] = {\n\t{ \"3B:7F:96:00:00:00:31:B8:64:40:70:14:10:73:94:01:80:82:90:00\",\n\t \"FF:FF:FF:FF:FF:FF:FF:FE:FF:FF:00:00:FF:FF:FF:FF:FF:FF:FF:FF\",\n\t\t\"IAS/ECC Gemalto\", SC_CARD_TYPE_IASECC_GEMALTO, 0, NULL },\n { \"3B:DD:18:00:81:31:FE:45:80:F9:A0:00:00:00:77:01:08:00:07:90:00:FE\", NULL,\n\t\t\"IAS/ECC v1.0.1 Oberthur\", SC_CARD_TYPE_IASECC_OBERTHUR, 0, NULL },\n\t{ \"3B:7D:13:00:00:4D:44:57:2D:49:41:53:2D:43:41:52:44:32\", NULL,\n\t\t\"IAS/ECC v1.0.1 Sagem MDW-IAS-CARD2\", SC_CARD_TYPE_IASECC_SAGEM, 0, NULL },\n\t{ \"3B:7F:18:00:00:00:31:B8:64:50:23:EC:C1:73:94:01:80:82:90:00\", NULL,\n\t\t\"IAS/ECC v1.0.1 Sagem ypsID S3\", SC_CARD_TYPE_IASECC_SAGEM, 0, NULL },\n\t{ \"3B:DF:96:00:80:31:FE:45:00:31:B8:64:04:1F:EC:C1:73:94:01:80:82:90:00:EC\", NULL,\n\t\t\"IAS/ECC Morpho MinInt - Agent Card\", SC_CARD_TYPE_IASECC_MI, 0, NULL },\n\t{ \"3B:DF:18:FF:81:91:FE:1F:C3:00:31:B8:64:0C:01:EC:C1:73:94:01:80:82:90:00:B3\", NULL,\n\t\t\"IAS/ECC v1.0.1 Amos\", SC_CARD_TYPE_IASECC_AMOS, 0, NULL },\n\t{ \"3B:DC:18:FF:81:91:FE:1F:C3:80:73:C8:21:13:66:02:04:03:55:00:02:34\", NULL,\n\t\t\"IAS/ECC v1.0.1 Amos\", SC_CARD_TYPE_IASECC_AMOS, 0, NULL },\n\t{ \"3B:DC:18:FF:81:91:FE:1F:C3:80:73:C8:21:13:66:01:0B:03:52:00:05:38\", NULL,\n\t\t\"IAS/ECC v1.0.1 Amos\", SC_CARD_TYPE_IASECC_AMOS, 0, NULL },\n\t{ NULL, NULL, NULL, 0, 0, NULL }\n};", "static struct sc_aid OberthurIASECC_AID = {\n\t{0xA0,0x00,0x00,0x00,0x77,0x01,0x08,0x00,0x07,0x00,0x00,0xFE,0x00,0x00,0x01,0x00}, 16\n};", "static struct sc_aid MIIASECC_AID = {\n\t{ 0x4D, 0x49, 0x4F, 0x4D, 0x43, 0x54}, 6\n};", "struct iasecc_pin_status {\n\tunsigned char sha1[SHA_DIGEST_LENGTH];\n\tunsigned char reference;", "\tstruct iasecc_pin_status *next;\n\tstruct iasecc_pin_status *prev;\n};", "struct iasecc_pin_status *checked_pins = NULL;", "static int iasecc_select_file(struct sc_card *card, const struct sc_path *path, struct sc_file **file_out);\nstatic int iasecc_process_fci(struct sc_card *card, struct sc_file *file, const unsigned char *buf, size_t buflen);\nstatic int iasecc_get_serialnr(struct sc_card *card, struct sc_serial_number *serial);\nstatic int iasecc_sdo_get_data(struct sc_card *card, struct iasecc_sdo *sdo);\nstatic int iasecc_pin_get_policy (struct sc_card *card, struct sc_pin_cmd_data *data);\nstatic int iasecc_pin_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd, int *tries_left);\nstatic int iasecc_get_free_reference(struct sc_card *card, struct iasecc_ctl_get_free_reference *ctl_data);\nstatic int iasecc_sdo_put_data(struct sc_card *card, struct iasecc_sdo_update *update);", "#ifdef ENABLE_SM\nstatic int _iasecc_sm_read_binary(struct sc_card *card, unsigned int offs, unsigned char *buf, size_t count);\nstatic int _iasecc_sm_update_binary(struct sc_card *card, unsigned int offs, const unsigned char *buff, size_t count);\n#endif", "static int\niasecc_chv_cache_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_pin_status *pin_status = NULL, *current = NULL;", "\tLOG_FUNC_CALLED(ctx);", "\tfor(current = checked_pins; current; current = current->next)\n\t\tif (current->reference == pin_cmd->pin_reference)\n\t\t\tbreak;", "\tif (current) {\n\t\tsc_log(ctx, \"iasecc_chv_cache_verified() current PIN-%i\", current->reference);\n\t\tpin_status = current;\n\t}\n\telse {\n\t\tpin_status = calloc(1, sizeof(struct iasecc_pin_status));\n\t\tif (!pin_status)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, \"Cannot callocate PIN status info\");\n\t\tsc_log(ctx, \"iasecc_chv_cache_verified() allocated %p\", pin_status);\n\t}", "\tpin_status->reference = pin_cmd->pin_reference;\n\tif (pin_cmd->pin1.data)\n\t\tSHA1(pin_cmd->pin1.data, pin_cmd->pin1.len, pin_status->sha1);\n\telse\n\t\tmemset(pin_status->sha1, 0, SHA_DIGEST_LENGTH);", "\tsc_log_hex(ctx, \"iasecc_chv_cache_verified() sha1(PIN)\", pin_status->sha1, SHA_DIGEST_LENGTH);", "\tif (!current) {\n\t\tif (!checked_pins) {\n\t\t\tchecked_pins = pin_status;\n\t\t}\n\t\telse {\n\t\tchecked_pins->prev = pin_status;\n\t\t\tpin_status->next = checked_pins;\n\t\t\tchecked_pins = pin_status;\n\t\t}\n\t}", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_chv_cache_clean(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_pin_status *current = NULL;", "\tLOG_FUNC_CALLED(ctx);", "\tfor(current = checked_pins; current; current = current->next)\n\t\tif (current->reference == pin_cmd->pin_reference)\n\t\t\tbreak;", "\tif (!current)\n\t\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);", "\n\tif (current->next && current->prev) {\n\t\tcurrent->prev->next = current->next;\n\t\tcurrent->next->prev = current->prev;\n\t}\n\telse if (!current->prev) {\n\t\tchecked_pins = current->next;\n\t}\n\telse if (!current->next && current->prev) {\n\t\tcurrent->prev->next = NULL;\n\t}", "\tfree(current);\n\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic struct iasecc_pin_status *\niasecc_chv_cache_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_pin_status *current = NULL;\n\tunsigned char data_sha1[SHA_DIGEST_LENGTH];", "\tLOG_FUNC_CALLED(ctx);", "\tif (pin_cmd->pin1.data)\n\t\tSHA1(pin_cmd->pin1.data, pin_cmd->pin1.len, data_sha1);\n\telse\n\t\tmemset(data_sha1, 0, SHA_DIGEST_LENGTH);\n\tsc_log_hex(ctx, \"data_sha1: %s\", data_sha1, SHA_DIGEST_LENGTH);", "\tfor(current = checked_pins; current; current = current->next)\n\t\tif (current->reference == pin_cmd->pin_reference)\n\t\t\tbreak;", "\tif (current && !memcmp(data_sha1, current->sha1, SHA_DIGEST_LENGTH)) {\n\t\tsc_log(ctx, \"PIN-%i status 'verified'\", pin_cmd->pin_reference);\n\t\treturn current;\n\t}", "\tsc_log(ctx, \"PIN-%i status 'not verified'\", pin_cmd->pin_reference);\n\treturn NULL;\n}", "\nstatic int\niasecc_select_mf(struct sc_card *card, struct sc_file **file_out)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_file *mf_file = NULL;\n\tstruct sc_path path;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);", "\tif (file_out)\n\t\t*file_out = NULL;", "\tmemset(&path, 0, sizeof(struct sc_path));\n\tif (!card->ef_atr || !card->ef_atr->aid.len) {\n\t\tstruct sc_apdu apdu;\n\t\tunsigned char apdu_resp[SC_MAX_APDU_BUFFER_SIZE];", "\t\t/* ISO 'select' command fails when not FCP data returned */\n\t\tsc_format_path(\"3F00\", &path);\n\t\tpath.type = SC_PATH_TYPE_FILE_ID;", "\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 0x00, 0x00);\n\t\tapdu.lc = path.len;\n\t\tapdu.data = path.value;\n\t\tapdu.datalen = path.len;\n\t\tapdu.resplen = sizeof(apdu_resp);\n\t\tapdu.resp = apdu_resp;", "\t\tif (card->type == SC_CARD_TYPE_IASECC_MI2)\n\t\t\tapdu.p2 = 0x04;", "\t\trv = sc_transmit_apdu(card, &apdu);\n\t\tLOG_TEST_RET(card->ctx, rv, \"APDU transmit failed\");\n\t\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\t\tLOG_TEST_RET(card->ctx, rv, \"Cannot select MF\");\n\t}\n\telse {\n\t\tmemset(&path, 0, sizeof(path));\n\t\tpath.type = SC_PATH_TYPE_DF_NAME;\n\t\tmemcpy(path.value, card->ef_atr->aid.value, card->ef_atr->aid.len);\n\t\tpath.len = card->ef_atr->aid.len;\n\t\trv = iasecc_select_file(card, &path, file_out);\n\t\tLOG_TEST_RET(ctx, rv, \"Unable to ROOT selection\");\n\t}", "\t/* Ignore the FCP of the MF, because:\n\t * - some cards do not return it;\n\t * - there is not need of it -- create/delete of the files in MF is not envisaged.\n\t */\n\tmf_file = sc_file_new();\n\tif (mf_file == NULL)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, \"Cannot allocate MF file\");\n\tmf_file->type = SC_FILE_TYPE_DF;\n\tmf_file->path = path;", "\tif (card->cache.valid)\n\t\t sc_file_free(card->cache.current_df);\n\tcard->cache.current_df = NULL;", "\tif (card->cache.valid)\n\t\tsc_file_free(card->cache.current_ef);\n\tcard->cache.current_ef = NULL;", "\tsc_file_dup(&card->cache.current_df, mf_file);\n\tcard->cache.valid = 1;", "\tif (file_out && *file_out == NULL)\n\t\t*file_out = mf_file;\n\telse\n\t\tsc_file_free(mf_file);", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_select_aid(struct sc_card *card, struct sc_aid *aid, unsigned char *out, size_t *out_len)\n{\n\tstruct sc_apdu apdu;\n\tunsigned char apdu_resp[SC_MAX_APDU_BUFFER_SIZE];\n\tint rv;", "\t/* Select application (deselect previously selected application) */\n\tsc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x04, 0x00);\n\tapdu.lc = aid->len;\n\tapdu.data = aid->value;\n\tapdu.datalen = aid->len;\n\tapdu.resplen = sizeof(apdu_resp);\n\tapdu.resp = apdu_resp;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(card->ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(card->ctx, rv, \"Cannot select AID\");", "\tif (*out_len < apdu.resplen)\n\t\tLOG_TEST_RET(card->ctx, SC_ERROR_BUFFER_TOO_SMALL, \"Cannot select AID\");\n\tmemcpy(out, apdu.resp, apdu.resplen);", "\treturn SC_SUCCESS;\n}", "\nstatic int\niasecc_match_card(struct sc_card *card)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tint i;", "\ti = _sc_match_atr(card, iasecc_known_atrs, &card->type);\n\tif (i < 0) {\n\t\tsc_log(ctx, \"card not matched\");\n\t\treturn 0;\n\t}", "\tsc_log(ctx, \"'%s' card matched\", iasecc_known_atrs[i].name);\n\treturn 1;\n}", "\nstatic int iasecc_parse_ef_atr(struct sc_card *card)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_private_data *pdata = (struct iasecc_private_data *) card->drv_data;\n\tstruct iasecc_version *version = &pdata->version;\n\tstruct iasecc_io_buffer_sizes *sizes = &pdata->max_sizes;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\trv = sc_parse_ef_atr(card);\n\tLOG_TEST_RET(ctx, rv, \"MF selection error\");", "\tif (card->ef_atr->pre_issuing_len < 4)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"Invalid pre-issuing data\");", "\tversion->ic_manufacturer =\tcard->ef_atr->pre_issuing[0];\n\tversion->ic_type =\t\tcard->ef_atr->pre_issuing[1];\n\tversion->os_version =\t\tcard->ef_atr->pre_issuing[2];\n\tversion->iasecc_version =\tcard->ef_atr->pre_issuing[3];\n\tsc_log(ctx, \"EF.ATR: IC manufacturer/type %X/%X, OS/IasEcc versions %X/%X\",\n\t\tversion->ic_manufacturer, version->ic_type, version->os_version, version->iasecc_version);", "\tif (card->ef_atr->issuer_data_len < 16)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"Invalid issuer data\");", "\tsizes->send =\t card->ef_atr->issuer_data[2] * 0x100 + card->ef_atr->issuer_data[3];\n\tsizes->send_sc = card->ef_atr->issuer_data[6] * 0x100 + card->ef_atr->issuer_data[7];\n\tsizes->recv =\t card->ef_atr->issuer_data[10] * 0x100 + card->ef_atr->issuer_data[11];\n\tsizes->recv_sc = card->ef_atr->issuer_data[14] * 0x100 + card->ef_atr->issuer_data[15];", "\tcard->max_send_size = sizes->send;\n\tcard->max_recv_size = sizes->recv;", "\t/* Most of the card producers interpret 'send' values as \"maximum APDU data size\".\n\t * Oberthur strictly follows specification and interpret these values as \"maximum APDU command size\".\n\t * Here we need 'data size'.\n\t */\n\tif (card->max_send_size > 0xFF)\n\t\tcard->max_send_size -= 5;", "\tsc_log(ctx,\n\t \"EF.ATR: max send/recv sizes %\"SC_FORMAT_LEN_SIZE_T\"X/%\"SC_FORMAT_LEN_SIZE_T\"X\",\n\t card->max_send_size, card->max_recv_size);", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_init_gemalto(struct sc_card *card)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_path path;\n\tunsigned int flags;\n\tint rv = 0;", "\tLOG_FUNC_CALLED(ctx);", "\tflags = IASECC_CARD_DEFAULT_FLAGS;", "\t_sc_card_add_rsa_alg(card, 1024, flags, 0x10001);\n\t_sc_card_add_rsa_alg(card, 2048, flags, 0x10001);", "\tcard->caps = SC_CARD_CAP_RNG;\n\tcard->caps |= SC_CARD_CAP_APDU_EXT;\n\tcard->caps |= SC_CARD_CAP_USE_FCI_AC;", "\tsc_format_path(\"3F00\", &path);\n\trv = sc_select_file(card, &path, NULL);\n\t/* Result ignored*/", "\trv = iasecc_parse_ef_atr(card);\n\tsc_log(ctx, \"rv %i\", rv);\n\tif (rv == SC_ERROR_FILE_NOT_FOUND) {\n\t\tsc_log(ctx, \"Select MF\");\n\t\trv = iasecc_select_mf(card, NULL);\n\t\tsc_log(ctx, \"rv %i\", rv);\n\t\tLOG_TEST_RET(ctx, rv, \"MF selection error\");", "\t\trv = iasecc_parse_ef_atr(card);\n\t\tsc_log(ctx, \"rv %i\", rv);\n\t}\n\tsc_log(ctx, \"rv %i\", rv);\n\tLOG_TEST_RET(ctx, rv, \"Cannot read/parse EF.ATR\");", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_oberthur_match(struct sc_card *card)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tunsigned char *hist = card->reader->atr_info.hist_bytes;", "\tLOG_FUNC_CALLED(ctx);", "\tif (*hist != 0x80 || ((*(hist+1)&0xF0) != 0xF0))\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_OBJECT_NOT_FOUND);", "\tsc_log_hex(ctx, \"AID in historical_bytes\", hist + 2, *(hist+1) & 0x0F);", "\tif (memcmp(hist + 2, OberthurIASECC_AID.value, *(hist+1) & 0x0F))\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_RECORD_NOT_FOUND);", "\tif (!card->ef_atr)\n\t\tcard->ef_atr = calloc(1, sizeof(struct sc_ef_atr));\n\tif (!card->ef_atr)\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);", "\tmemcpy(card->ef_atr->aid.value, OberthurIASECC_AID.value, OberthurIASECC_AID.len);\n\tcard->ef_atr->aid.len = OberthurIASECC_AID.len;", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_init_oberthur(struct sc_card *card)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tunsigned int flags;\n\tint rv = 0;", "\tLOG_FUNC_CALLED(ctx);", "\tflags = IASECC_CARD_DEFAULT_FLAGS;", "\t_sc_card_add_rsa_alg(card, 1024, flags, 0x10001);\n\t_sc_card_add_rsa_alg(card, 2048, flags, 0x10001);", "\tcard->caps = SC_CARD_CAP_RNG;\n\tcard->caps |= SC_CARD_CAP_APDU_EXT;\n\tcard->caps |= SC_CARD_CAP_USE_FCI_AC;", "\tiasecc_parse_ef_atr(card);", "\t/* if we fail to select CM, */\n\tif (gp_select_card_manager(card)) {\n\t\tgp_select_isd_rid(card);\n\t}", "\trv = iasecc_oberthur_match(card);\n\tLOG_TEST_RET(ctx, rv, \"unknown Oberthur's IAS/ECC card\");", "\trv = iasecc_select_mf(card, NULL);\n\tLOG_TEST_RET(ctx, rv, \"MF selection error\");", "\trv = iasecc_parse_ef_atr(card);\n\tLOG_TEST_RET(ctx, rv, \"EF.ATR read or parse error\");", "\tsc_log(ctx, \"EF.ATR(aid:'%s')\", sc_dump_hex(card->ef_atr->aid.value, card->ef_atr->aid.len));\n\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_mi_match(struct sc_card *card)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tunsigned char resp[0x100];\n\tsize_t resp_len;\n\tint rv = 0;", "\tLOG_FUNC_CALLED(ctx);", "\tresp_len = sizeof(resp);\n\trv = iasecc_select_aid(card, &MIIASECC_AID, resp, &resp_len);\n\tLOG_TEST_RET(ctx, rv, \"IASECC: failed to select MI IAS/ECC applet\");", "\tif (!card->ef_atr)\n\t\tcard->ef_atr = calloc(1, sizeof(struct sc_ef_atr));\n\tif (!card->ef_atr)\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);", "\tmemcpy(card->ef_atr->aid.value, MIIASECC_AID.value, MIIASECC_AID.len);\n\tcard->ef_atr->aid.len = MIIASECC_AID.len;", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_init_amos_or_sagem(struct sc_card *card)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tunsigned int flags;\n\tint rv = 0;", "\tLOG_FUNC_CALLED(ctx);", "\tflags = IASECC_CARD_DEFAULT_FLAGS;", "\t_sc_card_add_rsa_alg(card, 1024, flags, 0x10001);\n\t_sc_card_add_rsa_alg(card, 2048, flags, 0x10001);", "\tcard->caps = SC_CARD_CAP_RNG;\n\tcard->caps |= SC_CARD_CAP_APDU_EXT;\n\tcard->caps |= SC_CARD_CAP_USE_FCI_AC;", "\tif (card->type == SC_CARD_TYPE_IASECC_MI) {\n\t\trv = iasecc_mi_match(card);\n\t\tif (rv)\n\t\t\tcard->type = SC_CARD_TYPE_IASECC_MI2;\n\t\telse\n\t\t\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n\t}", "\trv = iasecc_parse_ef_atr(card);\n\tif (rv == SC_ERROR_FILE_NOT_FOUND) {\n\t\trv = iasecc_select_mf(card, NULL);\n\t\tLOG_TEST_RET(ctx, rv, \"MF selection error\");", "\t\trv = iasecc_parse_ef_atr(card);\n\t}\n\tLOG_TEST_RET(ctx, rv, \"IASECC: ATR parse failed\");", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_init(struct sc_card *card)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_private_data *private_data = NULL;\n\tint rv = SC_ERROR_NO_CARD_SUPPORT;", "\tLOG_FUNC_CALLED(ctx);\n\tprivate_data = (struct iasecc_private_data *) calloc(1, sizeof(struct iasecc_private_data));\n\tif (private_data == NULL)\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);", "\tcard->cla = 0x00;\n\tcard->drv_data = private_data;", "\tif (card->type == SC_CARD_TYPE_IASECC_GEMALTO)\n\t\trv = iasecc_init_gemalto(card);\n\telse if (card->type == SC_CARD_TYPE_IASECC_OBERTHUR)\n\t\trv = iasecc_init_oberthur(card);\n\telse if (card->type == SC_CARD_TYPE_IASECC_SAGEM)\n\t\trv = iasecc_init_amos_or_sagem(card);\n\telse if (card->type == SC_CARD_TYPE_IASECC_AMOS)\n\t\trv = iasecc_init_amos_or_sagem(card);\n\telse if (card->type == SC_CARD_TYPE_IASECC_MI)\n\t\trv = iasecc_init_amos_or_sagem(card);\n\telse\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_CARD);", "\n\tif (!rv) {\n\t\tif (card->ef_atr && card->ef_atr->aid.len) {\n\t\t\tstruct sc_path path;", "\t\t\tmemset(&path, 0, sizeof(struct sc_path));\n\t\t\tpath.type = SC_PATH_TYPE_DF_NAME;\n\t\t\tmemcpy(path.value, card->ef_atr->aid.value, card->ef_atr->aid.len);\n\t\t\tpath.len = card->ef_atr->aid.len;", "\t\t\trv = iasecc_select_file(card, &path, NULL);\n\t\t\tsc_log(ctx, \"Select ECC ROOT with the AID from EF.ATR: rv %i\", rv);\n\t\t\tLOG_TEST_RET(ctx, rv, \"Select EF.ATR AID failed\");\n\t\t}", "\t\trv = iasecc_get_serialnr(card, NULL);\n\t}", "#ifdef ENABLE_SM\n\tcard->sm_ctx.ops.read_binary = _iasecc_sm_read_binary;\n\tcard->sm_ctx.ops.update_binary = _iasecc_sm_update_binary;\n#endif", "\tif (!rv) {\n\t\tsc_log(ctx, \"EF.ATR(aid:'%s')\", sc_dump_hex(card->ef_atr->aid.value, card->ef_atr->aid.len));\n\t\trv = SC_ERROR_INVALID_CARD;\n\t}\n\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_read_binary(struct sc_card *card, unsigned int offs,\n\t\tunsigned char *buf, size_t count, unsigned long flags)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_apdu apdu;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx,\n\t \"iasecc_read_binary(card:%p) offs %i; count %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t card, offs, count);\n\tif (offs > 0x7fff) {\n\t\tsc_log(ctx, \"invalid EF offset: 0x%X > 0x7FFF\", offs);\n\t\treturn SC_ERROR_OFFSET_TOO_LARGE;\n\t}", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xB0, (offs >> 8) & 0x7F, offs & 0xFF);\n\tapdu.le = count < 0x100 ? count : 0x100;\n\tapdu.resplen = count;\n\tapdu.resp = buf;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"iasecc_read_binary() failed\");\n\tsc_log(ctx,\n\t \"iasecc_read_binary() apdu.resplen %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t apdu.resplen);", "\tif (apdu.resplen == IASECC_READ_BINARY_LENGTH_MAX && apdu.resplen < count) {\n\t\trv = iasecc_read_binary(card, offs + apdu.resplen, buf + apdu.resplen, count - apdu.resplen, flags);\n\t\tif (rv != SC_ERROR_WRONG_LENGTH) {\n\t\t\tLOG_TEST_RET(ctx, rv, \"iasecc_read_binary() read tail failed\");\n\t\t\tapdu.resplen += rv;\n\t\t}\n\t}", "\tLOG_FUNC_RETURN(ctx, apdu.resplen);\n}", "\nstatic int\niasecc_erase_binary(struct sc_card *card, unsigned int offs, size_t count, unsigned long flags)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tunsigned char *tmp = NULL;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx,\n\t \"iasecc_erase_binary(card:%p) count %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t card, count);\n\tif (!count)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"'ERASE BINARY' failed: invalid size to erase\");", "\ttmp = malloc(count);\n\tif (!tmp)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, \"Cannot allocate temporary buffer\");\n\tmemset(tmp, 0xFF, count);", "\trv = sc_update_binary(card, offs, tmp, count, flags);\n\tfree(tmp);\n\tLOG_TEST_RET(ctx, rv, \"iasecc_erase_binary() update binary error\");\n\tLOG_FUNC_RETURN(ctx, rv);\n}", "\n#if ENABLE_SM\nstatic int\n_iasecc_sm_read_binary(struct sc_card *card, unsigned int offs,\n\t\tunsigned char *buff, size_t count)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tconst struct sc_acl_entry *entry = NULL;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx,\n\t \"iasecc_sm_read_binary() card:%p offs:%i count:%\"SC_FORMAT_LEN_SIZE_T\"u \",\n\t card, offs, count);\n\tif (offs > 0x7fff)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_OFFSET_TOO_LARGE, \"Invalid arguments\");", "\tif (count == 0)\n\t\treturn 0;", "\tsc_print_cache(card);", "\tif (card->cache.valid && card->cache.current_ef) {\n\t\tentry = sc_file_get_acl_entry(card->cache.current_ef, SC_AC_OP_READ);\n\t\tif (!entry)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, \"iasecc_sm_read() 'READ' ACL not present\");", "\t\tsc_log(ctx, \"READ method/reference %X/%X\", entry->method, entry->key_ref);\n\t\tif ((entry->method == SC_AC_SCB) && (entry->key_ref & IASECC_SCB_METHOD_SM)) {\n\t\t\tunsigned char se_num = (entry->method == SC_AC_SCB) ? (entry->key_ref & IASECC_SCB_METHOD_MASK_REF) : 0;", "\t\t\trv = iasecc_sm_read_binary(card, se_num, offs, buff, count);\n\t\t\tLOG_FUNC_RETURN(ctx, rv);\n\t\t}\n\t}", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\n_iasecc_sm_update_binary(struct sc_card *card, unsigned int offs,\n\t\tconst unsigned char *buff, size_t count)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tconst struct sc_acl_entry *entry = NULL;\n\tint rv;", "\tif (count == 0)\n\t\treturn SC_SUCCESS;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx,\n\t \"iasecc_sm_read_binary() card:%p offs:%i count:%\"SC_FORMAT_LEN_SIZE_T\"u \",\n\t card, offs, count);\n\tsc_print_cache(card);", "\tif (card->cache.valid && card->cache.current_ef) {\n\t\tentry = sc_file_get_acl_entry(card->cache.current_ef, SC_AC_OP_UPDATE);\n\t\tif (!entry)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, \"iasecc_sm_update() 'UPDATE' ACL not present\");", "\t\tsc_log(ctx, \"UPDATE method/reference %X/%X\", entry->method, entry->key_ref);\n\t\tif (entry->method == SC_AC_SCB && (entry->key_ref & IASECC_SCB_METHOD_SM)) {\n\t\t\tunsigned char se_num = entry->method == SC_AC_SCB ? entry->key_ref & IASECC_SCB_METHOD_MASK_REF : 0;", "\t\t\trv = iasecc_sm_update_binary(card, se_num, offs, buff, count);\n\t\t\tLOG_FUNC_RETURN(ctx, rv);\n\t\t}\n\t}", "\tLOG_FUNC_RETURN(ctx, 0);\n}\n#endif", "\nstatic int\niasecc_emulate_fcp(struct sc_context *ctx, struct sc_apdu *apdu)\n{\n\tunsigned char dummy_df_fcp[] = {\n\t\t0x62,0xFF,\n\t\t\t0x82,0x01,0x38,\n\t\t\t0x8A,0x01,0x05,\n\t\t\t0xA1,0x04,0x8C,0x02,0x02,0x00,\n\t\t\t0x84,0xFF,\n\t\t\t\t0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,\n\t\t\t\t0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF\n\t};", "\tLOG_FUNC_CALLED(ctx);", "\tif (apdu->p1 != 0x04)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"FCP emulation supported only for the DF-NAME selection type\");\n\tif (apdu->datalen > 16)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"Invalid DF-NAME length\");\n\tif (apdu->resplen < apdu->datalen + 16)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, \"not enough space for FCP data\");", "\tmemcpy(dummy_df_fcp + 16, apdu->data, apdu->datalen);\n\tdummy_df_fcp[15] = apdu->datalen;\n\tdummy_df_fcp[1] = apdu->datalen + 14;\n\tmemcpy(apdu->resp, dummy_df_fcp, apdu->datalen + 16);", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\n/* TODO: redesign using of cache\n * TODO: do not keep intermediate results in 'file_out' argument */\nstatic int\niasecc_select_file(struct sc_card *card, const struct sc_path *path,\n\t\t struct sc_file **file_out)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_path lpath;\n\tint cache_valid = card->cache.valid, df_from_cache = 0;\n\tint rv, ii;", "\tLOG_FUNC_CALLED(ctx);\n\tmemcpy(&lpath, path, sizeof(struct sc_path));\n\tif (file_out)\n\t\t*file_out = NULL;", "\tsc_log(ctx,\n\t \"iasecc_select_file(card:%p) path.len %\"SC_FORMAT_LEN_SIZE_T\"u; path.type %i; aid_len %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t card, path->len, path->type, path->aid.len);\n\tsc_log(ctx, \"iasecc_select_file() path:%s\", sc_print_path(path));", "\tsc_print_cache(card);", "\tif (lpath.len >= 2 && lpath.value[0] == 0x3F && lpath.value[1] == 0x00) {", "\t\tsc_log(ctx, \"EF.ATR(aid:'%s')\", card->ef_atr ? sc_dump_hex(card->ef_atr->aid.value, card->ef_atr->aid.len) : \"\");", "\t\trv = iasecc_select_mf(card, file_out);\n\t\tLOG_TEST_RET(ctx, rv, \"MF selection error\");\n", "\t\tif (lpath.len >= 2 && lpath.value[0] == 0x3F && lpath.value[1] == 0x00)\t {\n\t\t\tmemmove(&lpath.value[0], &lpath.value[2], lpath.len - 2);\n\t\t\tlpath.len -= 2;\n\t\t}", "\t}", "\tif (lpath.aid.len)\t{\n\t\tstruct sc_file *file = NULL;\n\t\tstruct sc_path ppath;", "\t\tsc_log(ctx,\n\t\t \"iasecc_select_file() select parent AID:%p/%\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t\t lpath.aid.value, lpath.aid.len);\n\t\tsc_log(ctx, \"iasecc_select_file() select parent AID:%s\", sc_dump_hex(lpath.aid.value, lpath.aid.len));\n\t\tmemset(&ppath, 0, sizeof(ppath));\n\t\tmemcpy(ppath.value, lpath.aid.value, lpath.aid.len);\n\t\tppath.len = lpath.aid.len;\n\t\tppath.type = SC_PATH_TYPE_DF_NAME;", "\t\tif (card->cache.valid && card->cache.current_df\n\t\t\t\t&& card->cache.current_df->path.len == lpath.aid.len\n\t\t\t\t&& !memcmp(card->cache.current_df->path.value, lpath.aid.value, lpath.aid.len))\n\t\t\tdf_from_cache = 1;", "\t\trv = iasecc_select_file(card, &ppath, &file);\n\t\tLOG_TEST_RET(ctx, rv, \"select AID path failed\");", "\t\tif (file_out)\n\t\t\t*file_out = file;\n\t\telse\n\t\t sc_file_free(file);", "\t\tif (lpath.type == SC_PATH_TYPE_DF_NAME)\n\t\t\tlpath.type = SC_PATH_TYPE_FROM_CURRENT;\n\t}", "\tif (lpath.type == SC_PATH_TYPE_PATH)\n\t\tlpath.type = SC_PATH_TYPE_FROM_CURRENT;", "\tif (!lpath.len)\n\t\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);", "\tsc_print_cache(card);", "\tif (card->cache.valid && card->cache.current_df && lpath.type == SC_PATH_TYPE_DF_NAME\n\t\t\t&& card->cache.current_df->path.len == lpath.len\n\t\t\t&& !memcmp(card->cache.current_df->path.value, lpath.value, lpath.len)) {\n\t\tsc_log(ctx, \"returns current DF path %s\", sc_print_path(&card->cache.current_df->path));\n\t\tif (file_out) {\n\t\t\tsc_file_free(*file_out);\n\t\t\tsc_file_dup(file_out, card->cache.current_df);\n\t\t}", "\t\tsc_print_cache(card);\n\t\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n\t}", "\tdo {\n\t\tstruct sc_apdu apdu;\n\t\tstruct sc_file *file = NULL;\n\t\tunsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE];\n\t\tint pathlen = lpath.len;", "\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00);", "\t\tif (card->type != SC_CARD_TYPE_IASECC_GEMALTO\n\t\t\t\t&& card->type != SC_CARD_TYPE_IASECC_OBERTHUR\n\t\t\t\t&& card->type != SC_CARD_TYPE_IASECC_SAGEM\n\t\t\t\t&& card->type != SC_CARD_TYPE_IASECC_AMOS\n\t\t\t\t&& card->type != SC_CARD_TYPE_IASECC_MI\n\t\t\t\t&& card->type != SC_CARD_TYPE_IASECC_MI2)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Unsupported card\");", "\t\tif (lpath.type == SC_PATH_TYPE_FILE_ID) {\n\t\t\tapdu.p1 = 0x02;\n\t\t\tif (card->type == SC_CARD_TYPE_IASECC_OBERTHUR) {\n\t\t\t\tapdu.p1 = 0x01;\n\t\t\t\tapdu.p2 = 0x04;\n\t\t\t}\n\t\t\tif (card->type == SC_CARD_TYPE_IASECC_AMOS)\n\t\t\t\tapdu.p2 = 0x04;\n\t\t\tif (card->type == SC_CARD_TYPE_IASECC_MI)\n\t\t\t\tapdu.p2 = 0x04;\n\t\t\tif (card->type == SC_CARD_TYPE_IASECC_MI2)\n\t\t\t\tapdu.p2 = 0x04;\n\t\t}\n\t\telse if (lpath.type == SC_PATH_TYPE_FROM_CURRENT) {\n\t\t\tapdu.p1 = 0x09;\n\t\t\tif (card->type == SC_CARD_TYPE_IASECC_OBERTHUR)\n\t\t\t\tapdu.p2 = 0x04;\n\t\t\tif (card->type == SC_CARD_TYPE_IASECC_AMOS)\n\t\t\t\tapdu.p2 = 0x04;\n\t\t\tif (card->type == SC_CARD_TYPE_IASECC_MI)\n\t\t\t\tapdu.p2 = 0x04;\n\t\t\tif (card->type == SC_CARD_TYPE_IASECC_MI2)\n\t\t\t\tapdu.p2 = 0x04;\n\t\t}\n\t\telse if (lpath.type == SC_PATH_TYPE_PARENT) {\n\t\t\tapdu.p1 = 0x03;\n\t\t\tpathlen = 0;\n\t\t\tapdu.cse = SC_APDU_CASE_2_SHORT;\n\t\t}\n\t\telse if (lpath.type == SC_PATH_TYPE_DF_NAME) {\n\t\t\tapdu.p1 = 0x04;\n\t\t\tif (card->type == SC_CARD_TYPE_IASECC_AMOS)\n\t\t\t\tapdu.p2 = 0x04;\n\t\t\tif (card->type == SC_CARD_TYPE_IASECC_MI2)\n\t\t\t\tapdu.p2 = 0x04;\n\t\t}\n\t\telse {\n\t\t\tsc_log(ctx, \"Invalid PATH type: 0x%X\", lpath.type);\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"iasecc_select_file() invalid PATH type\");\n\t\t}", "\t\tfor (ii=0; ii<2; ii++) {\n\t\t\tapdu.lc = pathlen;\n\t\t\tapdu.data = lpath.value;\n\t\t\tapdu.datalen = pathlen;", "\t\t\tapdu.resp = rbuf;\n\t\t\tapdu.resplen = sizeof(rbuf);\n\t\t\tapdu.le = 256;", "\t\t\trv = sc_transmit_apdu(card, &apdu);\n\t\t\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\t\t\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\t\t\tif (rv == SC_ERROR_INCORRECT_PARAMETERS &&\n\t\t\t\t\tlpath.type == SC_PATH_TYPE_DF_NAME && apdu.p2 == 0x00) {\n\t\t\t\tapdu.p2 = 0x0C;\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tif (ii) {\n\t\t\t\t/* 'SELECT AID' do not returned FCP. Try to emulate. */\n\t\t\t\tapdu.resplen = sizeof(rbuf);\n\t\t\t\trv = iasecc_emulate_fcp(ctx, &apdu);\n\t\t\t\tLOG_TEST_RET(ctx, rv, \"Failed to emulate DF FCP\");\n\t\t\t}", "\t\t\tbreak;\n\t\t}", "\t\t/*\n\t\t * Using of the cached DF and EF can cause problems in the multi-thread environment.\n\t\t * FIXME: introduce config. option that invalidates this cache outside the locked card session,\n\t\t * (or invent something else)\n\t\t */\n\t\tif (rv == SC_ERROR_FILE_NOT_FOUND && cache_valid && df_from_cache) {\n\t\t\tsc_invalidate_cache(card);\n\t\t\tsc_log(ctx, \"iasecc_select_file() file not found, retry without cached DF\");\n\t\t\tif (file_out) {\n\t\t\t\tsc_file_free(*file_out);\n\t\t\t\t*file_out = NULL;\n\t\t\t}\n\t\t\trv = iasecc_select_file(card, path, file_out);\n\t\t\tLOG_FUNC_RETURN(ctx, rv);\n\t\t}", "\t\tLOG_TEST_RET(ctx, rv, \"iasecc_select_file() check SW failed\");", "\t\tsc_log(ctx,\n\t\t \"iasecc_select_file() apdu.resp %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t\t apdu.resplen);\n\t\tif (apdu.resplen) {\n\t\t\tsc_log(ctx, \"apdu.resp %02X:%02X:%02X...\", apdu.resp[0], apdu.resp[1], apdu.resp[2]);", "\t\t\tswitch (apdu.resp[0]) {\n\t\t\tcase 0x62:\n\t\t\tcase 0x6F:\n\t\t\t\tfile = sc_file_new();\n\t\t\t\tif (file == NULL)\n\t\t\t\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);\n\t\t\t\tfile->path = lpath;", "\t\t\t\trv = iasecc_process_fci(card, file, apdu.resp, apdu.resplen);\n\t\t\t\tif (rv)\n\t\t\t\t\tLOG_FUNC_RETURN(ctx, rv);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);\n\t\t\t}", "\t\t\tsc_log(ctx, \"FileType %i\", file->type);\n\t\t\tif (file->type == SC_FILE_TYPE_DF) {\n\t\t\t\tif (card->cache.valid)\n\t\t\t\t\tsc_file_free(card->cache.current_df);\n\t\t\t\tcard->cache.current_df = NULL;", "\n\t\t\t\tif (card->cache.valid)\n\t\t\t\t\tsc_file_free(card->cache.current_ef);\n\t\t\t\tcard->cache.current_ef = NULL;", "\t\t\t\tsc_file_dup(&card->cache.current_df, file);\n\t\t\t\tcard->cache.valid = 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (card->cache.valid)\n\t\t\t\t\tsc_file_free(card->cache.current_ef);", "\t\t\t\tcard->cache.current_ef = NULL;", "\t\t\t\tsc_file_dup(&card->cache.current_ef, file);\n\t\t\t}", "\t\t\tif (file_out) {\n\t\t\t\tsc_file_free(*file_out);\n\t\t\t\t*file_out = file;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsc_file_free(file);\n\t\t\t}\n\t\t}\n\t\telse if (lpath.type == SC_PATH_TYPE_DF_NAME) {\n\t\t\tsc_file_free(card->cache.current_df);\n\t\t\tcard->cache.current_df = NULL;", "\t\t\tsc_file_free(card->cache.current_ef);\n\t\t\tcard->cache.current_ef = NULL;", "\t\t\tcard->cache.valid = 1;\n\t\t}\n\t} while(0);", "\tsc_print_cache(card);\n\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_process_fci(struct sc_card *card, struct sc_file *file,\n\t\t const unsigned char *buf, size_t buflen)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tsize_t taglen;\n\tint rv, ii, offs;\n\tconst unsigned char *acls = NULL, *tag = NULL;\n\tunsigned char mask;\n\tunsigned char ops_DF[7] = {\n\t\tSC_AC_OP_DELETE, 0xFF, SC_AC_OP_ACTIVATE, SC_AC_OP_DEACTIVATE, 0xFF, SC_AC_OP_CREATE, 0xFF\n\t};\n\tunsigned char ops_EF[7] = {\n\t\tSC_AC_OP_DELETE, 0xFF, SC_AC_OP_ACTIVATE, SC_AC_OP_DEACTIVATE, 0xFF, SC_AC_OP_UPDATE, SC_AC_OP_READ\n\t};", "\tLOG_FUNC_CALLED(ctx);", "\ttag = sc_asn1_find_tag(ctx, buf, buflen, 0x6F, &taglen);\n\tsc_log(ctx, \"processing FCI: 0x6F tag %p\", tag);\n\tif (tag != NULL) {\n\t\tsc_log(ctx, \" FCP length %\"SC_FORMAT_LEN_SIZE_T\"u\", taglen);\n\t\tbuf = tag;\n\t\tbuflen = taglen;\n\t}", "\ttag = sc_asn1_find_tag(ctx, buf, buflen, 0x62, &taglen);\n\tsc_log(ctx, \"processing FCI: 0x62 tag %p\", tag);\n\tif (tag != NULL) {\n\t\tsc_log(ctx, \" FCP length %\"SC_FORMAT_LEN_SIZE_T\"u\", taglen);\n\t\tbuf = tag;\n\t\tbuflen = taglen;\n\t}", "\trv = iso_ops->process_fci(card, file, buf, buflen);\n\tLOG_TEST_RET(ctx, rv, \"ISO parse FCI failed\");\n/*\n\tGemalto: 6F 19 80 02 02 ED 82 01 01 83 02 B0 01 88 00\t8C 07 7B 17 17 17 17 17 00 8A 01 05 90 00\n\tSagem: 6F 17 62 15 80 02 00 7D 82 01 01 8C 02 01 00 83 02 2F 00 88 01 F0 8A 01 05 90 00\n\tOberthur: 62 1B 80 02 05 DC 82 01 01 83 02 B0 01 88 00 A1 09 8C 07 7B 17 FF 17 17 17 00 8A 01 05 90 00\n*/", "\tsc_log(ctx, \"iasecc_process_fci() type %i; let's parse file ACLs\", file->type);\n\ttag = sc_asn1_find_tag(ctx, buf, buflen, IASECC_DOCP_TAG_ACLS, &taglen);\n\tif (tag)\n\t\tacls = sc_asn1_find_tag(ctx, tag, taglen, IASECC_DOCP_TAG_ACLS_CONTACT, &taglen);\n\telse\n\t\tacls = sc_asn1_find_tag(ctx, buf, buflen, IASECC_DOCP_TAG_ACLS_CONTACT, &taglen);", "\tif (!acls) {\n\t\tsc_log(ctx,\n\t\t \"ACLs not found in data(%\"SC_FORMAT_LEN_SIZE_T\"u) %s\",\n\t\t buflen, sc_dump_hex(buf, buflen));\n\t\tLOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, \"ACLs tag missing\");\n\t}", "\tsc_log(ctx, \"ACLs(%\"SC_FORMAT_LEN_SIZE_T\"u) '%s'\", taglen,\n\t sc_dump_hex(acls, taglen));\n\tmask = 0x40, offs = 1;\n\tfor (ii = 0; ii < 7; ii++, mask /= 2) {\n\t\tunsigned char op = file->type == SC_FILE_TYPE_DF ? ops_DF[ii] : ops_EF[ii];", "\t\tif (!(mask & acls[0]))\n\t\t\tcontinue;", "\t\tsc_log(ctx, \"ACLs mask 0x%X, offs %i, op 0x%X, acls[offs] 0x%X\", mask, offs, op, acls[offs]);\n\t\tif (op == 0xFF) {\n\t\t\t;\n\t\t}\n\t\telse if (acls[offs] == 0) {\n\t\t\tsc_file_add_acl_entry(file, op, SC_AC_NONE, 0);\n\t\t}\n\t\telse if (acls[offs] == 0xFF) {\n\t\t\tsc_file_add_acl_entry(file, op, SC_AC_NEVER, 0);\n\t\t}\n\t\telse if ((acls[offs] & IASECC_SCB_METHOD_MASK) == IASECC_SCB_METHOD_USER_AUTH) {\n\t\t\tsc_file_add_acl_entry(file, op, SC_AC_SEN, acls[offs] & IASECC_SCB_METHOD_MASK_REF);\n\t\t}\n\t\telse if (acls[offs] & IASECC_SCB_METHOD_MASK) {\n\t\t\tsc_file_add_acl_entry(file, op, SC_AC_SCB, acls[offs]);\n\t\t}\n\t\telse {\n\t\t\tsc_log(ctx, \"Warning: non supported SCB method: %X\", acls[offs]);\n\t\t\tsc_file_add_acl_entry(file, op, SC_AC_NEVER, 0);\n\t\t}", "\t\toffs++;\n\t}", "\tLOG_FUNC_RETURN(ctx, 0);\n}", "\nstatic int\niasecc_fcp_encode(struct sc_card *card, struct sc_file *file, unsigned char *out, size_t out_len)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tunsigned char buf[0x80], type;\n\tunsigned char ops[7] = {\n\t\tSC_AC_OP_DELETE, 0xFF, SC_AC_OP_ACTIVATE, SC_AC_OP_DEACTIVATE, 0xFF, SC_AC_OP_UPDATE, SC_AC_OP_READ\n\t};\n\tunsigned char smbs[8];\n\tsize_t ii, offs = 0, amb, mask, nn_smb;", "\tLOG_FUNC_CALLED(ctx);", "\tif (file->type == SC_FILE_TYPE_DF)\n\t\ttype = IASECC_FCP_TYPE_DF;\n\telse\n\t\ttype = IASECC_FCP_TYPE_EF;", "\tbuf[offs++] = IASECC_FCP_TAG_SIZE;\n\tbuf[offs++] = 2;\n\tbuf[offs++] = (file->size >> 8) & 0xFF;\n\tbuf[offs++] = file->size & 0xFF;", "\tbuf[offs++] = IASECC_FCP_TAG_TYPE;\n\tbuf[offs++] = 1;\n\tbuf[offs++] = type;", "\tbuf[offs++] = IASECC_FCP_TAG_FID;\n\tbuf[offs++] = 2;\n\tbuf[offs++] = (file->id >> 8) & 0xFF;\n\tbuf[offs++] = file->id & 0xFF;", "\tbuf[offs++] = IASECC_FCP_TAG_SFID;\n\tbuf[offs++] = 0;", "\tamb = 0, mask = 0x40, nn_smb = 0;\n\tfor (ii = 0; ii < sizeof(ops); ii++, mask >>= 1) {\n\t\tconst struct sc_acl_entry *entry;", "\t\tif (ops[ii]==0xFF)\n\t\t\tcontinue;", "\t\tentry = sc_file_get_acl_entry(file, ops[ii]);\n\t\tif (!entry)\n\t\t\tcontinue;", "\t\tsc_log(ctx, \"method %X; reference %X\", entry->method, entry->key_ref);\n\t\tif (entry->method == SC_AC_NEVER)\n\t\t\tcontinue;\n\t\telse if (entry->method == SC_AC_NONE)\n\t\t\tsmbs[nn_smb++] = 0x00;\n\t\telse if (entry->method == SC_AC_CHV)\n\t\t\tsmbs[nn_smb++] = entry->key_ref | IASECC_SCB_METHOD_USER_AUTH;\n\t\telse if (entry->method == SC_AC_SEN)\n\t\t\tsmbs[nn_smb++] = entry->key_ref | IASECC_SCB_METHOD_USER_AUTH;\n\t\telse if (entry->method == SC_AC_SCB)\n\t\t\tsmbs[nn_smb++] = entry->key_ref;\n\t\telse if (entry->method == SC_AC_PRO)\n\t\t\tsmbs[nn_smb++] = entry->key_ref | IASECC_SCB_METHOD_SM;\n\t\telse\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Non supported AC method\");", "\t\tamb |= mask;\n\t\tsc_log(ctx,\n\t\t \"%\"SC_FORMAT_LEN_SIZE_T\"u: AMB %\"SC_FORMAT_LEN_SIZE_T\"X; nn_smb %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t\t ii, amb, nn_smb);\n\t}", "\t/* TODO: Encode contactless ACLs and life cycle status for all IAS/ECC cards */\n\tif (card->type == SC_CARD_TYPE_IASECC_SAGEM ||\n\t\t\tcard->type == SC_CARD_TYPE_IASECC_AMOS ) {\n\t\tunsigned char status = 0;", "\t\tbuf[offs++] = IASECC_FCP_TAG_ACLS;\n\t\tbuf[offs++] = 2*(2 + 1 + nn_smb);", "\t\tbuf[offs++] = IASECC_FCP_TAG_ACLS_CONTACT;\n\t\tbuf[offs++] = nn_smb + 1;\n\t\tbuf[offs++] = amb;\n\t\tmemcpy(buf + offs, smbs, nn_smb);\n\t\toffs += nn_smb;", "\t\t/* Same ACLs for contactless */\n\t\tbuf[offs++] = IASECC_FCP_TAG_ACLS_CONTACTLESS;\n\t\tbuf[offs++] = nn_smb + 1;\n\t\tbuf[offs++] = amb;\n\t\tmemcpy(buf + offs, smbs, nn_smb);\n\t\toffs += nn_smb;", "\t\tif (file->status == SC_FILE_STATUS_ACTIVATED)\n\t\t\tstatus = 0x05;\n\t\telse if (file->status == SC_FILE_STATUS_CREATION)\n\t\t\tstatus = 0x01;", "\t\tif (status) {\n\t\t\tbuf[offs++] = 0x8A;\n\t\t\tbuf[offs++] = 0x01;\n\t\t\tbuf[offs++] = status;\n\t\t}\n\t}\n\telse {\n\t\tbuf[offs++] = IASECC_FCP_TAG_ACLS;\n\t\tbuf[offs++] = 2 + 1 + nn_smb;", "\t\tbuf[offs++] = IASECC_FCP_TAG_ACLS_CONTACT;\n\t\tbuf[offs++] = nn_smb + 1;\n\t\tbuf[offs++] = amb;\n\t\tmemcpy(buf + offs, smbs, nn_smb);\n\t\toffs += nn_smb;\n\t}", "\tif (out) {\n\t\tif (out_len < offs)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, \"Buffer too small to encode FCP\");\n\t\tmemcpy(out, buf, offs);\n\t}", "\tLOG_FUNC_RETURN(ctx, offs);\n}", "\nstatic int\niasecc_create_file(struct sc_card *card, struct sc_file *file)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_apdu apdu;\n\tconst struct sc_acl_entry *entry = NULL;\n\tunsigned char sbuf[0x100];\n\tsize_t sbuf_len;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_print_cache(card);", "\tif (file->type != SC_FILE_TYPE_WORKING_EF)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Creation of the file with of this type is not supported\");", "\tsbuf_len = iasecc_fcp_encode(card, file, sbuf + 2, sizeof(sbuf)-2);\n\tLOG_TEST_RET(ctx, sbuf_len, \"FCP encode error\");", "\tsbuf[0] = IASECC_FCP_TAG;\n\tsbuf[1] = sbuf_len;", "\tif (card->cache.valid && card->cache.current_df) {\n\t\tentry = sc_file_get_acl_entry(card->cache.current_df, SC_AC_OP_CREATE);\n\t\tif (!entry)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, \"iasecc_create_file() 'CREATE' ACL not present\");", "\t\tsc_log(ctx, \"iasecc_create_file() 'CREATE' method/reference %X/%X\", entry->method, entry->key_ref);\n\t\tsc_log(ctx, \"iasecc_create_file() create data: '%s'\", sc_dump_hex(sbuf, sbuf_len + 2));\n\t\tif (entry->method == SC_AC_SCB && (entry->key_ref & IASECC_SCB_METHOD_SM)) {\n rv = iasecc_sm_create_file(card, entry->key_ref & IASECC_SCB_METHOD_MASK_REF, sbuf, sbuf_len + 2);\n LOG_TEST_RET(ctx, rv, \"iasecc_create_file() SM create file error\");", " rv = iasecc_select_file(card, &file->path, NULL);\n LOG_FUNC_RETURN(ctx, rv);", "\t\t}\n\t}", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0, 0);\n\tapdu.data = sbuf;\n\tapdu.datalen = sbuf_len + 2;\n\tapdu.lc = sbuf_len + 2;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"iasecc_create_file() create file error\");", "\trv = iasecc_select_file(card, &file->path, NULL);\n\tLOG_TEST_RET(ctx, rv, \"Cannot select newly created file\");", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_logout(struct sc_card *card)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_path path;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tif (!card->ef_atr || !card->ef_atr->aid.len)\n\t\treturn SC_SUCCESS;", "\tmemset(&path, 0, sizeof(struct sc_path));\n\tpath.type = SC_PATH_TYPE_DF_NAME;\n\tmemcpy(path.value, card->ef_atr->aid.value, card->ef_atr->aid.len);\n\tpath.len = card->ef_atr->aid.len;", "\trv = iasecc_select_file(card, &path, NULL);\n\tsc_log(ctx, \"Select ECC ROOT with the AID from EF.ATR: rv %i\", rv);", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_finish(struct sc_card *card)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_private_data *private_data = (struct iasecc_private_data *)card->drv_data;\n\tstruct iasecc_se_info *se_info = private_data->se_info, *next;", "\tLOG_FUNC_CALLED(ctx);", "\twhile (se_info) {\n\t\tsc_file_free(se_info->df);\n\t\tnext = se_info->next;\n\t\tfree(se_info);\n\t\tse_info = next;\n\t}", "\tfree(card->drv_data);\n\tcard->drv_data = NULL;", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_delete_file(struct sc_card *card, const struct sc_path *path)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tconst struct sc_acl_entry *entry = NULL;\n\tstruct sc_apdu apdu;\n\tstruct sc_file *file = NULL;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_print_cache(card);", "\trv = iasecc_select_file(card, path, &file);\n\tif (rv == SC_ERROR_FILE_NOT_FOUND)\n\t\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n\tLOG_TEST_RET(ctx, rv, \"Cannot select file to delete\");", "\tentry = sc_file_get_acl_entry(file, SC_AC_OP_DELETE);\n\tif (!entry)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, \"Cannot delete file: no 'DELETE' acl\");", "\tsc_log(ctx, \"DELETE method/reference %X/%X\", entry->method, entry->key_ref);\n\tif (entry->method == SC_AC_SCB && (entry->key_ref & IASECC_SCB_METHOD_SM)) {\n\t\tunsigned char se_num = (entry->method == SC_AC_SCB) ? (entry->key_ref & IASECC_SCB_METHOD_MASK_REF) : 0;\n\t\trv = iasecc_sm_delete_file(card, se_num, file->id);\n\t}\n\telse {\n\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xE4, 0x00, 0x00);", "\t\trv = sc_transmit_apdu(card, &apdu);\n\t\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\t\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\t\tLOG_TEST_RET(ctx, rv, \"Delete file failed\");", "\t\tif (card->cache.valid)\n\t\t\tsc_file_free(card->cache.current_ef);\n\t\tcard->cache.current_ef = NULL;\n\t}", "\tsc_file_free(file);\n\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2)\n{\n\tif (sw1 == 0x62 && sw2 == 0x82)\n\t\treturn SC_SUCCESS;", "\treturn iso_ops->check_sw(card, sw1, sw2);\n}", "\nstatic unsigned\niasecc_get_algorithm(struct sc_context *ctx, const struct sc_security_env *env,\n\t\tunsigned operation, unsigned mechanism)\n{\n const struct sc_supported_algo_info *info = NULL;\n int ii;", " if (!env)\n return 0;", " for (ii=0;ii<SC_MAX_SUPPORTED_ALGORITHMS && env->supported_algos[ii].reference; ii++)\n if ((env->supported_algos[ii].operations & operation)\n\t\t\t&& (env->supported_algos[ii].mechanism == mechanism))\n break;", " if (ii < SC_MAX_SUPPORTED_ALGORITHMS && env->supported_algos[ii].reference) {\n info = &env->supported_algos[ii];\n sc_log(ctx, \"found IAS/ECC algorithm %X:%X:%X:%X\",\n\t\t\tinfo->reference, info->mechanism, info->operations, info->algo_ref);\n }\n else {\n sc_log(ctx, \"cannot find IAS/ECC algorithm (operation:%X,mechanism:%X)\", operation, mechanism);\n }", " return info ? info->algo_ref : 0;\n}", "\nstatic int\niasecc_se_cache_info(struct sc_card *card, struct iasecc_se_info *se)\n{\n\tstruct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data;\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_se_info *se_info = NULL, *si = NULL;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);", "\tse_info = calloc(1, sizeof(struct iasecc_se_info));\n\tif (!se_info)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, \"SE info allocation error\");\n\tmemcpy(se_info, se, sizeof(struct iasecc_se_info));", "\tif (card->cache.valid && card->cache.current_df) {\n\t\tsc_file_dup(&se_info->df, card->cache.current_df);\n\t\tif (se_info->df == NULL) {\n\t\t\tfree(se_info);\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, \"Cannot duplicate current DF file\");\n\t\t}\n\t}", "\trv = iasecc_docp_copy(ctx, &se->docp, &se_info->docp);\n\tif (rv < 0) {\n\t\tfree(se_info->df);\n\t\tfree(se_info);\n\t\tLOG_TEST_RET(ctx, rv, \"Cannot make copy of DOCP\");\n\t}", "\tif (!prv->se_info) {\n\t\tprv->se_info = se_info;\n\t}\n\telse {\n\t\tfor (si = prv->se_info; si->next; si = si->next)\n\t\t\t;\n\t\tsi->next = se_info;\n\t}", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_se_get_info_from_cache(struct sc_card *card, struct iasecc_se_info *se)\n{\n\tstruct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data;\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_se_info *si = NULL;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);", "\tfor(si = prv->se_info; si; si = si->next) {\n\t\tif (si->reference != se->reference)\n\t\t\tcontinue;\n\t\tif (!(card->cache.valid && card->cache.current_df) && si->df)\n\t\t\tcontinue;\n\t\tif (card->cache.valid && card->cache.current_df && !si->df)\n\t\t\tcontinue;\n\t\tif (card->cache.valid && card->cache.current_df && si->df)\n\t\t\tif (memcmp(&card->cache.current_df->path, &si->df->path, sizeof(struct sc_path)))\n\t\t\t\tcontinue;\n\t\tbreak;\n\t}", "\tif (!si)\n\t\treturn SC_ERROR_OBJECT_NOT_FOUND;", "\tmemcpy(se, si, sizeof(struct iasecc_se_info));", "\tif (si->df) {\n\t\tsc_file_dup(&se->df, si->df);\n\t\tif (se->df == NULL)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, \"Cannot duplicate current DF file\");\n\t}", "\trv = iasecc_docp_copy(ctx, &si->docp, &se->docp);\n\tLOG_TEST_RET(ctx, rv, \"Cannot make copy of DOCP\");", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nint\niasecc_se_get_info(struct sc_card *card, struct iasecc_se_info *se)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_apdu apdu;\n\tunsigned char rbuf[0x100];\n\tunsigned char sbuf_iasecc[10] = {\n\t\t0x4D, 0x08, IASECC_SDO_TEMPLATE_TAG, 0x06,\n\t\tIASECC_SDO_TAG_HEADER, IASECC_SDO_CLASS_SE | IASECC_OBJECT_REF_LOCAL,\n\t\tse->reference & 0x3F,\n\t\t0x02, IASECC_SDO_CLASS_SE, 0x80\n\t};\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);", "\tif (se->reference > IASECC_SE_REF_MAX)\n LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);", "\trv = iasecc_se_get_info_from_cache(card, se);\n\tif (rv == SC_ERROR_OBJECT_NOT_FOUND) {\n\t\tsc_log(ctx, \"No SE#%X info in cache, try to use 'GET DATA'\", se->reference);", "\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xCB, 0x3F, 0xFF);\n\t\tapdu.data = sbuf_iasecc;\n\t\tapdu.datalen = sizeof(sbuf_iasecc);\n\t\tapdu.lc = apdu.datalen;\n\t\tapdu.resp = rbuf;\n\t\tapdu.resplen = sizeof(rbuf);\n\t\tapdu.le = sizeof(rbuf);", "\t\trv = sc_transmit_apdu(card, &apdu);\n\t\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\t\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\t\tLOG_TEST_RET(ctx, rv, \"get SE data error\");", "\t\trv = iasecc_se_parse(card, apdu.resp, apdu.resplen, se);\n\t\tLOG_TEST_RET(ctx, rv, \"cannot parse SE data\");", "\t\trv = iasecc_se_cache_info(card, se);\n\t\tLOG_TEST_RET(ctx, rv, \"failed to put SE data into cache\");\n\t}", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_set_security_env(struct sc_card *card,\n\t\tconst struct sc_security_env *env, int se_num)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_sdo sdo;\n\tstruct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data;\n\tunsigned algo_ref;\n\tstruct sc_apdu apdu;\n\tunsigned sign_meth, sign_ref, auth_meth, auth_ref, aflags;\n\tunsigned char cse_crt_at[] = {\n\t\t0x84, 0x01, 0xFF,\n\t\t0x80, 0x01, IASECC_ALGORITHM_RSA_PKCS\n\t};\n\tunsigned char cse_crt_dst[] = {\n\t\t0x84, 0x01, 0xFF,\n\t\t0x80, 0x01, (IASECC_ALGORITHM_RSA_PKCS | IASECC_ALGORITHM_SHA1)\n\t};\n\tunsigned char cse_crt_ht[] = {\n\t\t0x80, 0x01, IASECC_ALGORITHM_SHA1\n\t};\n\tunsigned char cse_crt_ct[] = {\n\t\t0x84, 0x01, 0xFF,\n\t\t0x80, 0x01, (IASECC_ALGORITHM_RSA_PKCS_DECRYPT | IASECC_ALGORITHM_SHA1)\n\t};\n\tint rv, operation = env->operation;", "\t/* TODO: take algorithm references from 5032, not from header file. */\n\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx, \"iasecc_set_security_env(card:%p) operation 0x%X; senv.algorithm 0x%X, senv.algorithm_ref 0x%X\",\n\t\t\tcard, env->operation, env->algorithm, env->algorithm_ref);", "\tmemset(&sdo, 0, sizeof(sdo));\n\tsdo.sdo_class = IASECC_SDO_CLASS_RSA_PRIVATE;\n\tsdo.sdo_ref = env->key_ref[0] & ~IASECC_OBJECT_REF_LOCAL;\n\trv = iasecc_sdo_get_data(card, &sdo);\n\tLOG_TEST_RET(ctx, rv, \"Cannot get RSA PRIVATE SDO data\");", "\t/* To made by iasecc_sdo_convert_to_file() */\n\tprv->key_size = *(sdo.docp.size.value + 0) * 0x100 + *(sdo.docp.size.value + 1);\n\tsc_log(ctx, \"prv->key_size 0x%\"SC_FORMAT_LEN_SIZE_T\"X\", prv->key_size);", "\trv = iasecc_sdo_convert_acl(card, &sdo, SC_AC_OP_PSO_COMPUTE_SIGNATURE, &sign_meth, &sign_ref);\n\tLOG_TEST_RET(ctx, rv, \"Cannot convert SC_AC_OP_SIGN acl\");", "\trv = iasecc_sdo_convert_acl(card, &sdo, SC_AC_OP_INTERNAL_AUTHENTICATE, &auth_meth, &auth_ref);\n\tLOG_TEST_RET(ctx, rv, \"Cannot convert SC_AC_OP_INT_AUTH acl\");", "\taflags = env->algorithm_flags;", "\tif (!(aflags & SC_ALGORITHM_RSA_PAD_PKCS1))\n\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Only supported signature with PKCS1 padding\");", "\tif (operation == SC_SEC_OPERATION_SIGN) {\n\t\tif (!(aflags & (SC_ALGORITHM_RSA_HASH_SHA1 | SC_ALGORITHM_RSA_HASH_SHA256))) {\n\t\t\tsc_log(ctx, \"CKM_RSA_PKCS asked -- use 'AUTHENTICATE' sign operation instead of 'SIGN'\");\n\t\t\toperation = SC_SEC_OPERATION_AUTHENTICATE;\n\t\t}\n\t\telse if (sign_meth == SC_AC_NEVER) {\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"PSO_DST not allowed for this key\");\n\t\t}\n\t}", "\tif (operation == SC_SEC_OPERATION_SIGN) {\n\t\tprv->op_method = sign_meth;\n\t\tprv->op_ref = sign_ref;\n\t}\n\telse if (operation == SC_SEC_OPERATION_AUTHENTICATE) {\n\t\tif (auth_meth == SC_AC_NEVER)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_ALLOWED, \"INTERNAL_AUTHENTICATE is not allowed for this key\");", "\t\tprv->op_method = auth_meth;\n\t\tprv->op_ref = auth_ref;\n\t}", "\tsc_log(ctx, \"senv.algorithm 0x%X, senv.algorithm_ref 0x%X\", env->algorithm, env->algorithm_ref);\n\tsc_log(ctx,\n\t \"se_num %i, operation 0x%X, algorithm 0x%X, algorithm_ref 0x%X, flags 0x%X; key size %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t se_num, operation, env->algorithm, env->algorithm_ref,\n\t env->algorithm_flags, prv->key_size);\n\tswitch (operation) {\n\tcase SC_SEC_OPERATION_SIGN:\n\t\tif (!(env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1))\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"Need RSA_PKCS1 specified\");", "\t\tif (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA256) {\n\t\t\talgo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_HASH, CKM_SHA256);\n\t\t\tif (!algo_ref)\n\t\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Card application do not supports HASH:SHA256\");", "\t\t\tcse_crt_ht[2] = algo_ref; /* IASECC_ALGORITHM_SHA2 */", "\t\t\talgo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_COMPUTE_SIGNATURE, CKM_SHA256_RSA_PKCS);\n\t\t\tif (!algo_ref)\n\t\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Card application do not supports SIGNATURE:SHA1_RSA_PKCS\");", "\t\t\tcse_crt_dst[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL;\n\t\t\tcse_crt_dst[5] = algo_ref; /* IASECC_ALGORITHM_RSA_PKCS | IASECC_ALGORITHM_SHA2 */\n\t\t}\n\t\telse if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA1) {\n\t\t\talgo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_HASH, CKM_SHA_1);\n\t\t\tif (!algo_ref)\n\t\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Card application do not supports HASH:SHA1\");", "\t\t\tcse_crt_ht[2] = algo_ref;\t/* IASECC_ALGORITHM_SHA1 */", "\t\t\talgo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_COMPUTE_SIGNATURE, CKM_SHA1_RSA_PKCS);\n\t\t\tif (!algo_ref)\n\t\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Card application do not supports SIGNATURE:SHA1_RSA_PKCS\");", "\t\t\tcse_crt_dst[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL;\n\t\t\tcse_crt_dst[5] = algo_ref; /* IASECC_ALGORITHM_RSA_PKCS | IASECC_ALGORITHM_SHA1 */\n\t\t}\n\t\telse {\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"Need RSA_HASH_SHA[1,256] specified\");\n\t\t}", "\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_HT);\n\t\tapdu.data = cse_crt_ht;\n\t\tapdu.datalen = sizeof(cse_crt_ht);\n\t\tapdu.lc = sizeof(cse_crt_ht);", "\t\trv = sc_transmit_apdu(card, &apdu);\n\t\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\t\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\t\tLOG_TEST_RET(ctx, rv, \"MSE restore error\");", "\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_DST);\n\t\tapdu.data = cse_crt_dst;\n\t\tapdu.datalen = sizeof(cse_crt_dst);\n\t\tapdu.lc = sizeof(cse_crt_dst);\n\t\tbreak;\n\tcase SC_SEC_OPERATION_AUTHENTICATE:\n\t\talgo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_COMPUTE_SIGNATURE, CKM_RSA_PKCS);\n\t\tif (!algo_ref)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Application do not supports SIGNATURE:RSA_PKCS\");", "\t\tcse_crt_at[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL;\n\t\tcse_crt_at[5] = algo_ref;\t/* IASECC_ALGORITHM_RSA_PKCS */", "\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_AT);\n\t\tapdu.data = cse_crt_at;\n\t\tapdu.datalen = sizeof(cse_crt_at);\n\t\tapdu.lc = sizeof(cse_crt_at);\n\t\tbreak;\n\tcase SC_SEC_OPERATION_DECIPHER:\n\t\trv = iasecc_sdo_convert_acl(card, &sdo, SC_AC_OP_PSO_DECRYPT, &prv->op_method, &prv->op_ref);\n\t\tLOG_TEST_RET(ctx, rv, \"Cannot convert SC_AC_OP_PSO_DECRYPT acl\");\n\t\talgo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_DECIPHER, CKM_RSA_PKCS);\n\t\tif (!algo_ref)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Application do not supports DECIPHER:RSA_PKCS\");", "\t\tcse_crt_ct[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL;\n\t\tcse_crt_ct[5] = algo_ref;\t/* IASECC_ALGORITHM_RSA_PKCS_DECRYPT | IASECC_ALGORITHM_SHA1 */", "\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_CT);\n\t\tapdu.data = cse_crt_ct;\n\t\tapdu.datalen = sizeof(cse_crt_ct);\n\t\tapdu.lc = sizeof(cse_crt_ct);\n\t\tbreak;\n\tdefault:\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);\n\t}", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"MSE restore error\");", "\tprv->security_env = *env;\n\tprv->security_env.operation = operation;", "\tLOG_FUNC_RETURN(ctx, 0);\n}", "\nstatic int\niasecc_chv_verify_pinpad(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd, int *tries_left)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tunsigned char buffer[0x100];\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx, \"CHV PINPAD PIN reference %i\", pin_cmd->pin_reference);", "\trv = iasecc_pin_is_verified(card, pin_cmd, tries_left);\n\tif (!rv)\n\t\tLOG_FUNC_RETURN(ctx, rv);", "\tif (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) {\n\t\tsc_log(ctx, \"Reader not ready for PIN PAD\");\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_READER);\n\t}", "\t/* When PIN stored length available\n\t * P10 verify data contains full template of 'VERIFY PIN' APDU.\n\t * Without PIN stored length\n\t * pin-pad has to set the Lc and fill PIN data itself.\n\t * Not all pin-pads support this case\n\t */\n\tpin_cmd->pin1.len = pin_cmd->pin1.stored_length;\n\tpin_cmd->pin1.length_offset = 5;", "\tmemset(buffer, 0xFF, sizeof(buffer));\n\tpin_cmd->pin1.data = buffer;", "\tpin_cmd->cmd = SC_PIN_CMD_VERIFY;\n\tpin_cmd->flags |= SC_PIN_CMD_USE_PINPAD;", "\t/*\n\tif (card->reader && card->reader->ops && card->reader->ops->load_message) {\n\t\trv = card->reader->ops->load_message(card->reader, card->slot, 0, \"Here we are!\");\n\t\tsc_log(ctx, \"Load message returned %i\", rv);\n\t}\n\t*/", "\trv = iso_ops->pin_cmd(card, pin_cmd, tries_left);\n\tsc_log(ctx, \"rv %i\", rv);", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_chv_verify(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd,\n\t\tint *tries_left)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_acl_entry acl = pin_cmd->pin1.acls[IASECC_ACLS_CHV_VERIFY];\n\tstruct sc_apdu apdu;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx, \"Verify CHV PIN(ref:%i,len:%i,acl:%X:%X)\", pin_cmd->pin_reference, pin_cmd->pin1.len,\n\t\t\tacl.method, acl.key_ref);", "\tif (acl.method & IASECC_SCB_METHOD_SM) {\n\t\trv = iasecc_sm_pin_verify(card, acl.key_ref, pin_cmd, tries_left);\n\t\tLOG_FUNC_RETURN(ctx, rv);\n\t}", "\tif (pin_cmd->pin1.data && !pin_cmd->pin1.len) {\n\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x20, 0, pin_cmd->pin_reference);\n\t}\n\telse if (pin_cmd->pin1.data && pin_cmd->pin1.len) {\n\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x20, 0, pin_cmd->pin_reference);\n\t\tapdu.data = pin_cmd->pin1.data;\n\t\tapdu.datalen = pin_cmd->pin1.len;\n\t\tapdu.lc = pin_cmd->pin1.len;\n\t}\n\telse if ((card->reader->capabilities & SC_READER_CAP_PIN_PAD) && !pin_cmd->pin1.data && !pin_cmd->pin1.len) {\n\t\trv = iasecc_chv_verify_pinpad(card, pin_cmd, tries_left);\n\t\tsc_log(ctx, \"Result of verifying CHV with PIN pad %i\", rv);\n\t\tLOG_FUNC_RETURN(ctx, rv);\n\t}\n\telse {\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);\n\t}", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");", "\tif (tries_left && apdu.sw1 == 0x63 && (apdu.sw2 & 0xF0) == 0xC0)\n\t\t*tries_left = apdu.sw2 & 0x0F;", "\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_se_at_to_chv_reference(struct sc_card *card, unsigned reference,\n\t\tunsigned *chv_reference)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_se_info se;\n\tstruct sc_crt crt;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx, \"SE reference %i\", reference);", "\tif (reference > IASECC_SE_REF_MAX)\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);", "\tmemset(&se, 0, sizeof(se));\n\tse.reference = reference;", "\trv = iasecc_se_get_info(card, &se);\n\tLOG_TEST_RET(ctx, rv, \"SDO get data error\");", "\tmemset(&crt, 0, sizeof(crt));\n\tcrt.tag = IASECC_CRT_TAG_AT;\n\tcrt.usage = IASECC_UQB_AT_USER_PASSWORD;", "\trv = iasecc_se_get_crt(card, &se, &crt);\n\tLOG_TEST_RET(ctx, rv, \"no authentication template for USER PASSWORD\");", "\tif (chv_reference)\n\t\t*chv_reference = crt.refs[0];", "\tsc_file_free(se.df);", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_pin_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd_data,\n\t\tint *tries_left)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_pin_cmd_data pin_cmd;\n struct sc_acl_entry acl = pin_cmd_data->pin1.acls[IASECC_ACLS_CHV_VERIFY];\n\tint rv = SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;", "\tLOG_FUNC_CALLED(ctx);", "\tif (pin_cmd_data->pin_type != SC_AC_CHV)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"PIN type is not supported for the verification\");", "\tsc_log(ctx, \"Verify ACL(method:%X;ref:%X)\", acl.method, acl.key_ref);\n\tif (acl.method != IASECC_SCB_ALWAYS)\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED);", "\tpin_cmd = *pin_cmd_data;\n\tpin_cmd.pin1.data = (unsigned char *)\"\";\n\tpin_cmd.pin1.len = 0;", "\trv = iasecc_chv_verify(card, &pin_cmd, tries_left);", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_pin_verify(struct sc_card *card, unsigned type, unsigned reference,\n\t\tconst unsigned char *data, size_t data_len, int *tries_left)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_pin_cmd_data pin_cmd;\n\tunsigned chv_ref = reference;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx,\n\t \"Verify PIN(type:%X,ref:%i,data(len:%\"SC_FORMAT_LEN_SIZE_T\"u,%p)\",\n\t type, reference, data_len, data);", "\tif (type == SC_AC_AUT) {\n\t\trv = iasecc_sm_external_authentication(card, reference, tries_left);\n\t\tLOG_FUNC_RETURN(ctx, rv);\n\t}\n\telse if (type == SC_AC_SCB) {\n\t\tif (reference & IASECC_SCB_METHOD_USER_AUTH) {\n\t\t\ttype = SC_AC_SEN;\n\t\t\treference = reference & IASECC_SCB_METHOD_MASK_REF;\n\t\t}\n\t\telse {\n\t\t\tsc_log(ctx, \"Do not try to verify non CHV PINs\");\n\t\t\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n\t\t}\n\t}", "\tif (type == SC_AC_SEN) {\n\t\trv = iasecc_se_at_to_chv_reference(card, reference, &chv_ref);\n\t\tLOG_TEST_RET(ctx, rv, \"SE AT to CHV reference error\");\n\t}", "\tmemset(&pin_cmd, 0, sizeof(pin_cmd));\n\tpin_cmd.pin_type = SC_AC_CHV;\n\tpin_cmd.pin_reference = chv_ref;\n\tpin_cmd.cmd = SC_PIN_CMD_VERIFY;", "\trv = iasecc_pin_get_policy(card, &pin_cmd);\n\tLOG_TEST_RET(ctx, rv, \"Get 'PIN policy' error\");", "\tpin_cmd.pin1.data = data;\n\tpin_cmd.pin1.len = data_len;", "\trv = iasecc_pin_is_verified(card, &pin_cmd, tries_left);\n\tif (data && !data_len)\n\t\tLOG_FUNC_RETURN(ctx, rv);", "\tif (!rv) {\n\t\tif (iasecc_chv_cache_is_verified(card, &pin_cmd))\n\t\t\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n\t}\n\telse if (rv != SC_ERROR_PIN_CODE_INCORRECT && rv != SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) {\n\t\tLOG_FUNC_RETURN(ctx, rv);\n\t}", "\tiasecc_chv_cache_clean(card, &pin_cmd);", "\trv = iasecc_chv_verify(card, &pin_cmd, tries_left);\n\tLOG_TEST_RET(ctx, rv, \"PIN CHV verification error\");", "\trv = iasecc_chv_cache_verified(card, &pin_cmd);", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_chv_change_pinpad(struct sc_card *card, unsigned reference, int *tries_left)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_pin_cmd_data pin_cmd;\n\tunsigned char pin1_data[0x100], pin2_data[0x100];\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx, \"CHV PINPAD PIN reference %i\", reference);", "\tmemset(pin1_data, 0xFF, sizeof(pin1_data));\n\tmemset(pin2_data, 0xFF, sizeof(pin2_data));", "\tif (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) {\n\t\tsc_log(ctx, \"Reader not ready for PIN PAD\");\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_READER);\n\t}", "\tmemset(&pin_cmd, 0, sizeof(pin_cmd));\n\tpin_cmd.pin_type = SC_AC_CHV;\n\tpin_cmd.pin_reference = reference;\n\tpin_cmd.cmd = SC_PIN_CMD_CHANGE;\n\tpin_cmd.flags |= SC_PIN_CMD_USE_PINPAD;", "\trv = iasecc_pin_get_policy(card, &pin_cmd);\n\tLOG_TEST_RET(ctx, rv, \"Get 'PIN policy' error\");", "\t/* Some pin-pads do not support mode with Lc=0.\n\t * Give them a chance to work with some cards.\n\t */\n\tif ((pin_cmd.pin1.min_length == pin_cmd.pin1.stored_length) && (pin_cmd.pin1.max_length == pin_cmd.pin1.min_length))\n\t\tpin_cmd.pin1.len = pin_cmd.pin1.stored_length;\n\telse\n\t\tpin_cmd.pin1.len = 0;", "\tpin_cmd.pin1.length_offset = 5;\n\tpin_cmd.pin1.data = pin1_data;", "\tmemcpy(&pin_cmd.pin2, &pin_cmd.pin1, sizeof(pin_cmd.pin1));\n\tpin_cmd.pin2.data = pin2_data;", "\tsc_log(ctx,\n\t \"PIN1 max/min/stored: %\"SC_FORMAT_LEN_SIZE_T\"u/%\"SC_FORMAT_LEN_SIZE_T\"u/%\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t pin_cmd.pin1.max_length, pin_cmd.pin1.min_length,\n\t pin_cmd.pin1.stored_length);\n\tsc_log(ctx,\n\t \"PIN2 max/min/stored: %\"SC_FORMAT_LEN_SIZE_T\"u/%\"SC_FORMAT_LEN_SIZE_T\"u/%\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t pin_cmd.pin2.max_length, pin_cmd.pin2.min_length,\n\t pin_cmd.pin2.stored_length);\n\trv = iso_ops->pin_cmd(card, &pin_cmd, tries_left);", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\n#if 0\nstatic int\niasecc_chv_set_pinpad(struct sc_card *card, unsigned char reference)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_pin_cmd_data pin_cmd;\n\tunsigned char pin_data[0x100];\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx, \"Set CHV PINPAD PIN reference %i\", reference);", "\tmemset(pin_data, 0xFF, sizeof(pin_data));", "\tif (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) {\n\t\tsc_log(ctx, \"Reader not ready for PIN PAD\");\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_READER);\n\t}", "\tmemset(&pin_cmd, 0, sizeof(pin_cmd));\n\tpin_cmd.pin_type = SC_AC_CHV;\n\tpin_cmd.pin_reference = reference;\n\tpin_cmd.cmd = SC_PIN_CMD_UNBLOCK;\n\tpin_cmd.flags |= SC_PIN_CMD_USE_PINPAD;", "\trv = iasecc_pin_get_policy(card, &pin_cmd);\n\tLOG_TEST_RET(ctx, rv, \"Get 'PIN policy' error\");", "\tif ((pin_cmd.pin1.min_length == pin_cmd.pin1.stored_length) && (pin_cmd.pin1.max_length == pin_cmd.pin1.min_length))\n\t\tpin_cmd.pin1.len = pin_cmd.pin1.stored_length;\n\telse\n\t\tpin_cmd.pin1.len = 0;", "\tpin_cmd.pin1.length_offset = 5;\n\tpin_cmd.pin1.data = pin_data;", "\tmemcpy(&pin_cmd.pin2, &pin_cmd.pin1, sizeof(pin_cmd.pin1));\n\tmemset(&pin_cmd.pin1, 0, sizeof(pin_cmd.pin1));\n\tpin_cmd.flags |= SC_PIN_CMD_IMPLICIT_CHANGE;", "\tsc_log(ctx, \"PIN1(max:%i,min:%i)\", pin_cmd.pin1.max_length, pin_cmd.pin1.min_length);\n\tsc_log(ctx, \"PIN2(max:%i,min:%i)\", pin_cmd.pin2.max_length, pin_cmd.pin2.min_length);", "\trv = iso_ops->pin_cmd(card, &pin_cmd, NULL);\n\tLOG_FUNC_RETURN(ctx, rv);\n}\n#endif", "\nstatic int\niasecc_pin_get_policy (struct sc_card *card, struct sc_pin_cmd_data *data)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_file *save_current_df = NULL, *save_current_ef = NULL;\n\tstruct iasecc_sdo sdo;\n\tstruct sc_path path;\n\tunsigned ii;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx, \"iasecc_pin_get_policy(card:%p)\", card);", "\tif (data->pin_type != SC_AC_CHV) {\n\t\tsc_log(ctx, \"To unblock PIN it's CHV reference should be presented\");\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);\n\t}", "\tif (card->cache.valid && card->cache.current_df) {\n\t\tsc_file_dup(&save_current_df, card->cache.current_df);\n\t\tif (save_current_df == NULL) {\n\t\t\trv = SC_ERROR_OUT_OF_MEMORY;\n\t\t\tsc_log(ctx, \"Cannot duplicate current DF file\");\n\t\t\tgoto err;\n\t\t}\n\t}", "\tif (card->cache.valid && card->cache.current_ef) {\n\t\tsc_file_dup(&save_current_ef, card->cache.current_ef);\n\t\tif (save_current_ef == NULL) {\n\t\t\trv = SC_ERROR_OUT_OF_MEMORY;\n\t\t\tsc_log(ctx, \"Cannot duplicate current EF file\");\n\t\t\tgoto err;\n\t\t}\n\t}", "\tif (!(data->pin_reference & IASECC_OBJECT_REF_LOCAL) && card->cache.valid && card->cache.current_df) {\n\t\tsc_format_path(\"3F00\", &path);\n\t\tpath.type = SC_PATH_TYPE_FILE_ID;\n\t\trv = iasecc_select_file(card, &path, NULL);\n\t\tLOG_TEST_GOTO_ERR(ctx, rv, \"Unable to select MF\");\n\t}", "\tmemset(&sdo, 0, sizeof(sdo));\n\tsdo.sdo_class = IASECC_SDO_CLASS_CHV;", "\tsdo.sdo_ref = data->pin_reference & ~IASECC_OBJECT_REF_LOCAL;", "\tsc_log(ctx, \"iasecc_pin_get_policy() reference %i\", sdo.sdo_ref);", "\trv = iasecc_sdo_get_data(card, &sdo);\n\tLOG_TEST_GOTO_ERR(ctx, rv, \"Cannot get SDO PIN data\");", "\tif (sdo.docp.acls_contact.size == 0) {\n\t\trv = SC_ERROR_INVALID_DATA;\n\t\tsc_log(ctx, \"Extremely strange ... there is no ACLs\");\n\t\tgoto err;\n\t}", "\tsc_log(ctx,\n\t \"iasecc_pin_get_policy() sdo.docp.size.size %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t sdo.docp.size.size);\n\tfor (ii=0; ii<sizeof(sdo.docp.scbs); ii++) {\n\t\tstruct iasecc_se_info se;\n\t\tunsigned char scb = sdo.docp.scbs[ii];\n\t\tstruct sc_acl_entry *acl = &data->pin1.acls[ii];\n\t\tint crt_num = 0;", "\t\tmemset(&se, 0, sizeof(se));\n\t\tmemset(&acl->crts, 0, sizeof(acl->crts));", "\t\tsc_log(ctx, \"iasecc_pin_get_policy() set info acls: SCB 0x%X\", scb);\n\t\t/* acl->raw_value = scb; */\n\t\tacl->method = scb & IASECC_SCB_METHOD_MASK;\n\t\tacl->key_ref = scb & IASECC_SCB_METHOD_MASK_REF;", "\t\tif (scb==0 || scb==0xFF)\n\t\t\tcontinue;", "\t\tif (se.reference != (int)acl->key_ref) {\n\t\t\tmemset(&se, 0, sizeof(se));", "\t\t\tse.reference = acl->key_ref;", "\t\t\trv = iasecc_se_get_info(card, &se);\n\t\t\tLOG_TEST_GOTO_ERR(ctx, rv, \"SDO get data error\");\n\t\t}", "\t\tif (scb & IASECC_SCB_METHOD_USER_AUTH) {\n\t\t\trv = iasecc_se_get_crt_by_usage(card, &se,\n\t\t\t\t\tIASECC_CRT_TAG_AT, IASECC_UQB_AT_USER_PASSWORD, &acl->crts[crt_num]);\n\t\t\tLOG_TEST_GOTO_ERR(ctx, rv, \"no authentication template for 'USER PASSWORD'\");\n\t\t\tsc_log(ctx, \"iasecc_pin_get_policy() scb:0x%X; sdo_ref:[%i,%i,...]\",\n\t\t\t\t\tscb, acl->crts[crt_num].refs[0], acl->crts[crt_num].refs[1]);\n\t\t\tcrt_num++;\n\t\t}", "\t\tif (scb & (IASECC_SCB_METHOD_SM | IASECC_SCB_METHOD_EXT_AUTH)) {\n\t\t\tsc_log(ctx, \"'SM' and 'EXTERNAL AUTHENTICATION' protection methods are not supported: SCB:0x%X\", scb);\n\t\t\t/* Set to 'NEVER' if all conditions are needed or\n\t\t\t * there is no user authentication method allowed */\n\t\t\tif (!crt_num || (scb & IASECC_SCB_METHOD_NEED_ALL))\n\t\t\t\tacl->method = SC_AC_NEVER;\n\t\t\tcontinue;\n\t\t}", "\t\tsc_file_free(se.df);\n\t}", "\tif (sdo.data.chv.size_max.value)\n\t\tdata->pin1.max_length = *sdo.data.chv.size_max.value;\n\tif (sdo.data.chv.size_min.value)\n\t\tdata->pin1.min_length = *sdo.data.chv.size_min.value;\n\tif (sdo.docp.tries_maximum.value)\n\t\tdata->pin1.max_tries = *sdo.docp.tries_maximum.value;\n\tif (sdo.docp.tries_remaining.value)\n\t\tdata->pin1.tries_left = *sdo.docp.tries_remaining.value;\n\tif (sdo.docp.size.value) {\n\t\tfor (ii=0; ii<sdo.docp.size.size; ii++)\n\t\t\tdata->pin1.stored_length = ((data->pin1.stored_length) << 8) + *(sdo.docp.size.value + ii);\n\t}", "\tdata->pin1.encoding = SC_PIN_ENCODING_ASCII;\n\tdata->pin1.offset = 5;\n\tdata->pin1.logged_in = SC_PIN_STATE_UNKNOWN;", "\tsc_log(ctx,\n\t \"PIN policy: size max/min %\"SC_FORMAT_LEN_SIZE_T\"u/%\"SC_FORMAT_LEN_SIZE_T\"u, tries max/left %i/%i\",\n\t data->pin1.max_length, data->pin1.min_length,\n\t data->pin1.max_tries, data->pin1.tries_left);\n\tiasecc_sdo_free_fields(card, &sdo);", "\tif (save_current_df) {\n\t\tsc_log(ctx, \"iasecc_pin_get_policy() restore current DF\");\n\t\trv = iasecc_select_file(card, &save_current_df->path, NULL);\n\t\tLOG_TEST_GOTO_ERR(ctx, rv, \"Cannot return to saved DF\");\n\t}", "\tif (save_current_ef) {\n\t\tsc_log(ctx, \"iasecc_pin_get_policy() restore current EF\");\n\t\trv = iasecc_select_file(card, &save_current_ef->path, NULL);\n\t\tLOG_TEST_GOTO_ERR(ctx, rv, \"Cannot return to saved EF\");\n\t}", "err:\n\tsc_file_free(save_current_df);\n\tsc_file_free(save_current_ef);", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_keyset_change(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_sdo_update update;\n\tstruct iasecc_sdo sdo;\n\tunsigned scb;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx, \"Change keyset(ref:%i,lengths:%i)\", data->pin_reference, data->pin2.len);\n\tif (!data->pin2.data || data->pin2.len < 32)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"Needs at least 32 bytes for a new keyset value\");", "\tmemset(&sdo, 0, sizeof(sdo));\n\tsdo.sdo_class = IASECC_SDO_CLASS_KEYSET;\n\tsdo.sdo_ref = data->pin_reference;", "\trv = iasecc_sdo_get_data(card, &sdo);\n\tLOG_TEST_RET(ctx, rv, \"Cannot get keyset data\");", "\tif (sdo.docp.acls_contact.size == 0)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"Bewildered ... there are no ACLs\");\n\tscb = sdo.docp.scbs[IASECC_ACLS_KEYSET_PUT_DATA];\n\tiasecc_sdo_free_fields(card, &sdo);", "\tsc_log(ctx, \"SCB:0x%X\", scb);\n\tif (!(scb & IASECC_SCB_METHOD_SM))\n\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Other then protected by SM, the keyset change is not supported\");", "\tmemset(&update, 0, sizeof(update));\n\tupdate.magic = SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA;\n\tupdate.sdo_class = sdo.sdo_class;\n\tupdate.sdo_ref = sdo.sdo_ref;", "\tupdate.fields[0].parent_tag = IASECC_SDO_KEYSET_TAG;\n\tupdate.fields[0].tag = IASECC_SDO_KEYSET_TAG_MAC;\n\t/* FIXME is it safe to modify the const value here? */\n\tupdate.fields[0].value = (unsigned char *) data->pin2.data;\n\tupdate.fields[0].size = 16;", "\tupdate.fields[1].parent_tag = IASECC_SDO_KEYSET_TAG;\n\tupdate.fields[1].tag = IASECC_SDO_KEYSET_TAG_ENC;\n\t/* FIXME is it safe to modify the const value here? */\n\tupdate.fields[1].value = (unsigned char *) data->pin2.data + 16;\n\tupdate.fields[1].size = 16;", "\trv = iasecc_sm_sdo_update(card, (scb & IASECC_SCB_METHOD_MASK_REF), &update);\n\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_pin_change(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_apdu apdu;\n\tunsigned reference = data->pin_reference;\n\tunsigned char pin_data[0x100];\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx, \"Change PIN(ref:%i,type:0x%X,lengths:%i/%i)\", reference, data->pin_type, data->pin1.len, data->pin2.len);", "\tif ((card->reader->capabilities & SC_READER_CAP_PIN_PAD)) {\n\t\tif (!data->pin1.data && !data->pin1.len && !data->pin2.data && !data->pin2.len) {\n\t\t\trv = iasecc_chv_change_pinpad(card, reference, tries_left);\n\t\t\tsc_log(ctx, \"iasecc_pin_cmd(SC_PIN_CMD_CHANGE) chv_change_pinpad returned %i\", rv);\n\t\t\tLOG_FUNC_RETURN(ctx, rv);\n\t\t}\n\t}", "\tif (!data->pin1.data && data->pin1.len)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"Invalid PIN1 arguments\");", "\tif (!data->pin2.data && data->pin2.len)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"Invalid PIN2 arguments\");", "\trv = iasecc_pin_verify(card, data->pin_type, reference, data->pin1.data, data->pin1.len, tries_left);\n\tsc_log(ctx, \"iasecc_pin_cmd(SC_PIN_CMD_CHANGE) pin_verify returned %i\", rv);\n\tLOG_TEST_RET(ctx, rv, \"PIN verification error\");", "\tif ((unsigned)(data->pin1.len + data->pin2.len) > sizeof(pin_data))\n\t\tLOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, \"Buffer too small for the 'Change PIN' data\");", "\tif (data->pin1.data)\n\t\tmemcpy(pin_data, data->pin1.data, data->pin1.len);\n\tif (data->pin2.data)\n\t\tmemcpy(pin_data + data->pin1.len, data->pin2.data, data->pin2.len);", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x24, 0, reference);\n\tapdu.data = pin_data;\n\tapdu.datalen = data->pin1.len + data->pin2.len;\n\tapdu.lc = apdu.datalen;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"PIN cmd failed\");", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_pin_reset(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_file *save_current = NULL;\n\tstruct iasecc_sdo sdo;\n\tstruct sc_apdu apdu;\n\tunsigned reference, scb;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx, \"Reset PIN(ref:%i,lengths:%i/%i)\", data->pin_reference, data->pin1.len, data->pin2.len);", "\tif (data->pin_type != SC_AC_CHV)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"Unblock procedure can be used only with the PINs of type CHV\");", "\treference = data->pin_reference;", "\tif (!(data->pin_reference & IASECC_OBJECT_REF_LOCAL) && card->cache.valid && card->cache.current_df) {\n\t\tstruct sc_path path;", "\t\tsc_file_dup(&save_current, card->cache.current_df);\n\t\tif (save_current == NULL)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, \"Cannot duplicate current DF file\");", "\t\tsc_format_path(\"3F00\", &path);\n\t\tpath.type = SC_PATH_TYPE_FILE_ID;\n\t\trv = iasecc_select_file(card, &path, NULL);\n\t\tLOG_TEST_RET(ctx, rv, \"Unable to select MF\");\n\t}", "\tmemset(&sdo, 0, sizeof(sdo));\n\tsdo.sdo_class = IASECC_SDO_CLASS_CHV;\n\tsdo.sdo_ref = reference & ~IASECC_OBJECT_REF_LOCAL;", "\trv = iasecc_sdo_get_data(card, &sdo);\n\tLOG_TEST_RET(ctx, rv, \"Cannot get PIN data\");", "\tif (sdo.docp.acls_contact.size == 0)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"Extremely strange ... there are no ACLs\");", "\tscb = sdo.docp.scbs[IASECC_ACLS_CHV_RESET];\n\tdo {\n\t\tunsigned need_all = scb & IASECC_SCB_METHOD_NEED_ALL ? 1 : 0;\n\t\tunsigned char se_num = scb & IASECC_SCB_METHOD_MASK_REF;", "\t\tif (scb & IASECC_SCB_METHOD_USER_AUTH) {\n\t\t\tsc_log(ctx, \"Verify PIN in SE %X\", se_num);\n\t\t\trv = iasecc_pin_verify(card, SC_AC_SEN, se_num, data->pin1.data, data->pin1.len, tries_left);\n\t\t\tLOG_TEST_RET(ctx, rv, \"iasecc_pin_reset() verify PUK error\");", "\t\t\tif (!need_all)\n\t\t\t\tbreak;\n\t\t}", "\t\tif (scb & IASECC_SCB_METHOD_SM) {\n\t\t\trv = iasecc_sm_pin_reset(card, se_num, data);\n\t\t\tLOG_FUNC_RETURN(ctx, rv);\n\t\t}", "\t\tif (scb & IASECC_SCB_METHOD_EXT_AUTH) {\n\t\t\trv = iasecc_sm_external_authentication(card, reference, tries_left);\n\t\t\tLOG_TEST_RET(ctx, rv, \"iasecc_pin_reset() external authentication error\");\n\t\t}\n\t} while(0);", "\tiasecc_sdo_free_fields(card, &sdo);", "\tif (data->pin2.len) {\n\t\tsc_log(ctx, \"Reset PIN %X and set new value\", reference);\n\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x2C, 0x02, reference);\n\t\tapdu.data = data->pin2.data;\n\t\tapdu.datalen = data->pin2.len;\n\t\tapdu.lc = apdu.datalen;", "\t\trv = sc_transmit_apdu(card, &apdu);\n\t\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\t\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\t\tLOG_TEST_RET(ctx, rv, \"PIN cmd failed\");\n\t}\n\telse if (data->pin2.data) {\n\t\tsc_log(ctx, \"Reset PIN %X and set new value\", reference);\n\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x2C, 3, reference);", "\t\trv = sc_transmit_apdu(card, &apdu);\n\t\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\t\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\t\tLOG_TEST_RET(ctx, rv, \"PIN cmd failed\");\n\t}\n\telse {\n\t\tsc_log(ctx, \"Reset PIN %X and set new value with PIN-PAD\", reference);\n#if 0\n\t\trv = iasecc_chv_set_pinpad(card, reference);\n\t\tLOG_TEST_RET(ctx, rv, \"Reset PIN failed\");\n#else\n\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Reset retry counter with PIN PAD not supported \");\n#endif\n\t}", "\tif (save_current) {\n\t\trv = iasecc_select_file(card, &save_current->path, NULL);\n\t\tLOG_TEST_RET(ctx, rv, \"Cannot return to saved PATH\");\n\t}", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx, \"iasecc_pin_cmd() cmd 0x%X, PIN type 0x%X, PIN reference %i, PIN-1 %p:%i, PIN-2 %p:%i\",\n\t\t\tdata->cmd, data->pin_type, data->pin_reference,\n\t\t\tdata->pin1.data, data->pin1.len, data->pin2.data, data->pin2.len);", "\tswitch (data->cmd) {\n\tcase SC_PIN_CMD_VERIFY:\n\t\trv = iasecc_pin_verify(card, data->pin_type, data->pin_reference, data->pin1.data, data->pin1.len, tries_left);\n\t\tbreak;\n\tcase SC_PIN_CMD_CHANGE:\n\t\tif (data->pin_type == SC_AC_AUT)\n\t\t\trv = iasecc_keyset_change(card, data, tries_left);\n\t\telse\n\t\t\trv = iasecc_pin_change(card, data, tries_left);\n\t\tbreak;\n\tcase SC_PIN_CMD_UNBLOCK:\n\t\trv = iasecc_pin_reset(card, data, tries_left);\n\t\tbreak;\n\tcase SC_PIN_CMD_GET_INFO:\n\t\trv = iasecc_pin_get_policy(card, data);\n\t\tbreak;\n\tdefault:\n\t\tsc_log(ctx, \"Other pin commands not supported yet: 0x%X\", data->cmd);\n\t\trv = SC_ERROR_NOT_SUPPORTED;\n\t}", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_get_serialnr(struct sc_card *card, struct sc_serial_number *serial)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_iin *iin = &card->serialnr.iin;\n\tstruct sc_apdu apdu;\n\tunsigned char rbuf[0xC0];\n\tsize_t ii, offs;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tif (card->serialnr.len)\n\t\tgoto end;", "\tmemset(&card->serialnr, 0, sizeof(card->serialnr));", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xB0, 0x80 | IASECC_SFI_EF_SN, 0);\n\tapdu.le = sizeof(rbuf);\n\tapdu.resp = rbuf;\n\tapdu.resplen = sizeof(rbuf);", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"Get 'serial number' data failed\");", "\tif (rbuf[0] != ISO7812_PAN_SN_TAG)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, \"serial number parse error\");", "\tiin->mii = (rbuf[2] >> 4) & 0x0F;", "\tiin->country = 0;\n\tfor (ii=5; ii<8; ii++) {\n\t\tiin->country *= 10;\n\t\tiin->country += (rbuf[ii/2] >> ((ii & 0x01) ? 0 : 4)) & 0x0F;\n\t}", "\tiin->issuer_id = 0;\n\tfor (ii=8; ii<10; ii++) {\n\t\tiin->issuer_id *= 10;\n\t\tiin->issuer_id += (rbuf[ii/2] >> (ii & 0x01 ? 0 : 4)) & 0x0F;\n\t}", "\toffs = rbuf[1] > 8 ? rbuf[1] - 8 : 0;\n\tif (card->type == SC_CARD_TYPE_IASECC_SAGEM) {\n\t\t/* 5A 0A 92 50 00 20 10 10 25 00 01 3F */\n\t\t/* 00 02 01 01 02 50 00 13 */\n\t\tfor (ii=0; (ii < rbuf[1] - offs) && (ii + offs + 2 < sizeof(rbuf)); ii++)\n\t\t\t*(card->serialnr.value + ii) = ((rbuf[ii + offs + 1] & 0x0F) << 4)\n\t\t\t\t+ ((rbuf[ii + offs + 2] & 0xF0) >> 4) ;\n\t\tcard->serialnr.len = ii;\n\t}\n\telse {\n\t\tfor (ii=0; ii < rbuf[1] - offs; ii++)\n\t\t\t*(card->serialnr.value + ii) = rbuf[ii + offs + 2];\n\t\tcard->serialnr.len = ii;\n\t}", "\tdo {\n\t\tchar txt[0x200];", "\t\tfor (ii=0;ii<card->serialnr.len;ii++)\n\t\t\tsprintf(txt + ii*2, \"%02X\", *(card->serialnr.value + ii));", "\t\tsc_log(ctx, \"serial number '%s'; mii %i; country %i; issuer_id %li\", txt, iin->mii, iin->country, iin->issuer_id);\n\t} while(0);", "end:\n\tif (serial)\n\t\tmemcpy(serial, &card->serialnr, sizeof(*serial));", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_sdo_create(struct sc_card *card, struct iasecc_sdo *sdo)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_apdu apdu;\n\tunsigned char *data = NULL, sdo_class = sdo->sdo_class;\n\tstruct iasecc_sdo_update update;\n\tstruct iasecc_extended_tlv *field = NULL;\n\tint rv = SC_ERROR_NOT_SUPPORTED, data_len;", "\tLOG_FUNC_CALLED(ctx);\n\tif (sdo->magic != SC_CARDCTL_IASECC_SDO_MAGIC)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"Invalid SDO data\");", "\tsc_log(ctx, \"iasecc_sdo_create(card:%p) %02X%02X%02X\", card,\n\t\t\tIASECC_SDO_TAG_HEADER, sdo->sdo_class | 0x80, sdo->sdo_ref);", "\tdata_len = iasecc_sdo_encode_create(ctx, sdo, &data);\n\tLOG_TEST_RET(ctx, data_len, \"iasecc_sdo_create() cannot encode SDO create data\");\n\tsc_log(ctx, \"iasecc_sdo_create() create data(%i):%s\", data_len, sc_dump_hex(data, data_len));", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xDB, 0x3F, 0xFF);\n\tapdu.data = data;\n\tapdu.datalen = data_len;\n\tapdu.lc = data_len;\n\tapdu.flags |= SC_APDU_FLAGS_CHAINING;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"iasecc_sdo_create() SDO put data error\");", "\tmemset(&update, 0, sizeof(update));\n\tupdate.magic = SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA;\n\tupdate.sdo_class = sdo->sdo_class;\n\tupdate.sdo_ref = sdo->sdo_ref;", "\tif (sdo_class == IASECC_SDO_CLASS_RSA_PRIVATE) {\n\t\tupdate.fields[0] = sdo->data.prv_key.compulsory;\n\t\tupdate.fields[0].parent_tag = IASECC_SDO_PRVKEY_TAG;\n\t\tfield = &sdo->data.prv_key.compulsory;\n\t}\n\telse if (sdo_class == IASECC_SDO_CLASS_RSA_PUBLIC) {\n\t\tupdate.fields[0] = sdo->data.pub_key.compulsory;\n\t\tupdate.fields[0].parent_tag = IASECC_SDO_PUBKEY_TAG;\n\t\tfield = &sdo->data.pub_key.compulsory;\n\t}\n\telse if (sdo_class == IASECC_SDO_CLASS_KEYSET) {\n\t\tupdate.fields[0] = sdo->data.keyset.compulsory;\n\t\tupdate.fields[0].parent_tag = IASECC_SDO_KEYSET_TAG;\n\t\tfield = &sdo->data.keyset.compulsory;\n\t}", "\tif (update.fields[0].value && !update.fields[0].on_card) {\n\t\trv = iasecc_sdo_put_data(card, &update);\n\t\tLOG_TEST_RET(ctx, rv, \"failed to update 'Compulsory usage' data\");", "\t\tif (field)\n\t\t\tfield->on_card = 1;\n\t}", "\tfree(data);\n\tLOG_FUNC_RETURN(ctx, rv);\n}", "/* Oberthur's specific */\nstatic int\niasecc_sdo_delete(struct sc_card *card, struct iasecc_sdo *sdo)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_apdu apdu;\n\tunsigned char data[6] = {\n\t\t0x70, 0x04, 0xBF, 0xFF, 0xFF, 0x00\n\t};\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tif (sdo->magic != SC_CARDCTL_IASECC_SDO_MAGIC)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"Invalid SDO data\");", "\tdata[2] = IASECC_SDO_TAG_HEADER;\n\tdata[3] = sdo->sdo_class | 0x80;\n\tdata[4] = sdo->sdo_ref;\n\tsc_log(ctx, \"delete SDO %02X%02X%02X\", data[2], data[3], data[4]);", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xDB, 0x3F, 0xFF);\n\tapdu.data = data;\n\tapdu.datalen = sizeof(data);\n\tapdu.lc = sizeof(data);\n\tapdu.flags |= SC_APDU_FLAGS_CHAINING;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"delete SDO error\");", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_sdo_put_data(struct sc_card *card, struct iasecc_sdo_update *update)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_apdu apdu;\n\tint ii, rv;", "\tLOG_FUNC_CALLED(ctx);\n\tif (update->magic != SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"Invalid SDO update data\");", "\tfor(ii=0; update->fields[ii].tag && ii < IASECC_SDO_TAGS_UPDATE_MAX; ii++) {\n\t\tunsigned char *encoded = NULL;\n\t\tint encoded_len;", "\t\tencoded_len = iasecc_sdo_encode_update_field(ctx, update->sdo_class, update->sdo_ref,\n\t\t\t\t\t\t\t&update->fields[ii], &encoded);\n\t\tsc_log(ctx, \"iasecc_sdo_put_data() encode[%i]; tag %X; encoded_len %i\", ii, update->fields[ii].tag, encoded_len);\n\t\tLOG_TEST_RET(ctx, encoded_len, \"Cannot encode update data\");", "\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xDB, 0x3F, 0xFF);\n\t\tapdu.data = encoded;\n\t\tapdu.datalen = encoded_len;\n\t\tapdu.lc = encoded_len;\n\t\tapdu.flags |= SC_APDU_FLAGS_CHAINING;", "\t\trv = sc_transmit_apdu(card, &apdu);\n\t\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\t\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\t\tLOG_TEST_RET(ctx, rv, \"SDO put data error\");", "\t\tfree(encoded);\n\t}", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_sdo_key_rsa_put_data(struct sc_card *card, struct iasecc_sdo_rsa_update *update)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tunsigned char scb;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);", "\tif (update->sdo_prv_key) {\n\t\tsc_log(ctx, \"encode private rsa in %p\", &update->update_prv);\n\t\trv = iasecc_sdo_encode_rsa_update(card->ctx, update->sdo_prv_key, update->p15_rsa, &update->update_prv);\n\t\tLOG_TEST_RET(ctx, rv, \"failed to encode update of RSA private key\");\n\t}", "\tif (update->sdo_pub_key) {\n\t\tsc_log(ctx, \"encode public rsa in %p\", &update->update_pub);\n\t\tif (card->type == SC_CARD_TYPE_IASECC_SAGEM) {\n\t\t\tif (update->sdo_pub_key->data.pub_key.cha.value) {\n\t\t\t\tfree(update->sdo_pub_key->data.pub_key.cha.value);\n\t\t\t\tmemset(&update->sdo_pub_key->data.pub_key.cha, 0, sizeof(update->sdo_pub_key->data.pub_key.cha));\n\t\t\t}\n\t\t}\n\t\trv = iasecc_sdo_encode_rsa_update(card->ctx, update->sdo_pub_key, update->p15_rsa, &update->update_pub);\n\t\tLOG_TEST_RET(ctx, rv, \"failed to encode update of RSA public key\");\n\t}", "\tif (update->sdo_prv_key) {\n\t\tsc_log(ctx, \"reference of the private key to store: %X\", update->sdo_prv_key->sdo_ref);", "\t\tif (update->sdo_prv_key->docp.acls_contact.size == 0)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"extremely strange ... there are no ACLs\");", "\t\tscb = update->sdo_prv_key->docp.scbs[IASECC_ACLS_RSAKEY_PUT_DATA];\n\t\tsc_log(ctx, \"'UPDATE PRIVATE RSA' scb 0x%X\", scb);", "\t\tdo {\n\t\t\tunsigned all_conditions = scb & IASECC_SCB_METHOD_NEED_ALL ? 1 : 0;", "\t\t\tif ((scb & IASECC_SCB_METHOD_USER_AUTH) && !all_conditions)\n\t\t\t\tbreak;", "\t\t\tif (scb & IASECC_SCB_METHOD_EXT_AUTH)\n\t\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Not yet\");", "\t\t\tif (scb & IASECC_SCB_METHOD_SM) {\n#ifdef ENABLE_SM\n\t\t\t\trv = iasecc_sm_rsa_update(card, scb & IASECC_SCB_METHOD_MASK_REF, update);\n\t\t\t\tLOG_FUNC_RETURN(ctx, rv);\n#else\n\t\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"built without support of Secure-Messaging\");\n#endif\n\t\t\t}\n\t\t} while(0);", "\t\trv = iasecc_sdo_put_data(card, &update->update_prv);\n\t\tLOG_TEST_RET(ctx, rv, \"failed to update of RSA private key\");\n\t}", "\tif (update->sdo_pub_key) {\n\t\tsc_log(ctx, \"reference of the public key to store: %X\", update->sdo_pub_key->sdo_ref);", "\t\trv = iasecc_sdo_put_data(card, &update->update_pub);\n\t\tLOG_TEST_RET(ctx, rv, \"failed to update of RSA public key\");\n\t}", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_sdo_tag_from_class(unsigned sdo_class)\n{\n\tswitch (sdo_class & ~IASECC_OBJECT_REF_LOCAL) {\n\tcase IASECC_SDO_CLASS_CHV:\n\t\treturn IASECC_SDO_CHV_TAG;\n\tcase IASECC_SDO_CLASS_RSA_PRIVATE:\n\t\treturn IASECC_SDO_PRVKEY_TAG;\n\tcase IASECC_SDO_CLASS_RSA_PUBLIC:\n\t\treturn IASECC_SDO_PUBKEY_TAG;\n\tcase IASECC_SDO_CLASS_SE:\n\t\treturn IASECC_SDO_CLASS_SE;\n\tcase IASECC_SDO_CLASS_KEYSET:\n\t\treturn IASECC_SDO_KEYSET_TAG;\n\t}", "\treturn -1;\n}", "\nstatic int\niasecc_sdo_get_tagged_data(struct sc_card *card, int sdo_tag, struct iasecc_sdo *sdo)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_apdu apdu;\n\tunsigned char sbuf[0x100];\n\tsize_t offs = sizeof(sbuf) - 1;\n\tunsigned char rbuf[0x400];\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);", "\tsbuf[offs--] = 0x80;\n\tsbuf[offs--] = sdo_tag & 0xFF;\n\tif ((sdo_tag >> 8) & 0xFF)\n\t\tsbuf[offs--] = (sdo_tag >> 8) & 0xFF;\n\tsbuf[offs] = sizeof(sbuf) - offs - 1;\n\toffs--;", "\tsbuf[offs--] = sdo->sdo_ref & 0x9F;\n\tsbuf[offs--] = sdo->sdo_class | IASECC_OBJECT_REF_LOCAL;\n\tsbuf[offs--] = IASECC_SDO_TAG_HEADER;", "\tsbuf[offs] = sizeof(sbuf) - offs - 1;\n\toffs--;\n\tsbuf[offs--] = IASECC_SDO_TEMPLATE_TAG;", "\tsbuf[offs] = sizeof(sbuf) - offs - 1;\n\toffs--;\n\tsbuf[offs] = 0x4D;", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xCB, 0x3F, 0xFF);\n\tapdu.data = sbuf + offs;\n\tapdu.datalen = sizeof(sbuf) - offs;\n\tapdu.lc = sizeof(sbuf) - offs;\n\tapdu.resp = rbuf;\n\tapdu.resplen = sizeof(rbuf);\n\tapdu.le = 0x100;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"SDO get data error\");", "\trv = iasecc_sdo_parse(card, apdu.resp, apdu.resplen, sdo);\n\tLOG_TEST_RET(ctx, rv, \"cannot parse SDO data\");", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_sdo_get_data(struct sc_card *card, struct iasecc_sdo *sdo)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tint rv, sdo_tag;", "\tLOG_FUNC_CALLED(ctx);", "\tsdo_tag = iasecc_sdo_tag_from_class(sdo->sdo_class);", "\trv = iasecc_sdo_get_tagged_data(card, sdo_tag, sdo);\n\t/* When there is no public data 'GET DATA' returns error */\n\tif (rv != SC_ERROR_INCORRECT_PARAMETERS)\n\t\tLOG_TEST_RET(ctx, rv, \"cannot parse ECC SDO data\");", "\trv = iasecc_sdo_get_tagged_data(card, IASECC_DOCP_TAG, sdo);\n\tLOG_TEST_RET(ctx, rv, \"cannot parse ECC DOCP data\");", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_sdo_generate(struct sc_card *card, struct iasecc_sdo *sdo)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_sdo_update update_pubkey;\n\tstruct sc_apdu apdu;\n\tunsigned char scb, sbuf[5], rbuf[0x400], exponent[3] = {0x01, 0x00, 0x01};\n\tint offs = 0, rv = SC_ERROR_NOT_SUPPORTED;", "\tLOG_FUNC_CALLED(ctx);", "\tif (sdo->sdo_class != IASECC_SDO_CLASS_RSA_PRIVATE)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"For a moment, only RSA_PRIVATE class can be accepted for the SDO generation\");", "\tif (sdo->docp.acls_contact.size == 0)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"Bewildered ... there are no ACLs\");", "\tscb = sdo->docp.scbs[IASECC_ACLS_RSAKEY_GENERATE];\n\tsc_log(ctx, \"'generate RSA key' SCB 0x%X\", scb);\n\tdo {\n\t\tunsigned all_conditions = scb & IASECC_SCB_METHOD_NEED_ALL ? 1 : 0;", "\t\tif (scb & IASECC_SCB_METHOD_USER_AUTH)\n\t\t\tif (!all_conditions)\n\t\t\t\tbreak;", "\t\tif (scb & IASECC_SCB_METHOD_EXT_AUTH)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Not yet\");", "\t\tif (scb & IASECC_SCB_METHOD_SM) {\n\t\t\trv = iasecc_sm_rsa_generate(card, scb & IASECC_SCB_METHOD_MASK_REF, sdo);\n LOG_FUNC_RETURN(ctx, rv);\n\t\t}\n\t} while(0);", "\tmemset(&update_pubkey, 0, sizeof(update_pubkey));\n\tupdate_pubkey.magic = SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA;\n\tupdate_pubkey.sdo_class = IASECC_SDO_CLASS_RSA_PUBLIC;\n\tupdate_pubkey.sdo_ref = sdo->sdo_ref;", "\tupdate_pubkey.fields[0].parent_tag = IASECC_SDO_PUBKEY_TAG;\n\tupdate_pubkey.fields[0].tag = IASECC_SDO_PUBKEY_TAG_E;\n\tupdate_pubkey.fields[0].value = exponent;\n\tupdate_pubkey.fields[0].size = sizeof(exponent);", "\trv = iasecc_sdo_put_data(card, &update_pubkey);\n\tLOG_TEST_RET(ctx, rv, \"iasecc_sdo_generate() update SDO public key failed\");", "\toffs = 0;\n\tsbuf[offs++] = IASECC_SDO_TEMPLATE_TAG;\n\tsbuf[offs++] = 0x03;\n\tsbuf[offs++] = IASECC_SDO_TAG_HEADER;\n\tsbuf[offs++] = IASECC_SDO_CLASS_RSA_PRIVATE | IASECC_OBJECT_REF_LOCAL;\n\tsbuf[offs++] = sdo->sdo_ref & ~IASECC_OBJECT_REF_LOCAL;", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x47, 0x00, 0x00);\n\tapdu.data = sbuf;\n\tapdu.datalen = offs;\n\tapdu.lc = offs;\n\tapdu.resp = rbuf;\n\tapdu.resplen = sizeof(rbuf);\n\tapdu.le = 0x100;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"SDO get data error\");", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_get_chv_reference_from_se(struct sc_card *card, int *se_reference)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_se_info se;\n\tstruct sc_crt crt;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);", "\tif (!se_reference)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"Invalid arguments\");", "\tmemset(&se, 0, sizeof(se));\n\tse.reference = *se_reference;", "\trv = iasecc_se_get_info(card, &se);\n\tLOG_TEST_RET(ctx, rv, \"get SE info error\");", "\tmemset(&crt, 0, sizeof(crt));\n\tcrt.tag = IASECC_CRT_TAG_AT;\n\tcrt.usage = IASECC_UQB_AT_USER_PASSWORD;", "\trv = iasecc_se_get_crt(card, &se, &crt);\n\tLOG_TEST_RET(ctx, rv, \"Cannot get 'USER PASSWORD' authentication template\");", "\tsc_file_free(se.df);\n\tLOG_FUNC_RETURN(ctx, crt.refs[0]);\n}", "\nstatic int\niasecc_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_sdo *sdo = (struct iasecc_sdo *) ptr;", "\tswitch (cmd) {\n\tcase SC_CARDCTL_GET_SERIALNR:\n\t\treturn iasecc_get_serialnr(card, (struct sc_serial_number *)ptr);\n\tcase SC_CARDCTL_IASECC_SDO_CREATE:\n\t\tsc_log(ctx, \"CMD SC_CARDCTL_IASECC_SDO_CREATE: sdo_class %X\", sdo->sdo_class);\n\t\treturn iasecc_sdo_create(card, (struct iasecc_sdo *) ptr);\n\tcase SC_CARDCTL_IASECC_SDO_DELETE:\n\t\tsc_log(ctx, \"CMD SC_CARDCTL_IASECC_SDO_DELETE: sdo_class %X\", sdo->sdo_class);\n\t\treturn iasecc_sdo_delete(card, (struct iasecc_sdo *) ptr);\n\tcase SC_CARDCTL_IASECC_SDO_PUT_DATA:\n\t\tsc_log(ctx, \"CMD SC_CARDCTL_IASECC_SDO_PUT_DATA: sdo_class %X\", sdo->sdo_class);\n\t\treturn iasecc_sdo_put_data(card, (struct iasecc_sdo_update *) ptr);\n\tcase SC_CARDCTL_IASECC_SDO_KEY_RSA_PUT_DATA:\n\t\tsc_log(ctx, \"CMD SC_CARDCTL_IASECC_SDO_KEY_RSA_PUT_DATA\");\n\t\treturn iasecc_sdo_key_rsa_put_data(card, (struct iasecc_sdo_rsa_update *) ptr);\n\tcase SC_CARDCTL_IASECC_SDO_GET_DATA:\n\t\tsc_log(ctx, \"CMD SC_CARDCTL_IASECC_SDO_GET_DATA: sdo_class %X\", sdo->sdo_class);\n\t\treturn iasecc_sdo_get_data(card, (struct iasecc_sdo *) ptr);\n\tcase SC_CARDCTL_IASECC_SDO_GENERATE:\n\t\tsc_log(ctx, \"CMD SC_CARDCTL_IASECC_SDO_GET_DATA: sdo_class %X\", sdo->sdo_class);\n\t\treturn iasecc_sdo_generate(card, (struct iasecc_sdo *) ptr);\n\tcase SC_CARDCTL_GET_SE_INFO:\n\t\tsc_log(ctx, \"CMD SC_CARDCTL_GET_SE_INFO: sdo_class %X\", sdo->sdo_class);\n\t\treturn iasecc_se_get_info(card, (struct iasecc_se_info *) ptr);\n\tcase SC_CARDCTL_GET_CHV_REFERENCE_IN_SE:\n\t\tsc_log(ctx, \"CMD SC_CARDCTL_GET_CHV_REFERENCE_IN_SE\");\n\t\treturn iasecc_get_chv_reference_from_se(card, (int *)ptr);\n\tcase SC_CARDCTL_IASECC_GET_FREE_KEY_REFERENCE:\n\t\tsc_log(ctx, \"CMD SC_CARDCTL_IASECC_GET_FREE_KEY_REFERENCE\");\n\t\treturn iasecc_get_free_reference(card, (struct iasecc_ctl_get_free_reference *)ptr);\n\t}\n\treturn SC_ERROR_NOT_SUPPORTED;\n}", "\nstatic int\niasecc_decipher(struct sc_card *card,\n\t\tconst unsigned char *in, size_t in_len,\n\t\tunsigned char *out, size_t out_len)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_apdu apdu;\n\tunsigned char sbuf[0x200];\n\tunsigned char resp[SC_MAX_APDU_BUFFER_SIZE];\n\tsize_t offs;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(card->ctx,\n\t \"crgram_len %\"SC_FORMAT_LEN_SIZE_T\"u; outlen %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t in_len, out_len);\n\tif (!out || !out_len || in_len > SC_MAX_APDU_BUFFER_SIZE)\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);", "\toffs = 0;\n\tsbuf[offs++] = 0x81;\n\tmemcpy(sbuf + offs, in, in_len);\n\toffs += in_len;", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86);\n\tapdu.flags |= SC_APDU_FLAGS_CHAINING;\n\tapdu.data = sbuf;\n\tapdu.datalen = offs;\n\tapdu.lc = offs;\n\tapdu.resp = resp;\n\tapdu.resplen = sizeof(resp);\n\tapdu.le = 256;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"Card returned error\");", "\tif (out_len > apdu.resplen)\n\t\tout_len = apdu.resplen;", "\tmemcpy(out, apdu.resp, out_len);\n\trv = out_len;", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_qsign_data_sha1(struct sc_context *ctx, const unsigned char *in, size_t in_len,\n\t\t\t\tstruct iasecc_qsign_data *out)\n{\n\tSHA_CTX sha;\n\tSHA_LONG pre_hash_Nl, *hh[5] = {\n\t\t&sha.h0, &sha.h1, &sha.h2, &sha.h3, &sha.h4\n\t};\n\tint jj, ii;\n\tint hh_size = sizeof(SHA_LONG), hh_num = SHA_DIGEST_LENGTH / sizeof(SHA_LONG);", "\tLOG_FUNC_CALLED(ctx);", "\tif (!in || !in_len || !out)\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);", "\tsc_log(ctx,\n\t \"sc_pkcs15_get_qsign_data() input data length %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t in_len);\n\tmemset(out, 0, sizeof(struct iasecc_qsign_data));", "\tSHA1_Init(&sha);\n\tSHA1_Update(&sha, in, in_len);", "\tfor (jj=0; jj<hh_num; jj++)\n\t\tfor(ii=0; ii<hh_size; ii++)\n\t\t\tout->pre_hash[jj*hh_size + ii] = ((*hh[jj] >> 8*(hh_size-1-ii)) & 0xFF);\n\tout->pre_hash_size = SHA_DIGEST_LENGTH;\n\tsc_log(ctx, \"Pre SHA1:%s\", sc_dump_hex(out->pre_hash, out->pre_hash_size));", "\tpre_hash_Nl = sha.Nl - (sha.Nl % (sizeof(sha.data) * 8));\n\tfor (ii=0; ii<hh_size; ii++) {\n\t\tout->counter[ii] = (sha.Nh >> 8*(hh_size-1-ii)) &0xFF;\n\t\tout->counter[hh_size+ii] = (pre_hash_Nl >> 8*(hh_size-1-ii)) &0xFF;\n\t}\n\tfor (ii=0, out->counter_long=0; ii<(int)sizeof(out->counter); ii++)\n\t\tout->counter_long = out->counter_long*0x100 + out->counter[ii];\n\tsc_log(ctx, \"Pre counter(%li):%s\", out->counter_long, sc_dump_hex(out->counter, sizeof(out->counter)));", "\tif (sha.num) {\n\t\tmemcpy(out->last_block, in + in_len - sha.num, sha.num);\n\t\tout->last_block_size = sha.num;\n\t\tsc_log(ctx, \"Last block(%\"SC_FORMAT_LEN_SIZE_T\"u):%s\",\n\t\t out->last_block_size,\n\t\t sc_dump_hex(out->last_block, out->last_block_size));\n\t}", "\tSHA1_Final(out->hash, &sha);\n\tout->hash_size = SHA_DIGEST_LENGTH;\n\tsc_log(ctx, \"Expected digest %s\\n\", sc_dump_hex(out->hash, out->hash_size));", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\n#if OPENSSL_VERSION_NUMBER >= 0x00908000L\nstatic int\niasecc_qsign_data_sha256(struct sc_context *ctx, const unsigned char *in, size_t in_len,\n\t\t\t\tstruct iasecc_qsign_data *out)\n{\n\tSHA256_CTX sha256;\n\tSHA_LONG pre_hash_Nl;\n\tint jj, ii;\n\tint hh_size = sizeof(SHA_LONG), hh_num = SHA256_DIGEST_LENGTH / sizeof(SHA_LONG);", "\tLOG_FUNC_CALLED(ctx);\n\tif (!in || !in_len || !out)\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);", "\tsc_log(ctx,\n\t \"sc_pkcs15_get_qsign_data() input data length %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t in_len);\n\tmemset(out, 0, sizeof(struct iasecc_qsign_data));", "\tSHA256_Init(&sha256);\n\tSHA256_Update(&sha256, in, in_len);", "\tfor (jj=0; jj<hh_num; jj++)\n\t\tfor(ii=0; ii<hh_size; ii++)\n\t\t\tout->pre_hash[jj*hh_size + ii] = ((sha256.h[jj] >> 8*(hh_size-1-ii)) & 0xFF);\n\tout->pre_hash_size = SHA256_DIGEST_LENGTH;\n\tsc_log(ctx, \"Pre hash:%s\", sc_dump_hex(out->pre_hash, out->pre_hash_size));", "\tpre_hash_Nl = sha256.Nl - (sha256.Nl % (sizeof(sha256.data) * 8));\n\tfor (ii=0; ii<hh_size; ii++) {\n\t\tout->counter[ii] = (sha256.Nh >> 8*(hh_size-1-ii)) &0xFF;\n\t\tout->counter[hh_size+ii] = (pre_hash_Nl >> 8*(hh_size-1-ii)) &0xFF;\n\t}\n\tfor (ii=0, out->counter_long=0; ii<(int)sizeof(out->counter); ii++)\n\t\tout->counter_long = out->counter_long*0x100 + out->counter[ii];\n\tsc_log(ctx, \"Pre counter(%li):%s\", out->counter_long, sc_dump_hex(out->counter, sizeof(out->counter)));", "\tif (sha256.num) {\n\t\tmemcpy(out->last_block, in + in_len - sha256.num, sha256.num);\n\t\tout->last_block_size = sha256.num;\n\t\tsc_log(ctx, \"Last block(%\"SC_FORMAT_LEN_SIZE_T\"u):%s\",\n\t\t out->last_block_size,\n\t\t sc_dump_hex(out->last_block, out->last_block_size));\n\t}", "\tSHA256_Final(out->hash, &sha256);\n\tout->hash_size = SHA256_DIGEST_LENGTH;\n\tsc_log(ctx, \"Expected digest %s\\n\", sc_dump_hex(out->hash, out->hash_size));", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}\n#endif", "\nstatic int\niasecc_compute_signature_dst(struct sc_card *card,\n\t\tconst unsigned char *in, size_t in_len, unsigned char *out, size_t out_len)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data;\n\tstruct sc_security_env *env = &prv->security_env;\n\tstruct iasecc_qsign_data qsign_data;\n\tstruct sc_apdu apdu;\n\tsize_t offs = 0, hash_len = 0;\n\tunsigned char sbuf[SC_MAX_APDU_BUFFER_SIZE];\n\tunsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE];\n\tint rv = SC_SUCCESS;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx,\n\t \"iasecc_compute_signature_dst() input length %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t in_len);\n\tif (env->operation != SC_SEC_OPERATION_SIGN)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"It's not SC_SEC_OPERATION_SIGN\");\n\telse if (!(prv->key_size & 0x1E0) || (prv->key_size & ~0x1E0))\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"Invalid key size for SC_SEC_OPERATION_SIGN\");", "\tmemset(&qsign_data, 0, sizeof(qsign_data));\n\tif (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA1) {\n\t\trv = iasecc_qsign_data_sha1(card->ctx, in, in_len, &qsign_data);\n\t}\n\telse if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA256) {\n#if OPENSSL_VERSION_NUMBER >= 0x00908000L\n\t\trv = iasecc_qsign_data_sha256(card->ctx, in, in_len, &qsign_data);\n#else\n\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"SHA256 is not supported by OpenSSL previous to v0.9.8\");\n#endif\n\t}\n\telse\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"Need RSA_HASH_SHA1 or RSA_HASH_SHA256 algorithm\");\n\tLOG_TEST_RET(ctx, rv, \"Cannot get QSign data\");", "\tsc_log(ctx,\n\t \"iasecc_compute_signature_dst() hash_len %\"SC_FORMAT_LEN_SIZE_T\"u; key_size %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t hash_len, prv->key_size);", "\tmemset(sbuf, 0, sizeof(sbuf));\n\tsbuf[offs++] = 0x90;\n\tif (qsign_data.counter_long) {\n\t\tsbuf[offs++] = qsign_data.hash_size + 8;\n\t\tmemcpy(sbuf + offs, qsign_data.pre_hash, qsign_data.pre_hash_size);\n\t\toffs += qsign_data.pre_hash_size;\n\t\tmemcpy(sbuf + offs, qsign_data.counter, sizeof(qsign_data.counter));\n\t\toffs += sizeof(qsign_data.counter);\n\t}\n\telse {\n\t\tsbuf[offs++] = 0;\n\t}", "\tsbuf[offs++] = 0x80;\n\tsbuf[offs++] = qsign_data.last_block_size;\n\tmemcpy(sbuf + offs, qsign_data.last_block, qsign_data.last_block_size);\n\toffs += qsign_data.last_block_size;", "\tsc_log(ctx,\n\t \"iasecc_compute_signature_dst() offs %\"SC_FORMAT_LEN_SIZE_T\"u; OP(meth:%X,ref:%X)\",\n\t offs, prv->op_method, prv->op_ref);\n\tif (prv->op_method == SC_AC_SCB && (prv->op_ref & IASECC_SCB_METHOD_SM))\n\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Not yet\");", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x2A, 0x90, 0xA0);\n\tapdu.data = sbuf;\n\tapdu.datalen = offs;\n\tapdu.lc = offs;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"Compute signature failed\");", "\tsc_log(ctx, \"iasecc_compute_signature_dst() partial hash OK\");", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0x2A, 0x9E, 0x9A);\n\tapdu.resp = rbuf;\n\tapdu.resplen = prv->key_size;\n\tapdu.le = prv->key_size;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"Compute signature failed\");", "\tsc_log(ctx,\n\t \"iasecc_compute_signature_dst() DST resplen %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t apdu.resplen);\n\tif (apdu.resplen > out_len)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, \"Result buffer too small for the DST signature\");", "\tmemcpy(out, apdu.resp, apdu.resplen);", "\tLOG_FUNC_RETURN(ctx, apdu.resplen);\n}", "\nstatic int\niasecc_compute_signature_at(struct sc_card *card,\n\t\tconst unsigned char *in, size_t in_len, unsigned char *out, size_t out_len)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data;\n\tstruct sc_security_env *env = &prv->security_env;\n\tstruct sc_apdu apdu;\n\tsize_t offs = 0, sz = 0;\n\tunsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE];\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tif (env->operation != SC_SEC_OPERATION_AUTHENTICATE)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"It's not SC_SEC_OPERATION_AUTHENTICATE\");", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x88, 0x00, 0x00);\n\tapdu.datalen = in_len;\n\tapdu.data = in;\n\tapdu.lc = in_len;\n\tapdu.resp = rbuf;\n\tapdu.resplen = sizeof(rbuf);\n\tapdu.le = 0x100;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"Compute signature failed\");", "\tdo {\n\t\tif (offs + apdu.resplen > out_len)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, \"Buffer too small to return signature\");", "\t\tmemcpy(out + offs, rbuf, apdu.resplen);\n\t\toffs += apdu.resplen;", "\t\tif (apdu.sw1 == 0x90 && apdu.sw2 == 0x00)\n\t\t\tbreak;", "\t\tif (apdu.sw1 == 0x61) {\n\t\t\tsz = apdu.sw2 == 0x00 ? 0x100 : apdu.sw2;\n\t\t\trv = iso_ops->get_response(card, &sz, rbuf);\n\t\t\tLOG_TEST_RET(ctx, rv, \"Get response error\");", "\t\t\tapdu.resplen = rv;\n\t\t}\n\t\telse {\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_INTERNAL, \"Impossible error: SW1 is not 0x90 neither 0x61\");\n\t\t}", "\t} while(rv > 0);", "\tLOG_FUNC_RETURN(ctx, offs);\n}", "\nstatic int\niasecc_compute_signature(struct sc_card *card,\n\t\tconst unsigned char *in, size_t in_len, unsigned char *out, size_t out_len)\n{\n\tstruct sc_context *ctx;\n\tstruct iasecc_private_data *prv;\n\tstruct sc_security_env *env;", "\tif (!card || !in || !out)\n\t\treturn SC_ERROR_INVALID_ARGUMENTS;", "\tctx = card->ctx;\n\tprv = (struct iasecc_private_data *) card->drv_data;\n\tenv = &prv->security_env;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx,\n\t \"inlen %\"SC_FORMAT_LEN_SIZE_T\"u, outlen %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t in_len, out_len);", "\tif (env->operation == SC_SEC_OPERATION_SIGN)\n\t\treturn iasecc_compute_signature_dst(card, in, in_len, out, out_len);\n\telse if (env->operation == SC_SEC_OPERATION_AUTHENTICATE)\n\t\treturn iasecc_compute_signature_at(card, in, in_len, out, out_len);", "\tLOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);\n}", "\nstatic int\niasecc_read_public_key(struct sc_card *card, unsigned type,\n\t\tstruct sc_path *key_path, unsigned ref, unsigned size,\n\t\tunsigned char **out, size_t *out_len)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_sdo sdo;\n\tstruct sc_pkcs15_bignum bn[2];\n\tstruct sc_pkcs15_pubkey_rsa rsa_key;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tif (type != SC_ALGORITHM_RSA)\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);", "\tsc_log(ctx, \"read public kay(ref:%i;size:%i)\", ref, size);", "\tmemset(&sdo, 0, sizeof(sdo));\n\tsdo.sdo_class = IASECC_SDO_CLASS_RSA_PUBLIC;\n\tsdo.sdo_ref = ref & ~IASECC_OBJECT_REF_LOCAL;", "\trv = iasecc_sdo_get_data(card, &sdo);\n\tLOG_TEST_RET(ctx, rv, \"failed to read public key: cannot get RSA SDO data\");", "\tif (out)\n\t\t*out = NULL;\n\tif (out_len)\n\t\t*out_len = 0;", "\tbn[0].data = (unsigned char *) malloc(sdo.data.pub_key.n.size);\n\tif (!bn[0].data)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, \"failed to read public key: cannot allocate modulus\");\n\tbn[0].len = sdo.data.pub_key.n.size;\n\tmemcpy(bn[0].data, sdo.data.pub_key.n.value, sdo.data.pub_key.n.size);", "\tbn[1].data = (unsigned char *) malloc(sdo.data.pub_key.e.size);\n\tif (!bn[1].data)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, \"failed to read public key: cannot allocate exponent\");\n\tbn[1].len = sdo.data.pub_key.e.size;\n\tmemcpy(bn[1].data, sdo.data.pub_key.e.value, sdo.data.pub_key.e.size);", "\trsa_key.modulus = bn[0];\n\trsa_key.exponent = bn[1];", "\trv = sc_pkcs15_encode_pubkey_rsa(ctx, &rsa_key, out, out_len);\n\tLOG_TEST_RET(ctx, rv, \"failed to read public key: cannot encode RSA public key\");", "\tif (out && out_len)\n\t\tsc_log(ctx, \"encoded public key: %s\", sc_dump_hex(*out, *out_len));", "\tif (bn[0].data)\n\t\tfree(bn[0].data);\n\tif (bn[1].data)\n\t\tfree(bn[1].data);", "\tiasecc_sdo_free_fields(card, &sdo);", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_get_free_reference(struct sc_card *card, struct iasecc_ctl_get_free_reference *ctl_data)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_sdo *sdo = NULL;\n\tint idx, rv;", "\tLOG_FUNC_CALLED(ctx);", "\tif ((ctl_data->key_size % 0x40) || ctl_data->index < 1 || (ctl_data->index > IASECC_OBJECT_REF_MAX))\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);", "\tsc_log(ctx, \"get reference for key(index:%i,usage:%X,access:%X)\", ctl_data->index, ctl_data->usage, ctl_data->access);\n\t/* TODO: when looking for the slot for the signature keys, check also PSO_SIGNATURE ACL */\n\tfor (idx = ctl_data->index; idx <= IASECC_OBJECT_REF_MAX; idx++) {\n\t\tunsigned char sdo_tag[3] = {\n\t\t\tIASECC_SDO_TAG_HEADER, IASECC_OBJECT_REF_LOCAL | IASECC_SDO_CLASS_RSA_PRIVATE, idx\n\t\t};\n\t\tsize_t sz;", "\t\tif (sdo)\n\t\t\tiasecc_sdo_free(card, sdo);", "\t\trv = iasecc_sdo_allocate_and_parse(card, sdo_tag, 3, &sdo);\n\t\tLOG_TEST_RET(ctx, rv, \"cannot parse SDO data\");", "\t\trv = iasecc_sdo_get_data(card, sdo);\n\t\tif (rv == SC_ERROR_DATA_OBJECT_NOT_FOUND) {\n\t\t\tiasecc_sdo_free(card, sdo);", "\t\t\tsc_log(ctx, \"found empty key slot %i\", idx);\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t\tLOG_TEST_RET(ctx, rv, \"get new key reference failed\");", "\t\tsz = *(sdo->docp.size.value + 0) * 0x100 + *(sdo->docp.size.value + 1);\n\t\tsc_log(ctx,\n\t\t \"SDO(idx:%i) size %\"SC_FORMAT_LEN_SIZE_T\"u; key_size %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t\t idx, sz, ctl_data->key_size);", "\t\tif (sz != ctl_data->key_size / 8) {\n\t\t\tsc_log(ctx,\n\t\t\t \"key index %i ignored: different key sizes %\"SC_FORMAT_LEN_SIZE_T\"u/%\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t\t\t idx, sz, ctl_data->key_size / 8);\n\t\t\tcontinue;\n\t\t}", "\t\tif (sdo->docp.non_repudiation.value) {\n\t\t\tsc_log(ctx, \"non repudiation flag %X\", sdo->docp.non_repudiation.value[0]);\n\t\t\tif ((ctl_data->usage & SC_PKCS15_PRKEY_USAGE_NONREPUDIATION) && !(*sdo->docp.non_repudiation.value)) {\n\t\t\t\tsc_log(ctx, \"key index %i ignored: need non repudiation\", idx);\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tif (!(ctl_data->usage & SC_PKCS15_PRKEY_USAGE_NONREPUDIATION) && *sdo->docp.non_repudiation.value) {\n\t\t\t\tsc_log(ctx, \"key index %i ignored: don't need non-repudiation\", idx);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}", "\t\tif (ctl_data->access & SC_PKCS15_PRKEY_ACCESS_LOCAL) {\n\t\t\tif (sdo->docp.scbs[IASECC_ACLS_RSAKEY_GENERATE] == IASECC_SCB_NEVER) {\n\t\t\t\tsc_log(ctx, \"key index %i ignored: GENERATE KEY not allowed\", idx);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (sdo->docp.scbs[IASECC_ACLS_RSAKEY_PUT_DATA] == IASECC_SCB_NEVER) {\n\t\t\t\tsc_log(ctx, \"key index %i ignored: PUT DATA not allowed\", idx);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}", "\t\tif ((ctl_data->usage & SC_PKCS15_PRKEY_USAGE_NONREPUDIATION) && (ctl_data->usage & SC_PKCS15_PRKEY_USAGE_SIGN)) {\n\t\t\tif (sdo->docp.scbs[IASECC_ACLS_RSAKEY_PSO_SIGN] == IASECC_SCB_NEVER) {\n\t\t\t\tsc_log(ctx, \"key index %i ignored: PSO SIGN not allowed\", idx);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\telse if (ctl_data->usage & SC_PKCS15_PRKEY_USAGE_SIGN) {\n\t\t\tif (sdo->docp.scbs[IASECC_ACLS_RSAKEY_INTERNAL_AUTH] == IASECC_SCB_NEVER) {\n\t\t\t\tsc_log(ctx, \"key index %i ignored: INTERNAL AUTHENTICATE not allowed\", idx);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}", "\t\tif (ctl_data->usage & (SC_PKCS15_PRKEY_USAGE_DECRYPT | SC_PKCS15_PRKEY_USAGE_UNWRAP)) {\n\t\t\tif (sdo->docp.scbs[IASECC_ACLS_RSAKEY_PSO_DECIPHER] == IASECC_SCB_NEVER) {\n\t\t\t\tsc_log(ctx, \"key index %i ignored: PSO DECIPHER not allowed\", idx);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}", "\t\tbreak;\n\t}", "\tctl_data->index = idx;", "\tif (idx > IASECC_OBJECT_REF_MAX)\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_DATA_OBJECT_NOT_FOUND);", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic struct sc_card_driver *\nsc_get_driver(void)\n{\n\tstruct sc_card_driver *iso_drv = sc_get_iso7816_driver();", "\tif (!iso_ops)\n\t\tiso_ops = iso_drv->ops;", "\tiasecc_ops = *iso_ops;", "\tiasecc_ops.match_card = iasecc_match_card;\n\tiasecc_ops.init = iasecc_init;\n\tiasecc_ops.finish = iasecc_finish;\n\tiasecc_ops.read_binary = iasecc_read_binary;\n\t/*\twrite_binary: ISO7816 implementation works\t*/\n\t/*\tupdate_binary: ISO7816 implementation works\t*/\n\tiasecc_ops.erase_binary = iasecc_erase_binary;\n\t/*\tresize_binary\t*/\n\t/* \tread_record: Untested\t*/\n\t/*\twrite_record: Untested\t*/\n\t/*\tappend_record: Untested\t*/\n\t/*\tupdate_record: Untested\t*/\n\tiasecc_ops.select_file = iasecc_select_file;\n\t/*\tget_response: Untested\t*/\n\t/*\tget_challenge: ISO7816 implementation works\t*/\n\tiasecc_ops.logout = iasecc_logout;\n\t/*\trestore_security_env\t*/\n\tiasecc_ops.set_security_env = iasecc_set_security_env;\n\tiasecc_ops.decipher = iasecc_decipher;\n\tiasecc_ops.compute_signature = iasecc_compute_signature;\n\tiasecc_ops.create_file = iasecc_create_file;\n\tiasecc_ops.delete_file = iasecc_delete_file;\n\t/*\tlist_files\t*/\n\tiasecc_ops.check_sw = iasecc_check_sw;\n\tiasecc_ops.card_ctl = iasecc_card_ctl;\n\tiasecc_ops.process_fci = iasecc_process_fci;\n\t/*\tconstruct_fci: Not needed\t*/\n\tiasecc_ops.pin_cmd = iasecc_pin_cmd;\n\t/*\tget_data: Not implemented\t*/\n\t/*\tput_data: Not implemented\t*/\n\t/*\tdelete_record: Not implemented\t*/", "\tiasecc_ops.read_public_key = iasecc_read_public_key;", "\treturn &iasecc_drv;\n}", "struct sc_card_driver *\nsc_get_iasecc_driver(void)\n{\n\treturn sc_get_driver();\n}", "#else", "/* we need to define the functions below to export them */\n#include \"errors.h\"", "int\niasecc_se_get_info()\n{\n\treturn SC_ERROR_NOT_SUPPORTED;\n}", "#endif /* ENABLE_OPENSSL */" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [840], "buggy_code_start_loc": [830], "filenames": ["src/libopensc/card-iasecc.c"], "fixing_code_end_loc": [840], "fixing_code_start_loc": [830], "message": "Endless recursion when handling responses from an IAS-ECC card in iasecc_select_file in libopensc/card-iasecc.c in OpenSC before 0.19.0-rc1 could be used by attackers able to supply crafted smartcards to hang or crash the opensc library using programs.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:opensc_project:opensc:*:*:*:*:*:*:*:*", "matchCriteriaId": "85C3EC93-1A01-4E7D-9730-F8429C1CD145", "versionEndExcluding": null, "versionEndIncluding": "0.18.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Endless recursion when handling responses from an IAS-ECC card in iasecc_select_file in libopensc/card-iasecc.c in OpenSC before 0.19.0-rc1 could be used by attackers able to supply crafted smartcards to hang or crash the opensc library using programs."}, {"lang": "es", "value": "Una recursi\u00f3n infinita al manejar las respuestas de una tarjeta IAS-ECC en iasecc_select_file en libopensc/card-iasecc.c en OpenSC en versiones anteriores a la 0.19.0-rc1 podr\u00eda ser empleada por atacantes para proporcionar smartcards manipuladas para provocar el bloqueo o el cierre inesperado de la librer\u00eda opensc mediante programas."}], "evaluatorComment": null, "id": "CVE-2018-16426", "lastModified": "2019-10-03T00:03:26.223", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 2.1, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "PHYSICAL", "availabilityImpact": "HIGH", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:P/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 0.7, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-09-04T00:29:01.293", "references": [{"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2019:2154"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/OpenSC/OpenSC/commit/03628449b75a93787eb2359412a3980365dda49b#diff-f8c0128e14031ed9307d47f10f601b54"}, {"source": "cve@mitre.org", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/OpenSC/OpenSC/releases/tag/0.19.0-rc1"}, {"source": "cve@mitre.org", "tags": null, "url": "https://lists.debian.org/debian-lts-announce/2019/09/msg00009.html"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://www.x41-dsec.de/lab/advisories/x41-2018-002-OpenSC/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-674"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/OpenSC/OpenSC/commit/03628449b75a93787eb2359412a3980365dda49b#diff-f8c0128e14031ed9307d47f10f601b54"}, "type": "CWE-674"}
198
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * card-iasecc.c: Support for IAS/ECC smart cards\n *\n * Copyright (C) 2010 Viktor Tarasov <vtarasov@gmail.com>\n *\t\t\tOpenTrust <www.opentrust.com>\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n */", "#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif", "#ifdef ENABLE_OPENSSL /* empty file without openssl */", "#include <string.h>\n#include <stdlib.h>", "#include <openssl/bn.h>\n#include <openssl/evp.h>\n#include <openssl/pem.h>\n#include <openssl/err.h>\n#include <openssl/rand.h>\n#include <openssl/sha.h>\n#include <openssl/rsa.h>\n#include <openssl/pkcs12.h>\n#include <openssl/x509v3.h>", "#include \"internal.h\"\n#include \"asn1.h\"\n#include \"cardctl.h\"\n#include \"opensc.h\"\n/* #include \"sm.h\" */\n#include \"pkcs15.h\"\n/* #include \"hash-strings.h\" */\n#include \"gp.h\"", "#include \"iasecc.h\"", "#define IASECC_CARD_DEFAULT_FLAGS ( 0\t\t\t\\\n\t\t| SC_ALGORITHM_ONBOARD_KEY_GEN\t\t\\\n\t\t| SC_ALGORITHM_RSA_PAD_ISO9796\t\t\\\n\t\t| SC_ALGORITHM_RSA_PAD_PKCS1\t\t\\\n\t\t| SC_ALGORITHM_RSA_HASH_NONE\t\t\\\n\t\t| SC_ALGORITHM_RSA_HASH_SHA1\t\t\\\n\t\t| SC_ALGORITHM_RSA_HASH_SHA256)", "/* generic iso 7816 operations table */\nstatic const struct sc_card_operations *iso_ops = NULL;", "/* our operations table with overrides */\nstatic struct sc_card_operations iasecc_ops;", "static struct sc_card_driver iasecc_drv = {\n\t\"IAS-ECC\",\n\t\"iasecc\",\n\t&iasecc_ops,\n\tNULL, 0, NULL\n};", "static struct sc_atr_table iasecc_known_atrs[] = {\n\t{ \"3B:7F:96:00:00:00:31:B8:64:40:70:14:10:73:94:01:80:82:90:00\",\n\t \"FF:FF:FF:FF:FF:FF:FF:FE:FF:FF:00:00:FF:FF:FF:FF:FF:FF:FF:FF\",\n\t\t\"IAS/ECC Gemalto\", SC_CARD_TYPE_IASECC_GEMALTO, 0, NULL },\n { \"3B:DD:18:00:81:31:FE:45:80:F9:A0:00:00:00:77:01:08:00:07:90:00:FE\", NULL,\n\t\t\"IAS/ECC v1.0.1 Oberthur\", SC_CARD_TYPE_IASECC_OBERTHUR, 0, NULL },\n\t{ \"3B:7D:13:00:00:4D:44:57:2D:49:41:53:2D:43:41:52:44:32\", NULL,\n\t\t\"IAS/ECC v1.0.1 Sagem MDW-IAS-CARD2\", SC_CARD_TYPE_IASECC_SAGEM, 0, NULL },\n\t{ \"3B:7F:18:00:00:00:31:B8:64:50:23:EC:C1:73:94:01:80:82:90:00\", NULL,\n\t\t\"IAS/ECC v1.0.1 Sagem ypsID S3\", SC_CARD_TYPE_IASECC_SAGEM, 0, NULL },\n\t{ \"3B:DF:96:00:80:31:FE:45:00:31:B8:64:04:1F:EC:C1:73:94:01:80:82:90:00:EC\", NULL,\n\t\t\"IAS/ECC Morpho MinInt - Agent Card\", SC_CARD_TYPE_IASECC_MI, 0, NULL },\n\t{ \"3B:DF:18:FF:81:91:FE:1F:C3:00:31:B8:64:0C:01:EC:C1:73:94:01:80:82:90:00:B3\", NULL,\n\t\t\"IAS/ECC v1.0.1 Amos\", SC_CARD_TYPE_IASECC_AMOS, 0, NULL },\n\t{ \"3B:DC:18:FF:81:91:FE:1F:C3:80:73:C8:21:13:66:02:04:03:55:00:02:34\", NULL,\n\t\t\"IAS/ECC v1.0.1 Amos\", SC_CARD_TYPE_IASECC_AMOS, 0, NULL },\n\t{ \"3B:DC:18:FF:81:91:FE:1F:C3:80:73:C8:21:13:66:01:0B:03:52:00:05:38\", NULL,\n\t\t\"IAS/ECC v1.0.1 Amos\", SC_CARD_TYPE_IASECC_AMOS, 0, NULL },\n\t{ NULL, NULL, NULL, 0, 0, NULL }\n};", "static struct sc_aid OberthurIASECC_AID = {\n\t{0xA0,0x00,0x00,0x00,0x77,0x01,0x08,0x00,0x07,0x00,0x00,0xFE,0x00,0x00,0x01,0x00}, 16\n};", "static struct sc_aid MIIASECC_AID = {\n\t{ 0x4D, 0x49, 0x4F, 0x4D, 0x43, 0x54}, 6\n};", "struct iasecc_pin_status {\n\tunsigned char sha1[SHA_DIGEST_LENGTH];\n\tunsigned char reference;", "\tstruct iasecc_pin_status *next;\n\tstruct iasecc_pin_status *prev;\n};", "struct iasecc_pin_status *checked_pins = NULL;", "static int iasecc_select_file(struct sc_card *card, const struct sc_path *path, struct sc_file **file_out);\nstatic int iasecc_process_fci(struct sc_card *card, struct sc_file *file, const unsigned char *buf, size_t buflen);\nstatic int iasecc_get_serialnr(struct sc_card *card, struct sc_serial_number *serial);\nstatic int iasecc_sdo_get_data(struct sc_card *card, struct iasecc_sdo *sdo);\nstatic int iasecc_pin_get_policy (struct sc_card *card, struct sc_pin_cmd_data *data);\nstatic int iasecc_pin_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd, int *tries_left);\nstatic int iasecc_get_free_reference(struct sc_card *card, struct iasecc_ctl_get_free_reference *ctl_data);\nstatic int iasecc_sdo_put_data(struct sc_card *card, struct iasecc_sdo_update *update);", "#ifdef ENABLE_SM\nstatic int _iasecc_sm_read_binary(struct sc_card *card, unsigned int offs, unsigned char *buf, size_t count);\nstatic int _iasecc_sm_update_binary(struct sc_card *card, unsigned int offs, const unsigned char *buff, size_t count);\n#endif", "static int\niasecc_chv_cache_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_pin_status *pin_status = NULL, *current = NULL;", "\tLOG_FUNC_CALLED(ctx);", "\tfor(current = checked_pins; current; current = current->next)\n\t\tif (current->reference == pin_cmd->pin_reference)\n\t\t\tbreak;", "\tif (current) {\n\t\tsc_log(ctx, \"iasecc_chv_cache_verified() current PIN-%i\", current->reference);\n\t\tpin_status = current;\n\t}\n\telse {\n\t\tpin_status = calloc(1, sizeof(struct iasecc_pin_status));\n\t\tif (!pin_status)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, \"Cannot callocate PIN status info\");\n\t\tsc_log(ctx, \"iasecc_chv_cache_verified() allocated %p\", pin_status);\n\t}", "\tpin_status->reference = pin_cmd->pin_reference;\n\tif (pin_cmd->pin1.data)\n\t\tSHA1(pin_cmd->pin1.data, pin_cmd->pin1.len, pin_status->sha1);\n\telse\n\t\tmemset(pin_status->sha1, 0, SHA_DIGEST_LENGTH);", "\tsc_log_hex(ctx, \"iasecc_chv_cache_verified() sha1(PIN)\", pin_status->sha1, SHA_DIGEST_LENGTH);", "\tif (!current) {\n\t\tif (!checked_pins) {\n\t\t\tchecked_pins = pin_status;\n\t\t}\n\t\telse {\n\t\tchecked_pins->prev = pin_status;\n\t\t\tpin_status->next = checked_pins;\n\t\t\tchecked_pins = pin_status;\n\t\t}\n\t}", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_chv_cache_clean(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_pin_status *current = NULL;", "\tLOG_FUNC_CALLED(ctx);", "\tfor(current = checked_pins; current; current = current->next)\n\t\tif (current->reference == pin_cmd->pin_reference)\n\t\t\tbreak;", "\tif (!current)\n\t\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);", "\n\tif (current->next && current->prev) {\n\t\tcurrent->prev->next = current->next;\n\t\tcurrent->next->prev = current->prev;\n\t}\n\telse if (!current->prev) {\n\t\tchecked_pins = current->next;\n\t}\n\telse if (!current->next && current->prev) {\n\t\tcurrent->prev->next = NULL;\n\t}", "\tfree(current);\n\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic struct iasecc_pin_status *\niasecc_chv_cache_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_pin_status *current = NULL;\n\tunsigned char data_sha1[SHA_DIGEST_LENGTH];", "\tLOG_FUNC_CALLED(ctx);", "\tif (pin_cmd->pin1.data)\n\t\tSHA1(pin_cmd->pin1.data, pin_cmd->pin1.len, data_sha1);\n\telse\n\t\tmemset(data_sha1, 0, SHA_DIGEST_LENGTH);\n\tsc_log_hex(ctx, \"data_sha1: %s\", data_sha1, SHA_DIGEST_LENGTH);", "\tfor(current = checked_pins; current; current = current->next)\n\t\tif (current->reference == pin_cmd->pin_reference)\n\t\t\tbreak;", "\tif (current && !memcmp(data_sha1, current->sha1, SHA_DIGEST_LENGTH)) {\n\t\tsc_log(ctx, \"PIN-%i status 'verified'\", pin_cmd->pin_reference);\n\t\treturn current;\n\t}", "\tsc_log(ctx, \"PIN-%i status 'not verified'\", pin_cmd->pin_reference);\n\treturn NULL;\n}", "\nstatic int\niasecc_select_mf(struct sc_card *card, struct sc_file **file_out)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_file *mf_file = NULL;\n\tstruct sc_path path;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);", "\tif (file_out)\n\t\t*file_out = NULL;", "\tmemset(&path, 0, sizeof(struct sc_path));\n\tif (!card->ef_atr || !card->ef_atr->aid.len) {\n\t\tstruct sc_apdu apdu;\n\t\tunsigned char apdu_resp[SC_MAX_APDU_BUFFER_SIZE];", "\t\t/* ISO 'select' command fails when not FCP data returned */\n\t\tsc_format_path(\"3F00\", &path);\n\t\tpath.type = SC_PATH_TYPE_FILE_ID;", "\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 0x00, 0x00);\n\t\tapdu.lc = path.len;\n\t\tapdu.data = path.value;\n\t\tapdu.datalen = path.len;\n\t\tapdu.resplen = sizeof(apdu_resp);\n\t\tapdu.resp = apdu_resp;", "\t\tif (card->type == SC_CARD_TYPE_IASECC_MI2)\n\t\t\tapdu.p2 = 0x04;", "\t\trv = sc_transmit_apdu(card, &apdu);\n\t\tLOG_TEST_RET(card->ctx, rv, \"APDU transmit failed\");\n\t\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\t\tLOG_TEST_RET(card->ctx, rv, \"Cannot select MF\");\n\t}\n\telse {\n\t\tmemset(&path, 0, sizeof(path));\n\t\tpath.type = SC_PATH_TYPE_DF_NAME;\n\t\tmemcpy(path.value, card->ef_atr->aid.value, card->ef_atr->aid.len);\n\t\tpath.len = card->ef_atr->aid.len;\n\t\trv = iasecc_select_file(card, &path, file_out);\n\t\tLOG_TEST_RET(ctx, rv, \"Unable to ROOT selection\");\n\t}", "\t/* Ignore the FCP of the MF, because:\n\t * - some cards do not return it;\n\t * - there is not need of it -- create/delete of the files in MF is not envisaged.\n\t */\n\tmf_file = sc_file_new();\n\tif (mf_file == NULL)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, \"Cannot allocate MF file\");\n\tmf_file->type = SC_FILE_TYPE_DF;\n\tmf_file->path = path;", "\tif (card->cache.valid)\n\t\t sc_file_free(card->cache.current_df);\n\tcard->cache.current_df = NULL;", "\tif (card->cache.valid)\n\t\tsc_file_free(card->cache.current_ef);\n\tcard->cache.current_ef = NULL;", "\tsc_file_dup(&card->cache.current_df, mf_file);\n\tcard->cache.valid = 1;", "\tif (file_out && *file_out == NULL)\n\t\t*file_out = mf_file;\n\telse\n\t\tsc_file_free(mf_file);", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_select_aid(struct sc_card *card, struct sc_aid *aid, unsigned char *out, size_t *out_len)\n{\n\tstruct sc_apdu apdu;\n\tunsigned char apdu_resp[SC_MAX_APDU_BUFFER_SIZE];\n\tint rv;", "\t/* Select application (deselect previously selected application) */\n\tsc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x04, 0x00);\n\tapdu.lc = aid->len;\n\tapdu.data = aid->value;\n\tapdu.datalen = aid->len;\n\tapdu.resplen = sizeof(apdu_resp);\n\tapdu.resp = apdu_resp;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(card->ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(card->ctx, rv, \"Cannot select AID\");", "\tif (*out_len < apdu.resplen)\n\t\tLOG_TEST_RET(card->ctx, SC_ERROR_BUFFER_TOO_SMALL, \"Cannot select AID\");\n\tmemcpy(out, apdu.resp, apdu.resplen);", "\treturn SC_SUCCESS;\n}", "\nstatic int\niasecc_match_card(struct sc_card *card)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tint i;", "\ti = _sc_match_atr(card, iasecc_known_atrs, &card->type);\n\tif (i < 0) {\n\t\tsc_log(ctx, \"card not matched\");\n\t\treturn 0;\n\t}", "\tsc_log(ctx, \"'%s' card matched\", iasecc_known_atrs[i].name);\n\treturn 1;\n}", "\nstatic int iasecc_parse_ef_atr(struct sc_card *card)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_private_data *pdata = (struct iasecc_private_data *) card->drv_data;\n\tstruct iasecc_version *version = &pdata->version;\n\tstruct iasecc_io_buffer_sizes *sizes = &pdata->max_sizes;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\trv = sc_parse_ef_atr(card);\n\tLOG_TEST_RET(ctx, rv, \"MF selection error\");", "\tif (card->ef_atr->pre_issuing_len < 4)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"Invalid pre-issuing data\");", "\tversion->ic_manufacturer =\tcard->ef_atr->pre_issuing[0];\n\tversion->ic_type =\t\tcard->ef_atr->pre_issuing[1];\n\tversion->os_version =\t\tcard->ef_atr->pre_issuing[2];\n\tversion->iasecc_version =\tcard->ef_atr->pre_issuing[3];\n\tsc_log(ctx, \"EF.ATR: IC manufacturer/type %X/%X, OS/IasEcc versions %X/%X\",\n\t\tversion->ic_manufacturer, version->ic_type, version->os_version, version->iasecc_version);", "\tif (card->ef_atr->issuer_data_len < 16)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"Invalid issuer data\");", "\tsizes->send =\t card->ef_atr->issuer_data[2] * 0x100 + card->ef_atr->issuer_data[3];\n\tsizes->send_sc = card->ef_atr->issuer_data[6] * 0x100 + card->ef_atr->issuer_data[7];\n\tsizes->recv =\t card->ef_atr->issuer_data[10] * 0x100 + card->ef_atr->issuer_data[11];\n\tsizes->recv_sc = card->ef_atr->issuer_data[14] * 0x100 + card->ef_atr->issuer_data[15];", "\tcard->max_send_size = sizes->send;\n\tcard->max_recv_size = sizes->recv;", "\t/* Most of the card producers interpret 'send' values as \"maximum APDU data size\".\n\t * Oberthur strictly follows specification and interpret these values as \"maximum APDU command size\".\n\t * Here we need 'data size'.\n\t */\n\tif (card->max_send_size > 0xFF)\n\t\tcard->max_send_size -= 5;", "\tsc_log(ctx,\n\t \"EF.ATR: max send/recv sizes %\"SC_FORMAT_LEN_SIZE_T\"X/%\"SC_FORMAT_LEN_SIZE_T\"X\",\n\t card->max_send_size, card->max_recv_size);", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_init_gemalto(struct sc_card *card)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_path path;\n\tunsigned int flags;\n\tint rv = 0;", "\tLOG_FUNC_CALLED(ctx);", "\tflags = IASECC_CARD_DEFAULT_FLAGS;", "\t_sc_card_add_rsa_alg(card, 1024, flags, 0x10001);\n\t_sc_card_add_rsa_alg(card, 2048, flags, 0x10001);", "\tcard->caps = SC_CARD_CAP_RNG;\n\tcard->caps |= SC_CARD_CAP_APDU_EXT;\n\tcard->caps |= SC_CARD_CAP_USE_FCI_AC;", "\tsc_format_path(\"3F00\", &path);\n\trv = sc_select_file(card, &path, NULL);\n\t/* Result ignored*/", "\trv = iasecc_parse_ef_atr(card);\n\tsc_log(ctx, \"rv %i\", rv);\n\tif (rv == SC_ERROR_FILE_NOT_FOUND) {\n\t\tsc_log(ctx, \"Select MF\");\n\t\trv = iasecc_select_mf(card, NULL);\n\t\tsc_log(ctx, \"rv %i\", rv);\n\t\tLOG_TEST_RET(ctx, rv, \"MF selection error\");", "\t\trv = iasecc_parse_ef_atr(card);\n\t\tsc_log(ctx, \"rv %i\", rv);\n\t}\n\tsc_log(ctx, \"rv %i\", rv);\n\tLOG_TEST_RET(ctx, rv, \"Cannot read/parse EF.ATR\");", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_oberthur_match(struct sc_card *card)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tunsigned char *hist = card->reader->atr_info.hist_bytes;", "\tLOG_FUNC_CALLED(ctx);", "\tif (*hist != 0x80 || ((*(hist+1)&0xF0) != 0xF0))\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_OBJECT_NOT_FOUND);", "\tsc_log_hex(ctx, \"AID in historical_bytes\", hist + 2, *(hist+1) & 0x0F);", "\tif (memcmp(hist + 2, OberthurIASECC_AID.value, *(hist+1) & 0x0F))\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_RECORD_NOT_FOUND);", "\tif (!card->ef_atr)\n\t\tcard->ef_atr = calloc(1, sizeof(struct sc_ef_atr));\n\tif (!card->ef_atr)\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);", "\tmemcpy(card->ef_atr->aid.value, OberthurIASECC_AID.value, OberthurIASECC_AID.len);\n\tcard->ef_atr->aid.len = OberthurIASECC_AID.len;", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_init_oberthur(struct sc_card *card)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tunsigned int flags;\n\tint rv = 0;", "\tLOG_FUNC_CALLED(ctx);", "\tflags = IASECC_CARD_DEFAULT_FLAGS;", "\t_sc_card_add_rsa_alg(card, 1024, flags, 0x10001);\n\t_sc_card_add_rsa_alg(card, 2048, flags, 0x10001);", "\tcard->caps = SC_CARD_CAP_RNG;\n\tcard->caps |= SC_CARD_CAP_APDU_EXT;\n\tcard->caps |= SC_CARD_CAP_USE_FCI_AC;", "\tiasecc_parse_ef_atr(card);", "\t/* if we fail to select CM, */\n\tif (gp_select_card_manager(card)) {\n\t\tgp_select_isd_rid(card);\n\t}", "\trv = iasecc_oberthur_match(card);\n\tLOG_TEST_RET(ctx, rv, \"unknown Oberthur's IAS/ECC card\");", "\trv = iasecc_select_mf(card, NULL);\n\tLOG_TEST_RET(ctx, rv, \"MF selection error\");", "\trv = iasecc_parse_ef_atr(card);\n\tLOG_TEST_RET(ctx, rv, \"EF.ATR read or parse error\");", "\tsc_log(ctx, \"EF.ATR(aid:'%s')\", sc_dump_hex(card->ef_atr->aid.value, card->ef_atr->aid.len));\n\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_mi_match(struct sc_card *card)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tunsigned char resp[0x100];\n\tsize_t resp_len;\n\tint rv = 0;", "\tLOG_FUNC_CALLED(ctx);", "\tresp_len = sizeof(resp);\n\trv = iasecc_select_aid(card, &MIIASECC_AID, resp, &resp_len);\n\tLOG_TEST_RET(ctx, rv, \"IASECC: failed to select MI IAS/ECC applet\");", "\tif (!card->ef_atr)\n\t\tcard->ef_atr = calloc(1, sizeof(struct sc_ef_atr));\n\tif (!card->ef_atr)\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);", "\tmemcpy(card->ef_atr->aid.value, MIIASECC_AID.value, MIIASECC_AID.len);\n\tcard->ef_atr->aid.len = MIIASECC_AID.len;", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_init_amos_or_sagem(struct sc_card *card)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tunsigned int flags;\n\tint rv = 0;", "\tLOG_FUNC_CALLED(ctx);", "\tflags = IASECC_CARD_DEFAULT_FLAGS;", "\t_sc_card_add_rsa_alg(card, 1024, flags, 0x10001);\n\t_sc_card_add_rsa_alg(card, 2048, flags, 0x10001);", "\tcard->caps = SC_CARD_CAP_RNG;\n\tcard->caps |= SC_CARD_CAP_APDU_EXT;\n\tcard->caps |= SC_CARD_CAP_USE_FCI_AC;", "\tif (card->type == SC_CARD_TYPE_IASECC_MI) {\n\t\trv = iasecc_mi_match(card);\n\t\tif (rv)\n\t\t\tcard->type = SC_CARD_TYPE_IASECC_MI2;\n\t\telse\n\t\t\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n\t}", "\trv = iasecc_parse_ef_atr(card);\n\tif (rv == SC_ERROR_FILE_NOT_FOUND) {\n\t\trv = iasecc_select_mf(card, NULL);\n\t\tLOG_TEST_RET(ctx, rv, \"MF selection error\");", "\t\trv = iasecc_parse_ef_atr(card);\n\t}\n\tLOG_TEST_RET(ctx, rv, \"IASECC: ATR parse failed\");", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_init(struct sc_card *card)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_private_data *private_data = NULL;\n\tint rv = SC_ERROR_NO_CARD_SUPPORT;", "\tLOG_FUNC_CALLED(ctx);\n\tprivate_data = (struct iasecc_private_data *) calloc(1, sizeof(struct iasecc_private_data));\n\tif (private_data == NULL)\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);", "\tcard->cla = 0x00;\n\tcard->drv_data = private_data;", "\tif (card->type == SC_CARD_TYPE_IASECC_GEMALTO)\n\t\trv = iasecc_init_gemalto(card);\n\telse if (card->type == SC_CARD_TYPE_IASECC_OBERTHUR)\n\t\trv = iasecc_init_oberthur(card);\n\telse if (card->type == SC_CARD_TYPE_IASECC_SAGEM)\n\t\trv = iasecc_init_amos_or_sagem(card);\n\telse if (card->type == SC_CARD_TYPE_IASECC_AMOS)\n\t\trv = iasecc_init_amos_or_sagem(card);\n\telse if (card->type == SC_CARD_TYPE_IASECC_MI)\n\t\trv = iasecc_init_amos_or_sagem(card);\n\telse\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_CARD);", "\n\tif (!rv) {\n\t\tif (card->ef_atr && card->ef_atr->aid.len) {\n\t\t\tstruct sc_path path;", "\t\t\tmemset(&path, 0, sizeof(struct sc_path));\n\t\t\tpath.type = SC_PATH_TYPE_DF_NAME;\n\t\t\tmemcpy(path.value, card->ef_atr->aid.value, card->ef_atr->aid.len);\n\t\t\tpath.len = card->ef_atr->aid.len;", "\t\t\trv = iasecc_select_file(card, &path, NULL);\n\t\t\tsc_log(ctx, \"Select ECC ROOT with the AID from EF.ATR: rv %i\", rv);\n\t\t\tLOG_TEST_RET(ctx, rv, \"Select EF.ATR AID failed\");\n\t\t}", "\t\trv = iasecc_get_serialnr(card, NULL);\n\t}", "#ifdef ENABLE_SM\n\tcard->sm_ctx.ops.read_binary = _iasecc_sm_read_binary;\n\tcard->sm_ctx.ops.update_binary = _iasecc_sm_update_binary;\n#endif", "\tif (!rv) {\n\t\tsc_log(ctx, \"EF.ATR(aid:'%s')\", sc_dump_hex(card->ef_atr->aid.value, card->ef_atr->aid.len));\n\t\trv = SC_ERROR_INVALID_CARD;\n\t}\n\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_read_binary(struct sc_card *card, unsigned int offs,\n\t\tunsigned char *buf, size_t count, unsigned long flags)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_apdu apdu;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx,\n\t \"iasecc_read_binary(card:%p) offs %i; count %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t card, offs, count);\n\tif (offs > 0x7fff) {\n\t\tsc_log(ctx, \"invalid EF offset: 0x%X > 0x7FFF\", offs);\n\t\treturn SC_ERROR_OFFSET_TOO_LARGE;\n\t}", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xB0, (offs >> 8) & 0x7F, offs & 0xFF);\n\tapdu.le = count < 0x100 ? count : 0x100;\n\tapdu.resplen = count;\n\tapdu.resp = buf;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"iasecc_read_binary() failed\");\n\tsc_log(ctx,\n\t \"iasecc_read_binary() apdu.resplen %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t apdu.resplen);", "\tif (apdu.resplen == IASECC_READ_BINARY_LENGTH_MAX && apdu.resplen < count) {\n\t\trv = iasecc_read_binary(card, offs + apdu.resplen, buf + apdu.resplen, count - apdu.resplen, flags);\n\t\tif (rv != SC_ERROR_WRONG_LENGTH) {\n\t\t\tLOG_TEST_RET(ctx, rv, \"iasecc_read_binary() read tail failed\");\n\t\t\tapdu.resplen += rv;\n\t\t}\n\t}", "\tLOG_FUNC_RETURN(ctx, apdu.resplen);\n}", "\nstatic int\niasecc_erase_binary(struct sc_card *card, unsigned int offs, size_t count, unsigned long flags)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tunsigned char *tmp = NULL;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx,\n\t \"iasecc_erase_binary(card:%p) count %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t card, count);\n\tif (!count)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"'ERASE BINARY' failed: invalid size to erase\");", "\ttmp = malloc(count);\n\tif (!tmp)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, \"Cannot allocate temporary buffer\");\n\tmemset(tmp, 0xFF, count);", "\trv = sc_update_binary(card, offs, tmp, count, flags);\n\tfree(tmp);\n\tLOG_TEST_RET(ctx, rv, \"iasecc_erase_binary() update binary error\");\n\tLOG_FUNC_RETURN(ctx, rv);\n}", "\n#if ENABLE_SM\nstatic int\n_iasecc_sm_read_binary(struct sc_card *card, unsigned int offs,\n\t\tunsigned char *buff, size_t count)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tconst struct sc_acl_entry *entry = NULL;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx,\n\t \"iasecc_sm_read_binary() card:%p offs:%i count:%\"SC_FORMAT_LEN_SIZE_T\"u \",\n\t card, offs, count);\n\tif (offs > 0x7fff)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_OFFSET_TOO_LARGE, \"Invalid arguments\");", "\tif (count == 0)\n\t\treturn 0;", "\tsc_print_cache(card);", "\tif (card->cache.valid && card->cache.current_ef) {\n\t\tentry = sc_file_get_acl_entry(card->cache.current_ef, SC_AC_OP_READ);\n\t\tif (!entry)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, \"iasecc_sm_read() 'READ' ACL not present\");", "\t\tsc_log(ctx, \"READ method/reference %X/%X\", entry->method, entry->key_ref);\n\t\tif ((entry->method == SC_AC_SCB) && (entry->key_ref & IASECC_SCB_METHOD_SM)) {\n\t\t\tunsigned char se_num = (entry->method == SC_AC_SCB) ? (entry->key_ref & IASECC_SCB_METHOD_MASK_REF) : 0;", "\t\t\trv = iasecc_sm_read_binary(card, se_num, offs, buff, count);\n\t\t\tLOG_FUNC_RETURN(ctx, rv);\n\t\t}\n\t}", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\n_iasecc_sm_update_binary(struct sc_card *card, unsigned int offs,\n\t\tconst unsigned char *buff, size_t count)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tconst struct sc_acl_entry *entry = NULL;\n\tint rv;", "\tif (count == 0)\n\t\treturn SC_SUCCESS;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx,\n\t \"iasecc_sm_read_binary() card:%p offs:%i count:%\"SC_FORMAT_LEN_SIZE_T\"u \",\n\t card, offs, count);\n\tsc_print_cache(card);", "\tif (card->cache.valid && card->cache.current_ef) {\n\t\tentry = sc_file_get_acl_entry(card->cache.current_ef, SC_AC_OP_UPDATE);\n\t\tif (!entry)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, \"iasecc_sm_update() 'UPDATE' ACL not present\");", "\t\tsc_log(ctx, \"UPDATE method/reference %X/%X\", entry->method, entry->key_ref);\n\t\tif (entry->method == SC_AC_SCB && (entry->key_ref & IASECC_SCB_METHOD_SM)) {\n\t\t\tunsigned char se_num = entry->method == SC_AC_SCB ? entry->key_ref & IASECC_SCB_METHOD_MASK_REF : 0;", "\t\t\trv = iasecc_sm_update_binary(card, se_num, offs, buff, count);\n\t\t\tLOG_FUNC_RETURN(ctx, rv);\n\t\t}\n\t}", "\tLOG_FUNC_RETURN(ctx, 0);\n}\n#endif", "\nstatic int\niasecc_emulate_fcp(struct sc_context *ctx, struct sc_apdu *apdu)\n{\n\tunsigned char dummy_df_fcp[] = {\n\t\t0x62,0xFF,\n\t\t\t0x82,0x01,0x38,\n\t\t\t0x8A,0x01,0x05,\n\t\t\t0xA1,0x04,0x8C,0x02,0x02,0x00,\n\t\t\t0x84,0xFF,\n\t\t\t\t0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,\n\t\t\t\t0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF\n\t};", "\tLOG_FUNC_CALLED(ctx);", "\tif (apdu->p1 != 0x04)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"FCP emulation supported only for the DF-NAME selection type\");\n\tif (apdu->datalen > 16)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"Invalid DF-NAME length\");\n\tif (apdu->resplen < apdu->datalen + 16)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, \"not enough space for FCP data\");", "\tmemcpy(dummy_df_fcp + 16, apdu->data, apdu->datalen);\n\tdummy_df_fcp[15] = apdu->datalen;\n\tdummy_df_fcp[1] = apdu->datalen + 14;\n\tmemcpy(apdu->resp, dummy_df_fcp, apdu->datalen + 16);", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\n/* TODO: redesign using of cache\n * TODO: do not keep intermediate results in 'file_out' argument */\nstatic int\niasecc_select_file(struct sc_card *card, const struct sc_path *path,\n\t\t struct sc_file **file_out)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_path lpath;\n\tint cache_valid = card->cache.valid, df_from_cache = 0;\n\tint rv, ii;", "\tLOG_FUNC_CALLED(ctx);\n\tmemcpy(&lpath, path, sizeof(struct sc_path));\n\tif (file_out)\n\t\t*file_out = NULL;", "\tsc_log(ctx,\n\t \"iasecc_select_file(card:%p) path.len %\"SC_FORMAT_LEN_SIZE_T\"u; path.type %i; aid_len %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t card, path->len, path->type, path->aid.len);\n\tsc_log(ctx, \"iasecc_select_file() path:%s\", sc_print_path(path));", "\tsc_print_cache(card);", "\tif (path->type != SC_PATH_TYPE_DF_NAME\n\t\t\t&& lpath.len >= 2\n\t\t\t&& lpath.value[0] == 0x3F && lpath.value[1] == 0x00) {", "\t\tsc_log(ctx, \"EF.ATR(aid:'%s')\", card->ef_atr ? sc_dump_hex(card->ef_atr->aid.value, card->ef_atr->aid.len) : \"\");", "\t\trv = iasecc_select_mf(card, file_out);\n\t\tLOG_TEST_RET(ctx, rv, \"MF selection error\");\n", "\t\tmemmove(&lpath.value[0], &lpath.value[2], lpath.len - 2);\n\t\tlpath.len -= 2;", "\t}", "\tif (lpath.aid.len)\t{\n\t\tstruct sc_file *file = NULL;\n\t\tstruct sc_path ppath;", "\t\tsc_log(ctx,\n\t\t \"iasecc_select_file() select parent AID:%p/%\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t\t lpath.aid.value, lpath.aid.len);\n\t\tsc_log(ctx, \"iasecc_select_file() select parent AID:%s\", sc_dump_hex(lpath.aid.value, lpath.aid.len));\n\t\tmemset(&ppath, 0, sizeof(ppath));\n\t\tmemcpy(ppath.value, lpath.aid.value, lpath.aid.len);\n\t\tppath.len = lpath.aid.len;\n\t\tppath.type = SC_PATH_TYPE_DF_NAME;", "\t\tif (card->cache.valid && card->cache.current_df\n\t\t\t\t&& card->cache.current_df->path.len == lpath.aid.len\n\t\t\t\t&& !memcmp(card->cache.current_df->path.value, lpath.aid.value, lpath.aid.len))\n\t\t\tdf_from_cache = 1;", "\t\trv = iasecc_select_file(card, &ppath, &file);\n\t\tLOG_TEST_RET(ctx, rv, \"select AID path failed\");", "\t\tif (file_out)\n\t\t\t*file_out = file;\n\t\telse\n\t\t sc_file_free(file);", "\t\tif (lpath.type == SC_PATH_TYPE_DF_NAME)\n\t\t\tlpath.type = SC_PATH_TYPE_FROM_CURRENT;\n\t}", "\tif (lpath.type == SC_PATH_TYPE_PATH)\n\t\tlpath.type = SC_PATH_TYPE_FROM_CURRENT;", "\tif (!lpath.len)\n\t\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);", "\tsc_print_cache(card);", "\tif (card->cache.valid && card->cache.current_df && lpath.type == SC_PATH_TYPE_DF_NAME\n\t\t\t&& card->cache.current_df->path.len == lpath.len\n\t\t\t&& !memcmp(card->cache.current_df->path.value, lpath.value, lpath.len)) {\n\t\tsc_log(ctx, \"returns current DF path %s\", sc_print_path(&card->cache.current_df->path));\n\t\tif (file_out) {\n\t\t\tsc_file_free(*file_out);\n\t\t\tsc_file_dup(file_out, card->cache.current_df);\n\t\t}", "\t\tsc_print_cache(card);\n\t\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n\t}", "\tdo {\n\t\tstruct sc_apdu apdu;\n\t\tstruct sc_file *file = NULL;\n\t\tunsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE];\n\t\tint pathlen = lpath.len;", "\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00);", "\t\tif (card->type != SC_CARD_TYPE_IASECC_GEMALTO\n\t\t\t\t&& card->type != SC_CARD_TYPE_IASECC_OBERTHUR\n\t\t\t\t&& card->type != SC_CARD_TYPE_IASECC_SAGEM\n\t\t\t\t&& card->type != SC_CARD_TYPE_IASECC_AMOS\n\t\t\t\t&& card->type != SC_CARD_TYPE_IASECC_MI\n\t\t\t\t&& card->type != SC_CARD_TYPE_IASECC_MI2)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Unsupported card\");", "\t\tif (lpath.type == SC_PATH_TYPE_FILE_ID) {\n\t\t\tapdu.p1 = 0x02;\n\t\t\tif (card->type == SC_CARD_TYPE_IASECC_OBERTHUR) {\n\t\t\t\tapdu.p1 = 0x01;\n\t\t\t\tapdu.p2 = 0x04;\n\t\t\t}\n\t\t\tif (card->type == SC_CARD_TYPE_IASECC_AMOS)\n\t\t\t\tapdu.p2 = 0x04;\n\t\t\tif (card->type == SC_CARD_TYPE_IASECC_MI)\n\t\t\t\tapdu.p2 = 0x04;\n\t\t\tif (card->type == SC_CARD_TYPE_IASECC_MI2)\n\t\t\t\tapdu.p2 = 0x04;\n\t\t}\n\t\telse if (lpath.type == SC_PATH_TYPE_FROM_CURRENT) {\n\t\t\tapdu.p1 = 0x09;\n\t\t\tif (card->type == SC_CARD_TYPE_IASECC_OBERTHUR)\n\t\t\t\tapdu.p2 = 0x04;\n\t\t\tif (card->type == SC_CARD_TYPE_IASECC_AMOS)\n\t\t\t\tapdu.p2 = 0x04;\n\t\t\tif (card->type == SC_CARD_TYPE_IASECC_MI)\n\t\t\t\tapdu.p2 = 0x04;\n\t\t\tif (card->type == SC_CARD_TYPE_IASECC_MI2)\n\t\t\t\tapdu.p2 = 0x04;\n\t\t}\n\t\telse if (lpath.type == SC_PATH_TYPE_PARENT) {\n\t\t\tapdu.p1 = 0x03;\n\t\t\tpathlen = 0;\n\t\t\tapdu.cse = SC_APDU_CASE_2_SHORT;\n\t\t}\n\t\telse if (lpath.type == SC_PATH_TYPE_DF_NAME) {\n\t\t\tapdu.p1 = 0x04;\n\t\t\tif (card->type == SC_CARD_TYPE_IASECC_AMOS)\n\t\t\t\tapdu.p2 = 0x04;\n\t\t\tif (card->type == SC_CARD_TYPE_IASECC_MI2)\n\t\t\t\tapdu.p2 = 0x04;\n\t\t}\n\t\telse {\n\t\t\tsc_log(ctx, \"Invalid PATH type: 0x%X\", lpath.type);\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"iasecc_select_file() invalid PATH type\");\n\t\t}", "\t\tfor (ii=0; ii<2; ii++) {\n\t\t\tapdu.lc = pathlen;\n\t\t\tapdu.data = lpath.value;\n\t\t\tapdu.datalen = pathlen;", "\t\t\tapdu.resp = rbuf;\n\t\t\tapdu.resplen = sizeof(rbuf);\n\t\t\tapdu.le = 256;", "\t\t\trv = sc_transmit_apdu(card, &apdu);\n\t\t\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\t\t\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\t\t\tif (rv == SC_ERROR_INCORRECT_PARAMETERS &&\n\t\t\t\t\tlpath.type == SC_PATH_TYPE_DF_NAME && apdu.p2 == 0x00) {\n\t\t\t\tapdu.p2 = 0x0C;\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tif (ii) {\n\t\t\t\t/* 'SELECT AID' do not returned FCP. Try to emulate. */\n\t\t\t\tapdu.resplen = sizeof(rbuf);\n\t\t\t\trv = iasecc_emulate_fcp(ctx, &apdu);\n\t\t\t\tLOG_TEST_RET(ctx, rv, \"Failed to emulate DF FCP\");\n\t\t\t}", "\t\t\tbreak;\n\t\t}", "\t\t/*\n\t\t * Using of the cached DF and EF can cause problems in the multi-thread environment.\n\t\t * FIXME: introduce config. option that invalidates this cache outside the locked card session,\n\t\t * (or invent something else)\n\t\t */\n\t\tif (rv == SC_ERROR_FILE_NOT_FOUND && cache_valid && df_from_cache) {\n\t\t\tsc_invalidate_cache(card);\n\t\t\tsc_log(ctx, \"iasecc_select_file() file not found, retry without cached DF\");\n\t\t\tif (file_out) {\n\t\t\t\tsc_file_free(*file_out);\n\t\t\t\t*file_out = NULL;\n\t\t\t}\n\t\t\trv = iasecc_select_file(card, path, file_out);\n\t\t\tLOG_FUNC_RETURN(ctx, rv);\n\t\t}", "\t\tLOG_TEST_RET(ctx, rv, \"iasecc_select_file() check SW failed\");", "\t\tsc_log(ctx,\n\t\t \"iasecc_select_file() apdu.resp %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t\t apdu.resplen);\n\t\tif (apdu.resplen) {\n\t\t\tsc_log(ctx, \"apdu.resp %02X:%02X:%02X...\", apdu.resp[0], apdu.resp[1], apdu.resp[2]);", "\t\t\tswitch (apdu.resp[0]) {\n\t\t\tcase 0x62:\n\t\t\tcase 0x6F:\n\t\t\t\tfile = sc_file_new();\n\t\t\t\tif (file == NULL)\n\t\t\t\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);\n\t\t\t\tfile->path = lpath;", "\t\t\t\trv = iasecc_process_fci(card, file, apdu.resp, apdu.resplen);\n\t\t\t\tif (rv)\n\t\t\t\t\tLOG_FUNC_RETURN(ctx, rv);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);\n\t\t\t}", "\t\t\tsc_log(ctx, \"FileType %i\", file->type);\n\t\t\tif (file->type == SC_FILE_TYPE_DF) {\n\t\t\t\tif (card->cache.valid)\n\t\t\t\t\tsc_file_free(card->cache.current_df);\n\t\t\t\tcard->cache.current_df = NULL;", "\n\t\t\t\tif (card->cache.valid)\n\t\t\t\t\tsc_file_free(card->cache.current_ef);\n\t\t\t\tcard->cache.current_ef = NULL;", "\t\t\t\tsc_file_dup(&card->cache.current_df, file);\n\t\t\t\tcard->cache.valid = 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (card->cache.valid)\n\t\t\t\t\tsc_file_free(card->cache.current_ef);", "\t\t\t\tcard->cache.current_ef = NULL;", "\t\t\t\tsc_file_dup(&card->cache.current_ef, file);\n\t\t\t}", "\t\t\tif (file_out) {\n\t\t\t\tsc_file_free(*file_out);\n\t\t\t\t*file_out = file;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsc_file_free(file);\n\t\t\t}\n\t\t}\n\t\telse if (lpath.type == SC_PATH_TYPE_DF_NAME) {\n\t\t\tsc_file_free(card->cache.current_df);\n\t\t\tcard->cache.current_df = NULL;", "\t\t\tsc_file_free(card->cache.current_ef);\n\t\t\tcard->cache.current_ef = NULL;", "\t\t\tcard->cache.valid = 1;\n\t\t}\n\t} while(0);", "\tsc_print_cache(card);\n\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_process_fci(struct sc_card *card, struct sc_file *file,\n\t\t const unsigned char *buf, size_t buflen)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tsize_t taglen;\n\tint rv, ii, offs;\n\tconst unsigned char *acls = NULL, *tag = NULL;\n\tunsigned char mask;\n\tunsigned char ops_DF[7] = {\n\t\tSC_AC_OP_DELETE, 0xFF, SC_AC_OP_ACTIVATE, SC_AC_OP_DEACTIVATE, 0xFF, SC_AC_OP_CREATE, 0xFF\n\t};\n\tunsigned char ops_EF[7] = {\n\t\tSC_AC_OP_DELETE, 0xFF, SC_AC_OP_ACTIVATE, SC_AC_OP_DEACTIVATE, 0xFF, SC_AC_OP_UPDATE, SC_AC_OP_READ\n\t};", "\tLOG_FUNC_CALLED(ctx);", "\ttag = sc_asn1_find_tag(ctx, buf, buflen, 0x6F, &taglen);\n\tsc_log(ctx, \"processing FCI: 0x6F tag %p\", tag);\n\tif (tag != NULL) {\n\t\tsc_log(ctx, \" FCP length %\"SC_FORMAT_LEN_SIZE_T\"u\", taglen);\n\t\tbuf = tag;\n\t\tbuflen = taglen;\n\t}", "\ttag = sc_asn1_find_tag(ctx, buf, buflen, 0x62, &taglen);\n\tsc_log(ctx, \"processing FCI: 0x62 tag %p\", tag);\n\tif (tag != NULL) {\n\t\tsc_log(ctx, \" FCP length %\"SC_FORMAT_LEN_SIZE_T\"u\", taglen);\n\t\tbuf = tag;\n\t\tbuflen = taglen;\n\t}", "\trv = iso_ops->process_fci(card, file, buf, buflen);\n\tLOG_TEST_RET(ctx, rv, \"ISO parse FCI failed\");\n/*\n\tGemalto: 6F 19 80 02 02 ED 82 01 01 83 02 B0 01 88 00\t8C 07 7B 17 17 17 17 17 00 8A 01 05 90 00\n\tSagem: 6F 17 62 15 80 02 00 7D 82 01 01 8C 02 01 00 83 02 2F 00 88 01 F0 8A 01 05 90 00\n\tOberthur: 62 1B 80 02 05 DC 82 01 01 83 02 B0 01 88 00 A1 09 8C 07 7B 17 FF 17 17 17 00 8A 01 05 90 00\n*/", "\tsc_log(ctx, \"iasecc_process_fci() type %i; let's parse file ACLs\", file->type);\n\ttag = sc_asn1_find_tag(ctx, buf, buflen, IASECC_DOCP_TAG_ACLS, &taglen);\n\tif (tag)\n\t\tacls = sc_asn1_find_tag(ctx, tag, taglen, IASECC_DOCP_TAG_ACLS_CONTACT, &taglen);\n\telse\n\t\tacls = sc_asn1_find_tag(ctx, buf, buflen, IASECC_DOCP_TAG_ACLS_CONTACT, &taglen);", "\tif (!acls) {\n\t\tsc_log(ctx,\n\t\t \"ACLs not found in data(%\"SC_FORMAT_LEN_SIZE_T\"u) %s\",\n\t\t buflen, sc_dump_hex(buf, buflen));\n\t\tLOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, \"ACLs tag missing\");\n\t}", "\tsc_log(ctx, \"ACLs(%\"SC_FORMAT_LEN_SIZE_T\"u) '%s'\", taglen,\n\t sc_dump_hex(acls, taglen));\n\tmask = 0x40, offs = 1;\n\tfor (ii = 0; ii < 7; ii++, mask /= 2) {\n\t\tunsigned char op = file->type == SC_FILE_TYPE_DF ? ops_DF[ii] : ops_EF[ii];", "\t\tif (!(mask & acls[0]))\n\t\t\tcontinue;", "\t\tsc_log(ctx, \"ACLs mask 0x%X, offs %i, op 0x%X, acls[offs] 0x%X\", mask, offs, op, acls[offs]);\n\t\tif (op == 0xFF) {\n\t\t\t;\n\t\t}\n\t\telse if (acls[offs] == 0) {\n\t\t\tsc_file_add_acl_entry(file, op, SC_AC_NONE, 0);\n\t\t}\n\t\telse if (acls[offs] == 0xFF) {\n\t\t\tsc_file_add_acl_entry(file, op, SC_AC_NEVER, 0);\n\t\t}\n\t\telse if ((acls[offs] & IASECC_SCB_METHOD_MASK) == IASECC_SCB_METHOD_USER_AUTH) {\n\t\t\tsc_file_add_acl_entry(file, op, SC_AC_SEN, acls[offs] & IASECC_SCB_METHOD_MASK_REF);\n\t\t}\n\t\telse if (acls[offs] & IASECC_SCB_METHOD_MASK) {\n\t\t\tsc_file_add_acl_entry(file, op, SC_AC_SCB, acls[offs]);\n\t\t}\n\t\telse {\n\t\t\tsc_log(ctx, \"Warning: non supported SCB method: %X\", acls[offs]);\n\t\t\tsc_file_add_acl_entry(file, op, SC_AC_NEVER, 0);\n\t\t}", "\t\toffs++;\n\t}", "\tLOG_FUNC_RETURN(ctx, 0);\n}", "\nstatic int\niasecc_fcp_encode(struct sc_card *card, struct sc_file *file, unsigned char *out, size_t out_len)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tunsigned char buf[0x80], type;\n\tunsigned char ops[7] = {\n\t\tSC_AC_OP_DELETE, 0xFF, SC_AC_OP_ACTIVATE, SC_AC_OP_DEACTIVATE, 0xFF, SC_AC_OP_UPDATE, SC_AC_OP_READ\n\t};\n\tunsigned char smbs[8];\n\tsize_t ii, offs = 0, amb, mask, nn_smb;", "\tLOG_FUNC_CALLED(ctx);", "\tif (file->type == SC_FILE_TYPE_DF)\n\t\ttype = IASECC_FCP_TYPE_DF;\n\telse\n\t\ttype = IASECC_FCP_TYPE_EF;", "\tbuf[offs++] = IASECC_FCP_TAG_SIZE;\n\tbuf[offs++] = 2;\n\tbuf[offs++] = (file->size >> 8) & 0xFF;\n\tbuf[offs++] = file->size & 0xFF;", "\tbuf[offs++] = IASECC_FCP_TAG_TYPE;\n\tbuf[offs++] = 1;\n\tbuf[offs++] = type;", "\tbuf[offs++] = IASECC_FCP_TAG_FID;\n\tbuf[offs++] = 2;\n\tbuf[offs++] = (file->id >> 8) & 0xFF;\n\tbuf[offs++] = file->id & 0xFF;", "\tbuf[offs++] = IASECC_FCP_TAG_SFID;\n\tbuf[offs++] = 0;", "\tamb = 0, mask = 0x40, nn_smb = 0;\n\tfor (ii = 0; ii < sizeof(ops); ii++, mask >>= 1) {\n\t\tconst struct sc_acl_entry *entry;", "\t\tif (ops[ii]==0xFF)\n\t\t\tcontinue;", "\t\tentry = sc_file_get_acl_entry(file, ops[ii]);\n\t\tif (!entry)\n\t\t\tcontinue;", "\t\tsc_log(ctx, \"method %X; reference %X\", entry->method, entry->key_ref);\n\t\tif (entry->method == SC_AC_NEVER)\n\t\t\tcontinue;\n\t\telse if (entry->method == SC_AC_NONE)\n\t\t\tsmbs[nn_smb++] = 0x00;\n\t\telse if (entry->method == SC_AC_CHV)\n\t\t\tsmbs[nn_smb++] = entry->key_ref | IASECC_SCB_METHOD_USER_AUTH;\n\t\telse if (entry->method == SC_AC_SEN)\n\t\t\tsmbs[nn_smb++] = entry->key_ref | IASECC_SCB_METHOD_USER_AUTH;\n\t\telse if (entry->method == SC_AC_SCB)\n\t\t\tsmbs[nn_smb++] = entry->key_ref;\n\t\telse if (entry->method == SC_AC_PRO)\n\t\t\tsmbs[nn_smb++] = entry->key_ref | IASECC_SCB_METHOD_SM;\n\t\telse\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Non supported AC method\");", "\t\tamb |= mask;\n\t\tsc_log(ctx,\n\t\t \"%\"SC_FORMAT_LEN_SIZE_T\"u: AMB %\"SC_FORMAT_LEN_SIZE_T\"X; nn_smb %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t\t ii, amb, nn_smb);\n\t}", "\t/* TODO: Encode contactless ACLs and life cycle status for all IAS/ECC cards */\n\tif (card->type == SC_CARD_TYPE_IASECC_SAGEM ||\n\t\t\tcard->type == SC_CARD_TYPE_IASECC_AMOS ) {\n\t\tunsigned char status = 0;", "\t\tbuf[offs++] = IASECC_FCP_TAG_ACLS;\n\t\tbuf[offs++] = 2*(2 + 1 + nn_smb);", "\t\tbuf[offs++] = IASECC_FCP_TAG_ACLS_CONTACT;\n\t\tbuf[offs++] = nn_smb + 1;\n\t\tbuf[offs++] = amb;\n\t\tmemcpy(buf + offs, smbs, nn_smb);\n\t\toffs += nn_smb;", "\t\t/* Same ACLs for contactless */\n\t\tbuf[offs++] = IASECC_FCP_TAG_ACLS_CONTACTLESS;\n\t\tbuf[offs++] = nn_smb + 1;\n\t\tbuf[offs++] = amb;\n\t\tmemcpy(buf + offs, smbs, nn_smb);\n\t\toffs += nn_smb;", "\t\tif (file->status == SC_FILE_STATUS_ACTIVATED)\n\t\t\tstatus = 0x05;\n\t\telse if (file->status == SC_FILE_STATUS_CREATION)\n\t\t\tstatus = 0x01;", "\t\tif (status) {\n\t\t\tbuf[offs++] = 0x8A;\n\t\t\tbuf[offs++] = 0x01;\n\t\t\tbuf[offs++] = status;\n\t\t}\n\t}\n\telse {\n\t\tbuf[offs++] = IASECC_FCP_TAG_ACLS;\n\t\tbuf[offs++] = 2 + 1 + nn_smb;", "\t\tbuf[offs++] = IASECC_FCP_TAG_ACLS_CONTACT;\n\t\tbuf[offs++] = nn_smb + 1;\n\t\tbuf[offs++] = amb;\n\t\tmemcpy(buf + offs, smbs, nn_smb);\n\t\toffs += nn_smb;\n\t}", "\tif (out) {\n\t\tif (out_len < offs)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, \"Buffer too small to encode FCP\");\n\t\tmemcpy(out, buf, offs);\n\t}", "\tLOG_FUNC_RETURN(ctx, offs);\n}", "\nstatic int\niasecc_create_file(struct sc_card *card, struct sc_file *file)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_apdu apdu;\n\tconst struct sc_acl_entry *entry = NULL;\n\tunsigned char sbuf[0x100];\n\tsize_t sbuf_len;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_print_cache(card);", "\tif (file->type != SC_FILE_TYPE_WORKING_EF)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Creation of the file with of this type is not supported\");", "\tsbuf_len = iasecc_fcp_encode(card, file, sbuf + 2, sizeof(sbuf)-2);\n\tLOG_TEST_RET(ctx, sbuf_len, \"FCP encode error\");", "\tsbuf[0] = IASECC_FCP_TAG;\n\tsbuf[1] = sbuf_len;", "\tif (card->cache.valid && card->cache.current_df) {\n\t\tentry = sc_file_get_acl_entry(card->cache.current_df, SC_AC_OP_CREATE);\n\t\tif (!entry)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, \"iasecc_create_file() 'CREATE' ACL not present\");", "\t\tsc_log(ctx, \"iasecc_create_file() 'CREATE' method/reference %X/%X\", entry->method, entry->key_ref);\n\t\tsc_log(ctx, \"iasecc_create_file() create data: '%s'\", sc_dump_hex(sbuf, sbuf_len + 2));\n\t\tif (entry->method == SC_AC_SCB && (entry->key_ref & IASECC_SCB_METHOD_SM)) {\n rv = iasecc_sm_create_file(card, entry->key_ref & IASECC_SCB_METHOD_MASK_REF, sbuf, sbuf_len + 2);\n LOG_TEST_RET(ctx, rv, \"iasecc_create_file() SM create file error\");", " rv = iasecc_select_file(card, &file->path, NULL);\n LOG_FUNC_RETURN(ctx, rv);", "\t\t}\n\t}", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0, 0);\n\tapdu.data = sbuf;\n\tapdu.datalen = sbuf_len + 2;\n\tapdu.lc = sbuf_len + 2;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"iasecc_create_file() create file error\");", "\trv = iasecc_select_file(card, &file->path, NULL);\n\tLOG_TEST_RET(ctx, rv, \"Cannot select newly created file\");", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_logout(struct sc_card *card)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_path path;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tif (!card->ef_atr || !card->ef_atr->aid.len)\n\t\treturn SC_SUCCESS;", "\tmemset(&path, 0, sizeof(struct sc_path));\n\tpath.type = SC_PATH_TYPE_DF_NAME;\n\tmemcpy(path.value, card->ef_atr->aid.value, card->ef_atr->aid.len);\n\tpath.len = card->ef_atr->aid.len;", "\trv = iasecc_select_file(card, &path, NULL);\n\tsc_log(ctx, \"Select ECC ROOT with the AID from EF.ATR: rv %i\", rv);", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_finish(struct sc_card *card)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_private_data *private_data = (struct iasecc_private_data *)card->drv_data;\n\tstruct iasecc_se_info *se_info = private_data->se_info, *next;", "\tLOG_FUNC_CALLED(ctx);", "\twhile (se_info) {\n\t\tsc_file_free(se_info->df);\n\t\tnext = se_info->next;\n\t\tfree(se_info);\n\t\tse_info = next;\n\t}", "\tfree(card->drv_data);\n\tcard->drv_data = NULL;", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_delete_file(struct sc_card *card, const struct sc_path *path)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tconst struct sc_acl_entry *entry = NULL;\n\tstruct sc_apdu apdu;\n\tstruct sc_file *file = NULL;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_print_cache(card);", "\trv = iasecc_select_file(card, path, &file);\n\tif (rv == SC_ERROR_FILE_NOT_FOUND)\n\t\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n\tLOG_TEST_RET(ctx, rv, \"Cannot select file to delete\");", "\tentry = sc_file_get_acl_entry(file, SC_AC_OP_DELETE);\n\tif (!entry)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, \"Cannot delete file: no 'DELETE' acl\");", "\tsc_log(ctx, \"DELETE method/reference %X/%X\", entry->method, entry->key_ref);\n\tif (entry->method == SC_AC_SCB && (entry->key_ref & IASECC_SCB_METHOD_SM)) {\n\t\tunsigned char se_num = (entry->method == SC_AC_SCB) ? (entry->key_ref & IASECC_SCB_METHOD_MASK_REF) : 0;\n\t\trv = iasecc_sm_delete_file(card, se_num, file->id);\n\t}\n\telse {\n\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xE4, 0x00, 0x00);", "\t\trv = sc_transmit_apdu(card, &apdu);\n\t\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\t\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\t\tLOG_TEST_RET(ctx, rv, \"Delete file failed\");", "\t\tif (card->cache.valid)\n\t\t\tsc_file_free(card->cache.current_ef);\n\t\tcard->cache.current_ef = NULL;\n\t}", "\tsc_file_free(file);\n\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2)\n{\n\tif (sw1 == 0x62 && sw2 == 0x82)\n\t\treturn SC_SUCCESS;", "\treturn iso_ops->check_sw(card, sw1, sw2);\n}", "\nstatic unsigned\niasecc_get_algorithm(struct sc_context *ctx, const struct sc_security_env *env,\n\t\tunsigned operation, unsigned mechanism)\n{\n const struct sc_supported_algo_info *info = NULL;\n int ii;", " if (!env)\n return 0;", " for (ii=0;ii<SC_MAX_SUPPORTED_ALGORITHMS && env->supported_algos[ii].reference; ii++)\n if ((env->supported_algos[ii].operations & operation)\n\t\t\t&& (env->supported_algos[ii].mechanism == mechanism))\n break;", " if (ii < SC_MAX_SUPPORTED_ALGORITHMS && env->supported_algos[ii].reference) {\n info = &env->supported_algos[ii];\n sc_log(ctx, \"found IAS/ECC algorithm %X:%X:%X:%X\",\n\t\t\tinfo->reference, info->mechanism, info->operations, info->algo_ref);\n }\n else {\n sc_log(ctx, \"cannot find IAS/ECC algorithm (operation:%X,mechanism:%X)\", operation, mechanism);\n }", " return info ? info->algo_ref : 0;\n}", "\nstatic int\niasecc_se_cache_info(struct sc_card *card, struct iasecc_se_info *se)\n{\n\tstruct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data;\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_se_info *se_info = NULL, *si = NULL;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);", "\tse_info = calloc(1, sizeof(struct iasecc_se_info));\n\tif (!se_info)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, \"SE info allocation error\");\n\tmemcpy(se_info, se, sizeof(struct iasecc_se_info));", "\tif (card->cache.valid && card->cache.current_df) {\n\t\tsc_file_dup(&se_info->df, card->cache.current_df);\n\t\tif (se_info->df == NULL) {\n\t\t\tfree(se_info);\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, \"Cannot duplicate current DF file\");\n\t\t}\n\t}", "\trv = iasecc_docp_copy(ctx, &se->docp, &se_info->docp);\n\tif (rv < 0) {\n\t\tfree(se_info->df);\n\t\tfree(se_info);\n\t\tLOG_TEST_RET(ctx, rv, \"Cannot make copy of DOCP\");\n\t}", "\tif (!prv->se_info) {\n\t\tprv->se_info = se_info;\n\t}\n\telse {\n\t\tfor (si = prv->se_info; si->next; si = si->next)\n\t\t\t;\n\t\tsi->next = se_info;\n\t}", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_se_get_info_from_cache(struct sc_card *card, struct iasecc_se_info *se)\n{\n\tstruct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data;\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_se_info *si = NULL;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);", "\tfor(si = prv->se_info; si; si = si->next) {\n\t\tif (si->reference != se->reference)\n\t\t\tcontinue;\n\t\tif (!(card->cache.valid && card->cache.current_df) && si->df)\n\t\t\tcontinue;\n\t\tif (card->cache.valid && card->cache.current_df && !si->df)\n\t\t\tcontinue;\n\t\tif (card->cache.valid && card->cache.current_df && si->df)\n\t\t\tif (memcmp(&card->cache.current_df->path, &si->df->path, sizeof(struct sc_path)))\n\t\t\t\tcontinue;\n\t\tbreak;\n\t}", "\tif (!si)\n\t\treturn SC_ERROR_OBJECT_NOT_FOUND;", "\tmemcpy(se, si, sizeof(struct iasecc_se_info));", "\tif (si->df) {\n\t\tsc_file_dup(&se->df, si->df);\n\t\tif (se->df == NULL)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, \"Cannot duplicate current DF file\");\n\t}", "\trv = iasecc_docp_copy(ctx, &si->docp, &se->docp);\n\tLOG_TEST_RET(ctx, rv, \"Cannot make copy of DOCP\");", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nint\niasecc_se_get_info(struct sc_card *card, struct iasecc_se_info *se)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_apdu apdu;\n\tunsigned char rbuf[0x100];\n\tunsigned char sbuf_iasecc[10] = {\n\t\t0x4D, 0x08, IASECC_SDO_TEMPLATE_TAG, 0x06,\n\t\tIASECC_SDO_TAG_HEADER, IASECC_SDO_CLASS_SE | IASECC_OBJECT_REF_LOCAL,\n\t\tse->reference & 0x3F,\n\t\t0x02, IASECC_SDO_CLASS_SE, 0x80\n\t};\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);", "\tif (se->reference > IASECC_SE_REF_MAX)\n LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);", "\trv = iasecc_se_get_info_from_cache(card, se);\n\tif (rv == SC_ERROR_OBJECT_NOT_FOUND) {\n\t\tsc_log(ctx, \"No SE#%X info in cache, try to use 'GET DATA'\", se->reference);", "\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xCB, 0x3F, 0xFF);\n\t\tapdu.data = sbuf_iasecc;\n\t\tapdu.datalen = sizeof(sbuf_iasecc);\n\t\tapdu.lc = apdu.datalen;\n\t\tapdu.resp = rbuf;\n\t\tapdu.resplen = sizeof(rbuf);\n\t\tapdu.le = sizeof(rbuf);", "\t\trv = sc_transmit_apdu(card, &apdu);\n\t\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\t\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\t\tLOG_TEST_RET(ctx, rv, \"get SE data error\");", "\t\trv = iasecc_se_parse(card, apdu.resp, apdu.resplen, se);\n\t\tLOG_TEST_RET(ctx, rv, \"cannot parse SE data\");", "\t\trv = iasecc_se_cache_info(card, se);\n\t\tLOG_TEST_RET(ctx, rv, \"failed to put SE data into cache\");\n\t}", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_set_security_env(struct sc_card *card,\n\t\tconst struct sc_security_env *env, int se_num)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_sdo sdo;\n\tstruct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data;\n\tunsigned algo_ref;\n\tstruct sc_apdu apdu;\n\tunsigned sign_meth, sign_ref, auth_meth, auth_ref, aflags;\n\tunsigned char cse_crt_at[] = {\n\t\t0x84, 0x01, 0xFF,\n\t\t0x80, 0x01, IASECC_ALGORITHM_RSA_PKCS\n\t};\n\tunsigned char cse_crt_dst[] = {\n\t\t0x84, 0x01, 0xFF,\n\t\t0x80, 0x01, (IASECC_ALGORITHM_RSA_PKCS | IASECC_ALGORITHM_SHA1)\n\t};\n\tunsigned char cse_crt_ht[] = {\n\t\t0x80, 0x01, IASECC_ALGORITHM_SHA1\n\t};\n\tunsigned char cse_crt_ct[] = {\n\t\t0x84, 0x01, 0xFF,\n\t\t0x80, 0x01, (IASECC_ALGORITHM_RSA_PKCS_DECRYPT | IASECC_ALGORITHM_SHA1)\n\t};\n\tint rv, operation = env->operation;", "\t/* TODO: take algorithm references from 5032, not from header file. */\n\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx, \"iasecc_set_security_env(card:%p) operation 0x%X; senv.algorithm 0x%X, senv.algorithm_ref 0x%X\",\n\t\t\tcard, env->operation, env->algorithm, env->algorithm_ref);", "\tmemset(&sdo, 0, sizeof(sdo));\n\tsdo.sdo_class = IASECC_SDO_CLASS_RSA_PRIVATE;\n\tsdo.sdo_ref = env->key_ref[0] & ~IASECC_OBJECT_REF_LOCAL;\n\trv = iasecc_sdo_get_data(card, &sdo);\n\tLOG_TEST_RET(ctx, rv, \"Cannot get RSA PRIVATE SDO data\");", "\t/* To made by iasecc_sdo_convert_to_file() */\n\tprv->key_size = *(sdo.docp.size.value + 0) * 0x100 + *(sdo.docp.size.value + 1);\n\tsc_log(ctx, \"prv->key_size 0x%\"SC_FORMAT_LEN_SIZE_T\"X\", prv->key_size);", "\trv = iasecc_sdo_convert_acl(card, &sdo, SC_AC_OP_PSO_COMPUTE_SIGNATURE, &sign_meth, &sign_ref);\n\tLOG_TEST_RET(ctx, rv, \"Cannot convert SC_AC_OP_SIGN acl\");", "\trv = iasecc_sdo_convert_acl(card, &sdo, SC_AC_OP_INTERNAL_AUTHENTICATE, &auth_meth, &auth_ref);\n\tLOG_TEST_RET(ctx, rv, \"Cannot convert SC_AC_OP_INT_AUTH acl\");", "\taflags = env->algorithm_flags;", "\tif (!(aflags & SC_ALGORITHM_RSA_PAD_PKCS1))\n\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Only supported signature with PKCS1 padding\");", "\tif (operation == SC_SEC_OPERATION_SIGN) {\n\t\tif (!(aflags & (SC_ALGORITHM_RSA_HASH_SHA1 | SC_ALGORITHM_RSA_HASH_SHA256))) {\n\t\t\tsc_log(ctx, \"CKM_RSA_PKCS asked -- use 'AUTHENTICATE' sign operation instead of 'SIGN'\");\n\t\t\toperation = SC_SEC_OPERATION_AUTHENTICATE;\n\t\t}\n\t\telse if (sign_meth == SC_AC_NEVER) {\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"PSO_DST not allowed for this key\");\n\t\t}\n\t}", "\tif (operation == SC_SEC_OPERATION_SIGN) {\n\t\tprv->op_method = sign_meth;\n\t\tprv->op_ref = sign_ref;\n\t}\n\telse if (operation == SC_SEC_OPERATION_AUTHENTICATE) {\n\t\tif (auth_meth == SC_AC_NEVER)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_ALLOWED, \"INTERNAL_AUTHENTICATE is not allowed for this key\");", "\t\tprv->op_method = auth_meth;\n\t\tprv->op_ref = auth_ref;\n\t}", "\tsc_log(ctx, \"senv.algorithm 0x%X, senv.algorithm_ref 0x%X\", env->algorithm, env->algorithm_ref);\n\tsc_log(ctx,\n\t \"se_num %i, operation 0x%X, algorithm 0x%X, algorithm_ref 0x%X, flags 0x%X; key size %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t se_num, operation, env->algorithm, env->algorithm_ref,\n\t env->algorithm_flags, prv->key_size);\n\tswitch (operation) {\n\tcase SC_SEC_OPERATION_SIGN:\n\t\tif (!(env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1))\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"Need RSA_PKCS1 specified\");", "\t\tif (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA256) {\n\t\t\talgo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_HASH, CKM_SHA256);\n\t\t\tif (!algo_ref)\n\t\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Card application do not supports HASH:SHA256\");", "\t\t\tcse_crt_ht[2] = algo_ref; /* IASECC_ALGORITHM_SHA2 */", "\t\t\talgo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_COMPUTE_SIGNATURE, CKM_SHA256_RSA_PKCS);\n\t\t\tif (!algo_ref)\n\t\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Card application do not supports SIGNATURE:SHA1_RSA_PKCS\");", "\t\t\tcse_crt_dst[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL;\n\t\t\tcse_crt_dst[5] = algo_ref; /* IASECC_ALGORITHM_RSA_PKCS | IASECC_ALGORITHM_SHA2 */\n\t\t}\n\t\telse if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA1) {\n\t\t\talgo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_HASH, CKM_SHA_1);\n\t\t\tif (!algo_ref)\n\t\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Card application do not supports HASH:SHA1\");", "\t\t\tcse_crt_ht[2] = algo_ref;\t/* IASECC_ALGORITHM_SHA1 */", "\t\t\talgo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_COMPUTE_SIGNATURE, CKM_SHA1_RSA_PKCS);\n\t\t\tif (!algo_ref)\n\t\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Card application do not supports SIGNATURE:SHA1_RSA_PKCS\");", "\t\t\tcse_crt_dst[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL;\n\t\t\tcse_crt_dst[5] = algo_ref; /* IASECC_ALGORITHM_RSA_PKCS | IASECC_ALGORITHM_SHA1 */\n\t\t}\n\t\telse {\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"Need RSA_HASH_SHA[1,256] specified\");\n\t\t}", "\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_HT);\n\t\tapdu.data = cse_crt_ht;\n\t\tapdu.datalen = sizeof(cse_crt_ht);\n\t\tapdu.lc = sizeof(cse_crt_ht);", "\t\trv = sc_transmit_apdu(card, &apdu);\n\t\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\t\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\t\tLOG_TEST_RET(ctx, rv, \"MSE restore error\");", "\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_DST);\n\t\tapdu.data = cse_crt_dst;\n\t\tapdu.datalen = sizeof(cse_crt_dst);\n\t\tapdu.lc = sizeof(cse_crt_dst);\n\t\tbreak;\n\tcase SC_SEC_OPERATION_AUTHENTICATE:\n\t\talgo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_COMPUTE_SIGNATURE, CKM_RSA_PKCS);\n\t\tif (!algo_ref)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Application do not supports SIGNATURE:RSA_PKCS\");", "\t\tcse_crt_at[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL;\n\t\tcse_crt_at[5] = algo_ref;\t/* IASECC_ALGORITHM_RSA_PKCS */", "\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_AT);\n\t\tapdu.data = cse_crt_at;\n\t\tapdu.datalen = sizeof(cse_crt_at);\n\t\tapdu.lc = sizeof(cse_crt_at);\n\t\tbreak;\n\tcase SC_SEC_OPERATION_DECIPHER:\n\t\trv = iasecc_sdo_convert_acl(card, &sdo, SC_AC_OP_PSO_DECRYPT, &prv->op_method, &prv->op_ref);\n\t\tLOG_TEST_RET(ctx, rv, \"Cannot convert SC_AC_OP_PSO_DECRYPT acl\");\n\t\talgo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_DECIPHER, CKM_RSA_PKCS);\n\t\tif (!algo_ref)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Application do not supports DECIPHER:RSA_PKCS\");", "\t\tcse_crt_ct[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL;\n\t\tcse_crt_ct[5] = algo_ref;\t/* IASECC_ALGORITHM_RSA_PKCS_DECRYPT | IASECC_ALGORITHM_SHA1 */", "\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_CT);\n\t\tapdu.data = cse_crt_ct;\n\t\tapdu.datalen = sizeof(cse_crt_ct);\n\t\tapdu.lc = sizeof(cse_crt_ct);\n\t\tbreak;\n\tdefault:\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);\n\t}", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"MSE restore error\");", "\tprv->security_env = *env;\n\tprv->security_env.operation = operation;", "\tLOG_FUNC_RETURN(ctx, 0);\n}", "\nstatic int\niasecc_chv_verify_pinpad(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd, int *tries_left)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tunsigned char buffer[0x100];\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx, \"CHV PINPAD PIN reference %i\", pin_cmd->pin_reference);", "\trv = iasecc_pin_is_verified(card, pin_cmd, tries_left);\n\tif (!rv)\n\t\tLOG_FUNC_RETURN(ctx, rv);", "\tif (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) {\n\t\tsc_log(ctx, \"Reader not ready for PIN PAD\");\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_READER);\n\t}", "\t/* When PIN stored length available\n\t * P10 verify data contains full template of 'VERIFY PIN' APDU.\n\t * Without PIN stored length\n\t * pin-pad has to set the Lc and fill PIN data itself.\n\t * Not all pin-pads support this case\n\t */\n\tpin_cmd->pin1.len = pin_cmd->pin1.stored_length;\n\tpin_cmd->pin1.length_offset = 5;", "\tmemset(buffer, 0xFF, sizeof(buffer));\n\tpin_cmd->pin1.data = buffer;", "\tpin_cmd->cmd = SC_PIN_CMD_VERIFY;\n\tpin_cmd->flags |= SC_PIN_CMD_USE_PINPAD;", "\t/*\n\tif (card->reader && card->reader->ops && card->reader->ops->load_message) {\n\t\trv = card->reader->ops->load_message(card->reader, card->slot, 0, \"Here we are!\");\n\t\tsc_log(ctx, \"Load message returned %i\", rv);\n\t}\n\t*/", "\trv = iso_ops->pin_cmd(card, pin_cmd, tries_left);\n\tsc_log(ctx, \"rv %i\", rv);", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_chv_verify(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd,\n\t\tint *tries_left)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_acl_entry acl = pin_cmd->pin1.acls[IASECC_ACLS_CHV_VERIFY];\n\tstruct sc_apdu apdu;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx, \"Verify CHV PIN(ref:%i,len:%i,acl:%X:%X)\", pin_cmd->pin_reference, pin_cmd->pin1.len,\n\t\t\tacl.method, acl.key_ref);", "\tif (acl.method & IASECC_SCB_METHOD_SM) {\n\t\trv = iasecc_sm_pin_verify(card, acl.key_ref, pin_cmd, tries_left);\n\t\tLOG_FUNC_RETURN(ctx, rv);\n\t}", "\tif (pin_cmd->pin1.data && !pin_cmd->pin1.len) {\n\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x20, 0, pin_cmd->pin_reference);\n\t}\n\telse if (pin_cmd->pin1.data && pin_cmd->pin1.len) {\n\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x20, 0, pin_cmd->pin_reference);\n\t\tapdu.data = pin_cmd->pin1.data;\n\t\tapdu.datalen = pin_cmd->pin1.len;\n\t\tapdu.lc = pin_cmd->pin1.len;\n\t}\n\telse if ((card->reader->capabilities & SC_READER_CAP_PIN_PAD) && !pin_cmd->pin1.data && !pin_cmd->pin1.len) {\n\t\trv = iasecc_chv_verify_pinpad(card, pin_cmd, tries_left);\n\t\tsc_log(ctx, \"Result of verifying CHV with PIN pad %i\", rv);\n\t\tLOG_FUNC_RETURN(ctx, rv);\n\t}\n\telse {\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);\n\t}", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");", "\tif (tries_left && apdu.sw1 == 0x63 && (apdu.sw2 & 0xF0) == 0xC0)\n\t\t*tries_left = apdu.sw2 & 0x0F;", "\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_se_at_to_chv_reference(struct sc_card *card, unsigned reference,\n\t\tunsigned *chv_reference)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_se_info se;\n\tstruct sc_crt crt;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx, \"SE reference %i\", reference);", "\tif (reference > IASECC_SE_REF_MAX)\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);", "\tmemset(&se, 0, sizeof(se));\n\tse.reference = reference;", "\trv = iasecc_se_get_info(card, &se);\n\tLOG_TEST_RET(ctx, rv, \"SDO get data error\");", "\tmemset(&crt, 0, sizeof(crt));\n\tcrt.tag = IASECC_CRT_TAG_AT;\n\tcrt.usage = IASECC_UQB_AT_USER_PASSWORD;", "\trv = iasecc_se_get_crt(card, &se, &crt);\n\tLOG_TEST_RET(ctx, rv, \"no authentication template for USER PASSWORD\");", "\tif (chv_reference)\n\t\t*chv_reference = crt.refs[0];", "\tsc_file_free(se.df);", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_pin_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd_data,\n\t\tint *tries_left)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_pin_cmd_data pin_cmd;\n struct sc_acl_entry acl = pin_cmd_data->pin1.acls[IASECC_ACLS_CHV_VERIFY];\n\tint rv = SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;", "\tLOG_FUNC_CALLED(ctx);", "\tif (pin_cmd_data->pin_type != SC_AC_CHV)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"PIN type is not supported for the verification\");", "\tsc_log(ctx, \"Verify ACL(method:%X;ref:%X)\", acl.method, acl.key_ref);\n\tif (acl.method != IASECC_SCB_ALWAYS)\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED);", "\tpin_cmd = *pin_cmd_data;\n\tpin_cmd.pin1.data = (unsigned char *)\"\";\n\tpin_cmd.pin1.len = 0;", "\trv = iasecc_chv_verify(card, &pin_cmd, tries_left);", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_pin_verify(struct sc_card *card, unsigned type, unsigned reference,\n\t\tconst unsigned char *data, size_t data_len, int *tries_left)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_pin_cmd_data pin_cmd;\n\tunsigned chv_ref = reference;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx,\n\t \"Verify PIN(type:%X,ref:%i,data(len:%\"SC_FORMAT_LEN_SIZE_T\"u,%p)\",\n\t type, reference, data_len, data);", "\tif (type == SC_AC_AUT) {\n\t\trv = iasecc_sm_external_authentication(card, reference, tries_left);\n\t\tLOG_FUNC_RETURN(ctx, rv);\n\t}\n\telse if (type == SC_AC_SCB) {\n\t\tif (reference & IASECC_SCB_METHOD_USER_AUTH) {\n\t\t\ttype = SC_AC_SEN;\n\t\t\treference = reference & IASECC_SCB_METHOD_MASK_REF;\n\t\t}\n\t\telse {\n\t\t\tsc_log(ctx, \"Do not try to verify non CHV PINs\");\n\t\t\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n\t\t}\n\t}", "\tif (type == SC_AC_SEN) {\n\t\trv = iasecc_se_at_to_chv_reference(card, reference, &chv_ref);\n\t\tLOG_TEST_RET(ctx, rv, \"SE AT to CHV reference error\");\n\t}", "\tmemset(&pin_cmd, 0, sizeof(pin_cmd));\n\tpin_cmd.pin_type = SC_AC_CHV;\n\tpin_cmd.pin_reference = chv_ref;\n\tpin_cmd.cmd = SC_PIN_CMD_VERIFY;", "\trv = iasecc_pin_get_policy(card, &pin_cmd);\n\tLOG_TEST_RET(ctx, rv, \"Get 'PIN policy' error\");", "\tpin_cmd.pin1.data = data;\n\tpin_cmd.pin1.len = data_len;", "\trv = iasecc_pin_is_verified(card, &pin_cmd, tries_left);\n\tif (data && !data_len)\n\t\tLOG_FUNC_RETURN(ctx, rv);", "\tif (!rv) {\n\t\tif (iasecc_chv_cache_is_verified(card, &pin_cmd))\n\t\t\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n\t}\n\telse if (rv != SC_ERROR_PIN_CODE_INCORRECT && rv != SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) {\n\t\tLOG_FUNC_RETURN(ctx, rv);\n\t}", "\tiasecc_chv_cache_clean(card, &pin_cmd);", "\trv = iasecc_chv_verify(card, &pin_cmd, tries_left);\n\tLOG_TEST_RET(ctx, rv, \"PIN CHV verification error\");", "\trv = iasecc_chv_cache_verified(card, &pin_cmd);", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_chv_change_pinpad(struct sc_card *card, unsigned reference, int *tries_left)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_pin_cmd_data pin_cmd;\n\tunsigned char pin1_data[0x100], pin2_data[0x100];\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx, \"CHV PINPAD PIN reference %i\", reference);", "\tmemset(pin1_data, 0xFF, sizeof(pin1_data));\n\tmemset(pin2_data, 0xFF, sizeof(pin2_data));", "\tif (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) {\n\t\tsc_log(ctx, \"Reader not ready for PIN PAD\");\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_READER);\n\t}", "\tmemset(&pin_cmd, 0, sizeof(pin_cmd));\n\tpin_cmd.pin_type = SC_AC_CHV;\n\tpin_cmd.pin_reference = reference;\n\tpin_cmd.cmd = SC_PIN_CMD_CHANGE;\n\tpin_cmd.flags |= SC_PIN_CMD_USE_PINPAD;", "\trv = iasecc_pin_get_policy(card, &pin_cmd);\n\tLOG_TEST_RET(ctx, rv, \"Get 'PIN policy' error\");", "\t/* Some pin-pads do not support mode with Lc=0.\n\t * Give them a chance to work with some cards.\n\t */\n\tif ((pin_cmd.pin1.min_length == pin_cmd.pin1.stored_length) && (pin_cmd.pin1.max_length == pin_cmd.pin1.min_length))\n\t\tpin_cmd.pin1.len = pin_cmd.pin1.stored_length;\n\telse\n\t\tpin_cmd.pin1.len = 0;", "\tpin_cmd.pin1.length_offset = 5;\n\tpin_cmd.pin1.data = pin1_data;", "\tmemcpy(&pin_cmd.pin2, &pin_cmd.pin1, sizeof(pin_cmd.pin1));\n\tpin_cmd.pin2.data = pin2_data;", "\tsc_log(ctx,\n\t \"PIN1 max/min/stored: %\"SC_FORMAT_LEN_SIZE_T\"u/%\"SC_FORMAT_LEN_SIZE_T\"u/%\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t pin_cmd.pin1.max_length, pin_cmd.pin1.min_length,\n\t pin_cmd.pin1.stored_length);\n\tsc_log(ctx,\n\t \"PIN2 max/min/stored: %\"SC_FORMAT_LEN_SIZE_T\"u/%\"SC_FORMAT_LEN_SIZE_T\"u/%\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t pin_cmd.pin2.max_length, pin_cmd.pin2.min_length,\n\t pin_cmd.pin2.stored_length);\n\trv = iso_ops->pin_cmd(card, &pin_cmd, tries_left);", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\n#if 0\nstatic int\niasecc_chv_set_pinpad(struct sc_card *card, unsigned char reference)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_pin_cmd_data pin_cmd;\n\tunsigned char pin_data[0x100];\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx, \"Set CHV PINPAD PIN reference %i\", reference);", "\tmemset(pin_data, 0xFF, sizeof(pin_data));", "\tif (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) {\n\t\tsc_log(ctx, \"Reader not ready for PIN PAD\");\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_READER);\n\t}", "\tmemset(&pin_cmd, 0, sizeof(pin_cmd));\n\tpin_cmd.pin_type = SC_AC_CHV;\n\tpin_cmd.pin_reference = reference;\n\tpin_cmd.cmd = SC_PIN_CMD_UNBLOCK;\n\tpin_cmd.flags |= SC_PIN_CMD_USE_PINPAD;", "\trv = iasecc_pin_get_policy(card, &pin_cmd);\n\tLOG_TEST_RET(ctx, rv, \"Get 'PIN policy' error\");", "\tif ((pin_cmd.pin1.min_length == pin_cmd.pin1.stored_length) && (pin_cmd.pin1.max_length == pin_cmd.pin1.min_length))\n\t\tpin_cmd.pin1.len = pin_cmd.pin1.stored_length;\n\telse\n\t\tpin_cmd.pin1.len = 0;", "\tpin_cmd.pin1.length_offset = 5;\n\tpin_cmd.pin1.data = pin_data;", "\tmemcpy(&pin_cmd.pin2, &pin_cmd.pin1, sizeof(pin_cmd.pin1));\n\tmemset(&pin_cmd.pin1, 0, sizeof(pin_cmd.pin1));\n\tpin_cmd.flags |= SC_PIN_CMD_IMPLICIT_CHANGE;", "\tsc_log(ctx, \"PIN1(max:%i,min:%i)\", pin_cmd.pin1.max_length, pin_cmd.pin1.min_length);\n\tsc_log(ctx, \"PIN2(max:%i,min:%i)\", pin_cmd.pin2.max_length, pin_cmd.pin2.min_length);", "\trv = iso_ops->pin_cmd(card, &pin_cmd, NULL);\n\tLOG_FUNC_RETURN(ctx, rv);\n}\n#endif", "\nstatic int\niasecc_pin_get_policy (struct sc_card *card, struct sc_pin_cmd_data *data)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_file *save_current_df = NULL, *save_current_ef = NULL;\n\tstruct iasecc_sdo sdo;\n\tstruct sc_path path;\n\tunsigned ii;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx, \"iasecc_pin_get_policy(card:%p)\", card);", "\tif (data->pin_type != SC_AC_CHV) {\n\t\tsc_log(ctx, \"To unblock PIN it's CHV reference should be presented\");\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);\n\t}", "\tif (card->cache.valid && card->cache.current_df) {\n\t\tsc_file_dup(&save_current_df, card->cache.current_df);\n\t\tif (save_current_df == NULL) {\n\t\t\trv = SC_ERROR_OUT_OF_MEMORY;\n\t\t\tsc_log(ctx, \"Cannot duplicate current DF file\");\n\t\t\tgoto err;\n\t\t}\n\t}", "\tif (card->cache.valid && card->cache.current_ef) {\n\t\tsc_file_dup(&save_current_ef, card->cache.current_ef);\n\t\tif (save_current_ef == NULL) {\n\t\t\trv = SC_ERROR_OUT_OF_MEMORY;\n\t\t\tsc_log(ctx, \"Cannot duplicate current EF file\");\n\t\t\tgoto err;\n\t\t}\n\t}", "\tif (!(data->pin_reference & IASECC_OBJECT_REF_LOCAL) && card->cache.valid && card->cache.current_df) {\n\t\tsc_format_path(\"3F00\", &path);\n\t\tpath.type = SC_PATH_TYPE_FILE_ID;\n\t\trv = iasecc_select_file(card, &path, NULL);\n\t\tLOG_TEST_GOTO_ERR(ctx, rv, \"Unable to select MF\");\n\t}", "\tmemset(&sdo, 0, sizeof(sdo));\n\tsdo.sdo_class = IASECC_SDO_CLASS_CHV;", "\tsdo.sdo_ref = data->pin_reference & ~IASECC_OBJECT_REF_LOCAL;", "\tsc_log(ctx, \"iasecc_pin_get_policy() reference %i\", sdo.sdo_ref);", "\trv = iasecc_sdo_get_data(card, &sdo);\n\tLOG_TEST_GOTO_ERR(ctx, rv, \"Cannot get SDO PIN data\");", "\tif (sdo.docp.acls_contact.size == 0) {\n\t\trv = SC_ERROR_INVALID_DATA;\n\t\tsc_log(ctx, \"Extremely strange ... there is no ACLs\");\n\t\tgoto err;\n\t}", "\tsc_log(ctx,\n\t \"iasecc_pin_get_policy() sdo.docp.size.size %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t sdo.docp.size.size);\n\tfor (ii=0; ii<sizeof(sdo.docp.scbs); ii++) {\n\t\tstruct iasecc_se_info se;\n\t\tunsigned char scb = sdo.docp.scbs[ii];\n\t\tstruct sc_acl_entry *acl = &data->pin1.acls[ii];\n\t\tint crt_num = 0;", "\t\tmemset(&se, 0, sizeof(se));\n\t\tmemset(&acl->crts, 0, sizeof(acl->crts));", "\t\tsc_log(ctx, \"iasecc_pin_get_policy() set info acls: SCB 0x%X\", scb);\n\t\t/* acl->raw_value = scb; */\n\t\tacl->method = scb & IASECC_SCB_METHOD_MASK;\n\t\tacl->key_ref = scb & IASECC_SCB_METHOD_MASK_REF;", "\t\tif (scb==0 || scb==0xFF)\n\t\t\tcontinue;", "\t\tif (se.reference != (int)acl->key_ref) {\n\t\t\tmemset(&se, 0, sizeof(se));", "\t\t\tse.reference = acl->key_ref;", "\t\t\trv = iasecc_se_get_info(card, &se);\n\t\t\tLOG_TEST_GOTO_ERR(ctx, rv, \"SDO get data error\");\n\t\t}", "\t\tif (scb & IASECC_SCB_METHOD_USER_AUTH) {\n\t\t\trv = iasecc_se_get_crt_by_usage(card, &se,\n\t\t\t\t\tIASECC_CRT_TAG_AT, IASECC_UQB_AT_USER_PASSWORD, &acl->crts[crt_num]);\n\t\t\tLOG_TEST_GOTO_ERR(ctx, rv, \"no authentication template for 'USER PASSWORD'\");\n\t\t\tsc_log(ctx, \"iasecc_pin_get_policy() scb:0x%X; sdo_ref:[%i,%i,...]\",\n\t\t\t\t\tscb, acl->crts[crt_num].refs[0], acl->crts[crt_num].refs[1]);\n\t\t\tcrt_num++;\n\t\t}", "\t\tif (scb & (IASECC_SCB_METHOD_SM | IASECC_SCB_METHOD_EXT_AUTH)) {\n\t\t\tsc_log(ctx, \"'SM' and 'EXTERNAL AUTHENTICATION' protection methods are not supported: SCB:0x%X\", scb);\n\t\t\t/* Set to 'NEVER' if all conditions are needed or\n\t\t\t * there is no user authentication method allowed */\n\t\t\tif (!crt_num || (scb & IASECC_SCB_METHOD_NEED_ALL))\n\t\t\t\tacl->method = SC_AC_NEVER;\n\t\t\tcontinue;\n\t\t}", "\t\tsc_file_free(se.df);\n\t}", "\tif (sdo.data.chv.size_max.value)\n\t\tdata->pin1.max_length = *sdo.data.chv.size_max.value;\n\tif (sdo.data.chv.size_min.value)\n\t\tdata->pin1.min_length = *sdo.data.chv.size_min.value;\n\tif (sdo.docp.tries_maximum.value)\n\t\tdata->pin1.max_tries = *sdo.docp.tries_maximum.value;\n\tif (sdo.docp.tries_remaining.value)\n\t\tdata->pin1.tries_left = *sdo.docp.tries_remaining.value;\n\tif (sdo.docp.size.value) {\n\t\tfor (ii=0; ii<sdo.docp.size.size; ii++)\n\t\t\tdata->pin1.stored_length = ((data->pin1.stored_length) << 8) + *(sdo.docp.size.value + ii);\n\t}", "\tdata->pin1.encoding = SC_PIN_ENCODING_ASCII;\n\tdata->pin1.offset = 5;\n\tdata->pin1.logged_in = SC_PIN_STATE_UNKNOWN;", "\tsc_log(ctx,\n\t \"PIN policy: size max/min %\"SC_FORMAT_LEN_SIZE_T\"u/%\"SC_FORMAT_LEN_SIZE_T\"u, tries max/left %i/%i\",\n\t data->pin1.max_length, data->pin1.min_length,\n\t data->pin1.max_tries, data->pin1.tries_left);\n\tiasecc_sdo_free_fields(card, &sdo);", "\tif (save_current_df) {\n\t\tsc_log(ctx, \"iasecc_pin_get_policy() restore current DF\");\n\t\trv = iasecc_select_file(card, &save_current_df->path, NULL);\n\t\tLOG_TEST_GOTO_ERR(ctx, rv, \"Cannot return to saved DF\");\n\t}", "\tif (save_current_ef) {\n\t\tsc_log(ctx, \"iasecc_pin_get_policy() restore current EF\");\n\t\trv = iasecc_select_file(card, &save_current_ef->path, NULL);\n\t\tLOG_TEST_GOTO_ERR(ctx, rv, \"Cannot return to saved EF\");\n\t}", "err:\n\tsc_file_free(save_current_df);\n\tsc_file_free(save_current_ef);", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_keyset_change(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_sdo_update update;\n\tstruct iasecc_sdo sdo;\n\tunsigned scb;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx, \"Change keyset(ref:%i,lengths:%i)\", data->pin_reference, data->pin2.len);\n\tif (!data->pin2.data || data->pin2.len < 32)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"Needs at least 32 bytes for a new keyset value\");", "\tmemset(&sdo, 0, sizeof(sdo));\n\tsdo.sdo_class = IASECC_SDO_CLASS_KEYSET;\n\tsdo.sdo_ref = data->pin_reference;", "\trv = iasecc_sdo_get_data(card, &sdo);\n\tLOG_TEST_RET(ctx, rv, \"Cannot get keyset data\");", "\tif (sdo.docp.acls_contact.size == 0)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"Bewildered ... there are no ACLs\");\n\tscb = sdo.docp.scbs[IASECC_ACLS_KEYSET_PUT_DATA];\n\tiasecc_sdo_free_fields(card, &sdo);", "\tsc_log(ctx, \"SCB:0x%X\", scb);\n\tif (!(scb & IASECC_SCB_METHOD_SM))\n\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Other then protected by SM, the keyset change is not supported\");", "\tmemset(&update, 0, sizeof(update));\n\tupdate.magic = SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA;\n\tupdate.sdo_class = sdo.sdo_class;\n\tupdate.sdo_ref = sdo.sdo_ref;", "\tupdate.fields[0].parent_tag = IASECC_SDO_KEYSET_TAG;\n\tupdate.fields[0].tag = IASECC_SDO_KEYSET_TAG_MAC;\n\t/* FIXME is it safe to modify the const value here? */\n\tupdate.fields[0].value = (unsigned char *) data->pin2.data;\n\tupdate.fields[0].size = 16;", "\tupdate.fields[1].parent_tag = IASECC_SDO_KEYSET_TAG;\n\tupdate.fields[1].tag = IASECC_SDO_KEYSET_TAG_ENC;\n\t/* FIXME is it safe to modify the const value here? */\n\tupdate.fields[1].value = (unsigned char *) data->pin2.data + 16;\n\tupdate.fields[1].size = 16;", "\trv = iasecc_sm_sdo_update(card, (scb & IASECC_SCB_METHOD_MASK_REF), &update);\n\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_pin_change(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_apdu apdu;\n\tunsigned reference = data->pin_reference;\n\tunsigned char pin_data[0x100];\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx, \"Change PIN(ref:%i,type:0x%X,lengths:%i/%i)\", reference, data->pin_type, data->pin1.len, data->pin2.len);", "\tif ((card->reader->capabilities & SC_READER_CAP_PIN_PAD)) {\n\t\tif (!data->pin1.data && !data->pin1.len && !data->pin2.data && !data->pin2.len) {\n\t\t\trv = iasecc_chv_change_pinpad(card, reference, tries_left);\n\t\t\tsc_log(ctx, \"iasecc_pin_cmd(SC_PIN_CMD_CHANGE) chv_change_pinpad returned %i\", rv);\n\t\t\tLOG_FUNC_RETURN(ctx, rv);\n\t\t}\n\t}", "\tif (!data->pin1.data && data->pin1.len)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"Invalid PIN1 arguments\");", "\tif (!data->pin2.data && data->pin2.len)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"Invalid PIN2 arguments\");", "\trv = iasecc_pin_verify(card, data->pin_type, reference, data->pin1.data, data->pin1.len, tries_left);\n\tsc_log(ctx, \"iasecc_pin_cmd(SC_PIN_CMD_CHANGE) pin_verify returned %i\", rv);\n\tLOG_TEST_RET(ctx, rv, \"PIN verification error\");", "\tif ((unsigned)(data->pin1.len + data->pin2.len) > sizeof(pin_data))\n\t\tLOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, \"Buffer too small for the 'Change PIN' data\");", "\tif (data->pin1.data)\n\t\tmemcpy(pin_data, data->pin1.data, data->pin1.len);\n\tif (data->pin2.data)\n\t\tmemcpy(pin_data + data->pin1.len, data->pin2.data, data->pin2.len);", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x24, 0, reference);\n\tapdu.data = pin_data;\n\tapdu.datalen = data->pin1.len + data->pin2.len;\n\tapdu.lc = apdu.datalen;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"PIN cmd failed\");", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_pin_reset(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_file *save_current = NULL;\n\tstruct iasecc_sdo sdo;\n\tstruct sc_apdu apdu;\n\tunsigned reference, scb;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx, \"Reset PIN(ref:%i,lengths:%i/%i)\", data->pin_reference, data->pin1.len, data->pin2.len);", "\tif (data->pin_type != SC_AC_CHV)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"Unblock procedure can be used only with the PINs of type CHV\");", "\treference = data->pin_reference;", "\tif (!(data->pin_reference & IASECC_OBJECT_REF_LOCAL) && card->cache.valid && card->cache.current_df) {\n\t\tstruct sc_path path;", "\t\tsc_file_dup(&save_current, card->cache.current_df);\n\t\tif (save_current == NULL)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, \"Cannot duplicate current DF file\");", "\t\tsc_format_path(\"3F00\", &path);\n\t\tpath.type = SC_PATH_TYPE_FILE_ID;\n\t\trv = iasecc_select_file(card, &path, NULL);\n\t\tLOG_TEST_RET(ctx, rv, \"Unable to select MF\");\n\t}", "\tmemset(&sdo, 0, sizeof(sdo));\n\tsdo.sdo_class = IASECC_SDO_CLASS_CHV;\n\tsdo.sdo_ref = reference & ~IASECC_OBJECT_REF_LOCAL;", "\trv = iasecc_sdo_get_data(card, &sdo);\n\tLOG_TEST_RET(ctx, rv, \"Cannot get PIN data\");", "\tif (sdo.docp.acls_contact.size == 0)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"Extremely strange ... there are no ACLs\");", "\tscb = sdo.docp.scbs[IASECC_ACLS_CHV_RESET];\n\tdo {\n\t\tunsigned need_all = scb & IASECC_SCB_METHOD_NEED_ALL ? 1 : 0;\n\t\tunsigned char se_num = scb & IASECC_SCB_METHOD_MASK_REF;", "\t\tif (scb & IASECC_SCB_METHOD_USER_AUTH) {\n\t\t\tsc_log(ctx, \"Verify PIN in SE %X\", se_num);\n\t\t\trv = iasecc_pin_verify(card, SC_AC_SEN, se_num, data->pin1.data, data->pin1.len, tries_left);\n\t\t\tLOG_TEST_RET(ctx, rv, \"iasecc_pin_reset() verify PUK error\");", "\t\t\tif (!need_all)\n\t\t\t\tbreak;\n\t\t}", "\t\tif (scb & IASECC_SCB_METHOD_SM) {\n\t\t\trv = iasecc_sm_pin_reset(card, se_num, data);\n\t\t\tLOG_FUNC_RETURN(ctx, rv);\n\t\t}", "\t\tif (scb & IASECC_SCB_METHOD_EXT_AUTH) {\n\t\t\trv = iasecc_sm_external_authentication(card, reference, tries_left);\n\t\t\tLOG_TEST_RET(ctx, rv, \"iasecc_pin_reset() external authentication error\");\n\t\t}\n\t} while(0);", "\tiasecc_sdo_free_fields(card, &sdo);", "\tif (data->pin2.len) {\n\t\tsc_log(ctx, \"Reset PIN %X and set new value\", reference);\n\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x2C, 0x02, reference);\n\t\tapdu.data = data->pin2.data;\n\t\tapdu.datalen = data->pin2.len;\n\t\tapdu.lc = apdu.datalen;", "\t\trv = sc_transmit_apdu(card, &apdu);\n\t\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\t\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\t\tLOG_TEST_RET(ctx, rv, \"PIN cmd failed\");\n\t}\n\telse if (data->pin2.data) {\n\t\tsc_log(ctx, \"Reset PIN %X and set new value\", reference);\n\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x2C, 3, reference);", "\t\trv = sc_transmit_apdu(card, &apdu);\n\t\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\t\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\t\tLOG_TEST_RET(ctx, rv, \"PIN cmd failed\");\n\t}\n\telse {\n\t\tsc_log(ctx, \"Reset PIN %X and set new value with PIN-PAD\", reference);\n#if 0\n\t\trv = iasecc_chv_set_pinpad(card, reference);\n\t\tLOG_TEST_RET(ctx, rv, \"Reset PIN failed\");\n#else\n\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Reset retry counter with PIN PAD not supported \");\n#endif\n\t}", "\tif (save_current) {\n\t\trv = iasecc_select_file(card, &save_current->path, NULL);\n\t\tLOG_TEST_RET(ctx, rv, \"Cannot return to saved PATH\");\n\t}", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx, \"iasecc_pin_cmd() cmd 0x%X, PIN type 0x%X, PIN reference %i, PIN-1 %p:%i, PIN-2 %p:%i\",\n\t\t\tdata->cmd, data->pin_type, data->pin_reference,\n\t\t\tdata->pin1.data, data->pin1.len, data->pin2.data, data->pin2.len);", "\tswitch (data->cmd) {\n\tcase SC_PIN_CMD_VERIFY:\n\t\trv = iasecc_pin_verify(card, data->pin_type, data->pin_reference, data->pin1.data, data->pin1.len, tries_left);\n\t\tbreak;\n\tcase SC_PIN_CMD_CHANGE:\n\t\tif (data->pin_type == SC_AC_AUT)\n\t\t\trv = iasecc_keyset_change(card, data, tries_left);\n\t\telse\n\t\t\trv = iasecc_pin_change(card, data, tries_left);\n\t\tbreak;\n\tcase SC_PIN_CMD_UNBLOCK:\n\t\trv = iasecc_pin_reset(card, data, tries_left);\n\t\tbreak;\n\tcase SC_PIN_CMD_GET_INFO:\n\t\trv = iasecc_pin_get_policy(card, data);\n\t\tbreak;\n\tdefault:\n\t\tsc_log(ctx, \"Other pin commands not supported yet: 0x%X\", data->cmd);\n\t\trv = SC_ERROR_NOT_SUPPORTED;\n\t}", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_get_serialnr(struct sc_card *card, struct sc_serial_number *serial)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_iin *iin = &card->serialnr.iin;\n\tstruct sc_apdu apdu;\n\tunsigned char rbuf[0xC0];\n\tsize_t ii, offs;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tif (card->serialnr.len)\n\t\tgoto end;", "\tmemset(&card->serialnr, 0, sizeof(card->serialnr));", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xB0, 0x80 | IASECC_SFI_EF_SN, 0);\n\tapdu.le = sizeof(rbuf);\n\tapdu.resp = rbuf;\n\tapdu.resplen = sizeof(rbuf);", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"Get 'serial number' data failed\");", "\tif (rbuf[0] != ISO7812_PAN_SN_TAG)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, \"serial number parse error\");", "\tiin->mii = (rbuf[2] >> 4) & 0x0F;", "\tiin->country = 0;\n\tfor (ii=5; ii<8; ii++) {\n\t\tiin->country *= 10;\n\t\tiin->country += (rbuf[ii/2] >> ((ii & 0x01) ? 0 : 4)) & 0x0F;\n\t}", "\tiin->issuer_id = 0;\n\tfor (ii=8; ii<10; ii++) {\n\t\tiin->issuer_id *= 10;\n\t\tiin->issuer_id += (rbuf[ii/2] >> (ii & 0x01 ? 0 : 4)) & 0x0F;\n\t}", "\toffs = rbuf[1] > 8 ? rbuf[1] - 8 : 0;\n\tif (card->type == SC_CARD_TYPE_IASECC_SAGEM) {\n\t\t/* 5A 0A 92 50 00 20 10 10 25 00 01 3F */\n\t\t/* 00 02 01 01 02 50 00 13 */\n\t\tfor (ii=0; (ii < rbuf[1] - offs) && (ii + offs + 2 < sizeof(rbuf)); ii++)\n\t\t\t*(card->serialnr.value + ii) = ((rbuf[ii + offs + 1] & 0x0F) << 4)\n\t\t\t\t+ ((rbuf[ii + offs + 2] & 0xF0) >> 4) ;\n\t\tcard->serialnr.len = ii;\n\t}\n\telse {\n\t\tfor (ii=0; ii < rbuf[1] - offs; ii++)\n\t\t\t*(card->serialnr.value + ii) = rbuf[ii + offs + 2];\n\t\tcard->serialnr.len = ii;\n\t}", "\tdo {\n\t\tchar txt[0x200];", "\t\tfor (ii=0;ii<card->serialnr.len;ii++)\n\t\t\tsprintf(txt + ii*2, \"%02X\", *(card->serialnr.value + ii));", "\t\tsc_log(ctx, \"serial number '%s'; mii %i; country %i; issuer_id %li\", txt, iin->mii, iin->country, iin->issuer_id);\n\t} while(0);", "end:\n\tif (serial)\n\t\tmemcpy(serial, &card->serialnr, sizeof(*serial));", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_sdo_create(struct sc_card *card, struct iasecc_sdo *sdo)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_apdu apdu;\n\tunsigned char *data = NULL, sdo_class = sdo->sdo_class;\n\tstruct iasecc_sdo_update update;\n\tstruct iasecc_extended_tlv *field = NULL;\n\tint rv = SC_ERROR_NOT_SUPPORTED, data_len;", "\tLOG_FUNC_CALLED(ctx);\n\tif (sdo->magic != SC_CARDCTL_IASECC_SDO_MAGIC)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"Invalid SDO data\");", "\tsc_log(ctx, \"iasecc_sdo_create(card:%p) %02X%02X%02X\", card,\n\t\t\tIASECC_SDO_TAG_HEADER, sdo->sdo_class | 0x80, sdo->sdo_ref);", "\tdata_len = iasecc_sdo_encode_create(ctx, sdo, &data);\n\tLOG_TEST_RET(ctx, data_len, \"iasecc_sdo_create() cannot encode SDO create data\");\n\tsc_log(ctx, \"iasecc_sdo_create() create data(%i):%s\", data_len, sc_dump_hex(data, data_len));", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xDB, 0x3F, 0xFF);\n\tapdu.data = data;\n\tapdu.datalen = data_len;\n\tapdu.lc = data_len;\n\tapdu.flags |= SC_APDU_FLAGS_CHAINING;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"iasecc_sdo_create() SDO put data error\");", "\tmemset(&update, 0, sizeof(update));\n\tupdate.magic = SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA;\n\tupdate.sdo_class = sdo->sdo_class;\n\tupdate.sdo_ref = sdo->sdo_ref;", "\tif (sdo_class == IASECC_SDO_CLASS_RSA_PRIVATE) {\n\t\tupdate.fields[0] = sdo->data.prv_key.compulsory;\n\t\tupdate.fields[0].parent_tag = IASECC_SDO_PRVKEY_TAG;\n\t\tfield = &sdo->data.prv_key.compulsory;\n\t}\n\telse if (sdo_class == IASECC_SDO_CLASS_RSA_PUBLIC) {\n\t\tupdate.fields[0] = sdo->data.pub_key.compulsory;\n\t\tupdate.fields[0].parent_tag = IASECC_SDO_PUBKEY_TAG;\n\t\tfield = &sdo->data.pub_key.compulsory;\n\t}\n\telse if (sdo_class == IASECC_SDO_CLASS_KEYSET) {\n\t\tupdate.fields[0] = sdo->data.keyset.compulsory;\n\t\tupdate.fields[0].parent_tag = IASECC_SDO_KEYSET_TAG;\n\t\tfield = &sdo->data.keyset.compulsory;\n\t}", "\tif (update.fields[0].value && !update.fields[0].on_card) {\n\t\trv = iasecc_sdo_put_data(card, &update);\n\t\tLOG_TEST_RET(ctx, rv, \"failed to update 'Compulsory usage' data\");", "\t\tif (field)\n\t\t\tfield->on_card = 1;\n\t}", "\tfree(data);\n\tLOG_FUNC_RETURN(ctx, rv);\n}", "/* Oberthur's specific */\nstatic int\niasecc_sdo_delete(struct sc_card *card, struct iasecc_sdo *sdo)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_apdu apdu;\n\tunsigned char data[6] = {\n\t\t0x70, 0x04, 0xBF, 0xFF, 0xFF, 0x00\n\t};\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tif (sdo->magic != SC_CARDCTL_IASECC_SDO_MAGIC)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"Invalid SDO data\");", "\tdata[2] = IASECC_SDO_TAG_HEADER;\n\tdata[3] = sdo->sdo_class | 0x80;\n\tdata[4] = sdo->sdo_ref;\n\tsc_log(ctx, \"delete SDO %02X%02X%02X\", data[2], data[3], data[4]);", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xDB, 0x3F, 0xFF);\n\tapdu.data = data;\n\tapdu.datalen = sizeof(data);\n\tapdu.lc = sizeof(data);\n\tapdu.flags |= SC_APDU_FLAGS_CHAINING;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"delete SDO error\");", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_sdo_put_data(struct sc_card *card, struct iasecc_sdo_update *update)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_apdu apdu;\n\tint ii, rv;", "\tLOG_FUNC_CALLED(ctx);\n\tif (update->magic != SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"Invalid SDO update data\");", "\tfor(ii=0; update->fields[ii].tag && ii < IASECC_SDO_TAGS_UPDATE_MAX; ii++) {\n\t\tunsigned char *encoded = NULL;\n\t\tint encoded_len;", "\t\tencoded_len = iasecc_sdo_encode_update_field(ctx, update->sdo_class, update->sdo_ref,\n\t\t\t\t\t\t\t&update->fields[ii], &encoded);\n\t\tsc_log(ctx, \"iasecc_sdo_put_data() encode[%i]; tag %X; encoded_len %i\", ii, update->fields[ii].tag, encoded_len);\n\t\tLOG_TEST_RET(ctx, encoded_len, \"Cannot encode update data\");", "\t\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xDB, 0x3F, 0xFF);\n\t\tapdu.data = encoded;\n\t\tapdu.datalen = encoded_len;\n\t\tapdu.lc = encoded_len;\n\t\tapdu.flags |= SC_APDU_FLAGS_CHAINING;", "\t\trv = sc_transmit_apdu(card, &apdu);\n\t\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\t\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\t\tLOG_TEST_RET(ctx, rv, \"SDO put data error\");", "\t\tfree(encoded);\n\t}", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_sdo_key_rsa_put_data(struct sc_card *card, struct iasecc_sdo_rsa_update *update)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tunsigned char scb;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);", "\tif (update->sdo_prv_key) {\n\t\tsc_log(ctx, \"encode private rsa in %p\", &update->update_prv);\n\t\trv = iasecc_sdo_encode_rsa_update(card->ctx, update->sdo_prv_key, update->p15_rsa, &update->update_prv);\n\t\tLOG_TEST_RET(ctx, rv, \"failed to encode update of RSA private key\");\n\t}", "\tif (update->sdo_pub_key) {\n\t\tsc_log(ctx, \"encode public rsa in %p\", &update->update_pub);\n\t\tif (card->type == SC_CARD_TYPE_IASECC_SAGEM) {\n\t\t\tif (update->sdo_pub_key->data.pub_key.cha.value) {\n\t\t\t\tfree(update->sdo_pub_key->data.pub_key.cha.value);\n\t\t\t\tmemset(&update->sdo_pub_key->data.pub_key.cha, 0, sizeof(update->sdo_pub_key->data.pub_key.cha));\n\t\t\t}\n\t\t}\n\t\trv = iasecc_sdo_encode_rsa_update(card->ctx, update->sdo_pub_key, update->p15_rsa, &update->update_pub);\n\t\tLOG_TEST_RET(ctx, rv, \"failed to encode update of RSA public key\");\n\t}", "\tif (update->sdo_prv_key) {\n\t\tsc_log(ctx, \"reference of the private key to store: %X\", update->sdo_prv_key->sdo_ref);", "\t\tif (update->sdo_prv_key->docp.acls_contact.size == 0)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"extremely strange ... there are no ACLs\");", "\t\tscb = update->sdo_prv_key->docp.scbs[IASECC_ACLS_RSAKEY_PUT_DATA];\n\t\tsc_log(ctx, \"'UPDATE PRIVATE RSA' scb 0x%X\", scb);", "\t\tdo {\n\t\t\tunsigned all_conditions = scb & IASECC_SCB_METHOD_NEED_ALL ? 1 : 0;", "\t\t\tif ((scb & IASECC_SCB_METHOD_USER_AUTH) && !all_conditions)\n\t\t\t\tbreak;", "\t\t\tif (scb & IASECC_SCB_METHOD_EXT_AUTH)\n\t\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Not yet\");", "\t\t\tif (scb & IASECC_SCB_METHOD_SM) {\n#ifdef ENABLE_SM\n\t\t\t\trv = iasecc_sm_rsa_update(card, scb & IASECC_SCB_METHOD_MASK_REF, update);\n\t\t\t\tLOG_FUNC_RETURN(ctx, rv);\n#else\n\t\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"built without support of Secure-Messaging\");\n#endif\n\t\t\t}\n\t\t} while(0);", "\t\trv = iasecc_sdo_put_data(card, &update->update_prv);\n\t\tLOG_TEST_RET(ctx, rv, \"failed to update of RSA private key\");\n\t}", "\tif (update->sdo_pub_key) {\n\t\tsc_log(ctx, \"reference of the public key to store: %X\", update->sdo_pub_key->sdo_ref);", "\t\trv = iasecc_sdo_put_data(card, &update->update_pub);\n\t\tLOG_TEST_RET(ctx, rv, \"failed to update of RSA public key\");\n\t}", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_sdo_tag_from_class(unsigned sdo_class)\n{\n\tswitch (sdo_class & ~IASECC_OBJECT_REF_LOCAL) {\n\tcase IASECC_SDO_CLASS_CHV:\n\t\treturn IASECC_SDO_CHV_TAG;\n\tcase IASECC_SDO_CLASS_RSA_PRIVATE:\n\t\treturn IASECC_SDO_PRVKEY_TAG;\n\tcase IASECC_SDO_CLASS_RSA_PUBLIC:\n\t\treturn IASECC_SDO_PUBKEY_TAG;\n\tcase IASECC_SDO_CLASS_SE:\n\t\treturn IASECC_SDO_CLASS_SE;\n\tcase IASECC_SDO_CLASS_KEYSET:\n\t\treturn IASECC_SDO_KEYSET_TAG;\n\t}", "\treturn -1;\n}", "\nstatic int\niasecc_sdo_get_tagged_data(struct sc_card *card, int sdo_tag, struct iasecc_sdo *sdo)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_apdu apdu;\n\tunsigned char sbuf[0x100];\n\tsize_t offs = sizeof(sbuf) - 1;\n\tunsigned char rbuf[0x400];\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);", "\tsbuf[offs--] = 0x80;\n\tsbuf[offs--] = sdo_tag & 0xFF;\n\tif ((sdo_tag >> 8) & 0xFF)\n\t\tsbuf[offs--] = (sdo_tag >> 8) & 0xFF;\n\tsbuf[offs] = sizeof(sbuf) - offs - 1;\n\toffs--;", "\tsbuf[offs--] = sdo->sdo_ref & 0x9F;\n\tsbuf[offs--] = sdo->sdo_class | IASECC_OBJECT_REF_LOCAL;\n\tsbuf[offs--] = IASECC_SDO_TAG_HEADER;", "\tsbuf[offs] = sizeof(sbuf) - offs - 1;\n\toffs--;\n\tsbuf[offs--] = IASECC_SDO_TEMPLATE_TAG;", "\tsbuf[offs] = sizeof(sbuf) - offs - 1;\n\toffs--;\n\tsbuf[offs] = 0x4D;", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xCB, 0x3F, 0xFF);\n\tapdu.data = sbuf + offs;\n\tapdu.datalen = sizeof(sbuf) - offs;\n\tapdu.lc = sizeof(sbuf) - offs;\n\tapdu.resp = rbuf;\n\tapdu.resplen = sizeof(rbuf);\n\tapdu.le = 0x100;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"SDO get data error\");", "\trv = iasecc_sdo_parse(card, apdu.resp, apdu.resplen, sdo);\n\tLOG_TEST_RET(ctx, rv, \"cannot parse SDO data\");", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_sdo_get_data(struct sc_card *card, struct iasecc_sdo *sdo)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tint rv, sdo_tag;", "\tLOG_FUNC_CALLED(ctx);", "\tsdo_tag = iasecc_sdo_tag_from_class(sdo->sdo_class);", "\trv = iasecc_sdo_get_tagged_data(card, sdo_tag, sdo);\n\t/* When there is no public data 'GET DATA' returns error */\n\tif (rv != SC_ERROR_INCORRECT_PARAMETERS)\n\t\tLOG_TEST_RET(ctx, rv, \"cannot parse ECC SDO data\");", "\trv = iasecc_sdo_get_tagged_data(card, IASECC_DOCP_TAG, sdo);\n\tLOG_TEST_RET(ctx, rv, \"cannot parse ECC DOCP data\");", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_sdo_generate(struct sc_card *card, struct iasecc_sdo *sdo)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_sdo_update update_pubkey;\n\tstruct sc_apdu apdu;\n\tunsigned char scb, sbuf[5], rbuf[0x400], exponent[3] = {0x01, 0x00, 0x01};\n\tint offs = 0, rv = SC_ERROR_NOT_SUPPORTED;", "\tLOG_FUNC_CALLED(ctx);", "\tif (sdo->sdo_class != IASECC_SDO_CLASS_RSA_PRIVATE)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"For a moment, only RSA_PRIVATE class can be accepted for the SDO generation\");", "\tif (sdo->docp.acls_contact.size == 0)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, \"Bewildered ... there are no ACLs\");", "\tscb = sdo->docp.scbs[IASECC_ACLS_RSAKEY_GENERATE];\n\tsc_log(ctx, \"'generate RSA key' SCB 0x%X\", scb);\n\tdo {\n\t\tunsigned all_conditions = scb & IASECC_SCB_METHOD_NEED_ALL ? 1 : 0;", "\t\tif (scb & IASECC_SCB_METHOD_USER_AUTH)\n\t\t\tif (!all_conditions)\n\t\t\t\tbreak;", "\t\tif (scb & IASECC_SCB_METHOD_EXT_AUTH)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Not yet\");", "\t\tif (scb & IASECC_SCB_METHOD_SM) {\n\t\t\trv = iasecc_sm_rsa_generate(card, scb & IASECC_SCB_METHOD_MASK_REF, sdo);\n LOG_FUNC_RETURN(ctx, rv);\n\t\t}\n\t} while(0);", "\tmemset(&update_pubkey, 0, sizeof(update_pubkey));\n\tupdate_pubkey.magic = SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA;\n\tupdate_pubkey.sdo_class = IASECC_SDO_CLASS_RSA_PUBLIC;\n\tupdate_pubkey.sdo_ref = sdo->sdo_ref;", "\tupdate_pubkey.fields[0].parent_tag = IASECC_SDO_PUBKEY_TAG;\n\tupdate_pubkey.fields[0].tag = IASECC_SDO_PUBKEY_TAG_E;\n\tupdate_pubkey.fields[0].value = exponent;\n\tupdate_pubkey.fields[0].size = sizeof(exponent);", "\trv = iasecc_sdo_put_data(card, &update_pubkey);\n\tLOG_TEST_RET(ctx, rv, \"iasecc_sdo_generate() update SDO public key failed\");", "\toffs = 0;\n\tsbuf[offs++] = IASECC_SDO_TEMPLATE_TAG;\n\tsbuf[offs++] = 0x03;\n\tsbuf[offs++] = IASECC_SDO_TAG_HEADER;\n\tsbuf[offs++] = IASECC_SDO_CLASS_RSA_PRIVATE | IASECC_OBJECT_REF_LOCAL;\n\tsbuf[offs++] = sdo->sdo_ref & ~IASECC_OBJECT_REF_LOCAL;", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x47, 0x00, 0x00);\n\tapdu.data = sbuf;\n\tapdu.datalen = offs;\n\tapdu.lc = offs;\n\tapdu.resp = rbuf;\n\tapdu.resplen = sizeof(rbuf);\n\tapdu.le = 0x100;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"SDO get data error\");", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_get_chv_reference_from_se(struct sc_card *card, int *se_reference)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_se_info se;\n\tstruct sc_crt crt;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);", "\tif (!se_reference)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"Invalid arguments\");", "\tmemset(&se, 0, sizeof(se));\n\tse.reference = *se_reference;", "\trv = iasecc_se_get_info(card, &se);\n\tLOG_TEST_RET(ctx, rv, \"get SE info error\");", "\tmemset(&crt, 0, sizeof(crt));\n\tcrt.tag = IASECC_CRT_TAG_AT;\n\tcrt.usage = IASECC_UQB_AT_USER_PASSWORD;", "\trv = iasecc_se_get_crt(card, &se, &crt);\n\tLOG_TEST_RET(ctx, rv, \"Cannot get 'USER PASSWORD' authentication template\");", "\tsc_file_free(se.df);\n\tLOG_FUNC_RETURN(ctx, crt.refs[0]);\n}", "\nstatic int\niasecc_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_sdo *sdo = (struct iasecc_sdo *) ptr;", "\tswitch (cmd) {\n\tcase SC_CARDCTL_GET_SERIALNR:\n\t\treturn iasecc_get_serialnr(card, (struct sc_serial_number *)ptr);\n\tcase SC_CARDCTL_IASECC_SDO_CREATE:\n\t\tsc_log(ctx, \"CMD SC_CARDCTL_IASECC_SDO_CREATE: sdo_class %X\", sdo->sdo_class);\n\t\treturn iasecc_sdo_create(card, (struct iasecc_sdo *) ptr);\n\tcase SC_CARDCTL_IASECC_SDO_DELETE:\n\t\tsc_log(ctx, \"CMD SC_CARDCTL_IASECC_SDO_DELETE: sdo_class %X\", sdo->sdo_class);\n\t\treturn iasecc_sdo_delete(card, (struct iasecc_sdo *) ptr);\n\tcase SC_CARDCTL_IASECC_SDO_PUT_DATA:\n\t\tsc_log(ctx, \"CMD SC_CARDCTL_IASECC_SDO_PUT_DATA: sdo_class %X\", sdo->sdo_class);\n\t\treturn iasecc_sdo_put_data(card, (struct iasecc_sdo_update *) ptr);\n\tcase SC_CARDCTL_IASECC_SDO_KEY_RSA_PUT_DATA:\n\t\tsc_log(ctx, \"CMD SC_CARDCTL_IASECC_SDO_KEY_RSA_PUT_DATA\");\n\t\treturn iasecc_sdo_key_rsa_put_data(card, (struct iasecc_sdo_rsa_update *) ptr);\n\tcase SC_CARDCTL_IASECC_SDO_GET_DATA:\n\t\tsc_log(ctx, \"CMD SC_CARDCTL_IASECC_SDO_GET_DATA: sdo_class %X\", sdo->sdo_class);\n\t\treturn iasecc_sdo_get_data(card, (struct iasecc_sdo *) ptr);\n\tcase SC_CARDCTL_IASECC_SDO_GENERATE:\n\t\tsc_log(ctx, \"CMD SC_CARDCTL_IASECC_SDO_GET_DATA: sdo_class %X\", sdo->sdo_class);\n\t\treturn iasecc_sdo_generate(card, (struct iasecc_sdo *) ptr);\n\tcase SC_CARDCTL_GET_SE_INFO:\n\t\tsc_log(ctx, \"CMD SC_CARDCTL_GET_SE_INFO: sdo_class %X\", sdo->sdo_class);\n\t\treturn iasecc_se_get_info(card, (struct iasecc_se_info *) ptr);\n\tcase SC_CARDCTL_GET_CHV_REFERENCE_IN_SE:\n\t\tsc_log(ctx, \"CMD SC_CARDCTL_GET_CHV_REFERENCE_IN_SE\");\n\t\treturn iasecc_get_chv_reference_from_se(card, (int *)ptr);\n\tcase SC_CARDCTL_IASECC_GET_FREE_KEY_REFERENCE:\n\t\tsc_log(ctx, \"CMD SC_CARDCTL_IASECC_GET_FREE_KEY_REFERENCE\");\n\t\treturn iasecc_get_free_reference(card, (struct iasecc_ctl_get_free_reference *)ptr);\n\t}\n\treturn SC_ERROR_NOT_SUPPORTED;\n}", "\nstatic int\niasecc_decipher(struct sc_card *card,\n\t\tconst unsigned char *in, size_t in_len,\n\t\tunsigned char *out, size_t out_len)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct sc_apdu apdu;\n\tunsigned char sbuf[0x200];\n\tunsigned char resp[SC_MAX_APDU_BUFFER_SIZE];\n\tsize_t offs;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(card->ctx,\n\t \"crgram_len %\"SC_FORMAT_LEN_SIZE_T\"u; outlen %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t in_len, out_len);\n\tif (!out || !out_len || in_len > SC_MAX_APDU_BUFFER_SIZE)\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);", "\toffs = 0;\n\tsbuf[offs++] = 0x81;\n\tmemcpy(sbuf + offs, in, in_len);\n\toffs += in_len;", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86);\n\tapdu.flags |= SC_APDU_FLAGS_CHAINING;\n\tapdu.data = sbuf;\n\tapdu.datalen = offs;\n\tapdu.lc = offs;\n\tapdu.resp = resp;\n\tapdu.resplen = sizeof(resp);\n\tapdu.le = 256;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"Card returned error\");", "\tif (out_len > apdu.resplen)\n\t\tout_len = apdu.resplen;", "\tmemcpy(out, apdu.resp, out_len);\n\trv = out_len;", "\tLOG_FUNC_RETURN(ctx, rv);\n}", "\nstatic int\niasecc_qsign_data_sha1(struct sc_context *ctx, const unsigned char *in, size_t in_len,\n\t\t\t\tstruct iasecc_qsign_data *out)\n{\n\tSHA_CTX sha;\n\tSHA_LONG pre_hash_Nl, *hh[5] = {\n\t\t&sha.h0, &sha.h1, &sha.h2, &sha.h3, &sha.h4\n\t};\n\tint jj, ii;\n\tint hh_size = sizeof(SHA_LONG), hh_num = SHA_DIGEST_LENGTH / sizeof(SHA_LONG);", "\tLOG_FUNC_CALLED(ctx);", "\tif (!in || !in_len || !out)\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);", "\tsc_log(ctx,\n\t \"sc_pkcs15_get_qsign_data() input data length %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t in_len);\n\tmemset(out, 0, sizeof(struct iasecc_qsign_data));", "\tSHA1_Init(&sha);\n\tSHA1_Update(&sha, in, in_len);", "\tfor (jj=0; jj<hh_num; jj++)\n\t\tfor(ii=0; ii<hh_size; ii++)\n\t\t\tout->pre_hash[jj*hh_size + ii] = ((*hh[jj] >> 8*(hh_size-1-ii)) & 0xFF);\n\tout->pre_hash_size = SHA_DIGEST_LENGTH;\n\tsc_log(ctx, \"Pre SHA1:%s\", sc_dump_hex(out->pre_hash, out->pre_hash_size));", "\tpre_hash_Nl = sha.Nl - (sha.Nl % (sizeof(sha.data) * 8));\n\tfor (ii=0; ii<hh_size; ii++) {\n\t\tout->counter[ii] = (sha.Nh >> 8*(hh_size-1-ii)) &0xFF;\n\t\tout->counter[hh_size+ii] = (pre_hash_Nl >> 8*(hh_size-1-ii)) &0xFF;\n\t}\n\tfor (ii=0, out->counter_long=0; ii<(int)sizeof(out->counter); ii++)\n\t\tout->counter_long = out->counter_long*0x100 + out->counter[ii];\n\tsc_log(ctx, \"Pre counter(%li):%s\", out->counter_long, sc_dump_hex(out->counter, sizeof(out->counter)));", "\tif (sha.num) {\n\t\tmemcpy(out->last_block, in + in_len - sha.num, sha.num);\n\t\tout->last_block_size = sha.num;\n\t\tsc_log(ctx, \"Last block(%\"SC_FORMAT_LEN_SIZE_T\"u):%s\",\n\t\t out->last_block_size,\n\t\t sc_dump_hex(out->last_block, out->last_block_size));\n\t}", "\tSHA1_Final(out->hash, &sha);\n\tout->hash_size = SHA_DIGEST_LENGTH;\n\tsc_log(ctx, \"Expected digest %s\\n\", sc_dump_hex(out->hash, out->hash_size));", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\n#if OPENSSL_VERSION_NUMBER >= 0x00908000L\nstatic int\niasecc_qsign_data_sha256(struct sc_context *ctx, const unsigned char *in, size_t in_len,\n\t\t\t\tstruct iasecc_qsign_data *out)\n{\n\tSHA256_CTX sha256;\n\tSHA_LONG pre_hash_Nl;\n\tint jj, ii;\n\tint hh_size = sizeof(SHA_LONG), hh_num = SHA256_DIGEST_LENGTH / sizeof(SHA_LONG);", "\tLOG_FUNC_CALLED(ctx);\n\tif (!in || !in_len || !out)\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);", "\tsc_log(ctx,\n\t \"sc_pkcs15_get_qsign_data() input data length %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t in_len);\n\tmemset(out, 0, sizeof(struct iasecc_qsign_data));", "\tSHA256_Init(&sha256);\n\tSHA256_Update(&sha256, in, in_len);", "\tfor (jj=0; jj<hh_num; jj++)\n\t\tfor(ii=0; ii<hh_size; ii++)\n\t\t\tout->pre_hash[jj*hh_size + ii] = ((sha256.h[jj] >> 8*(hh_size-1-ii)) & 0xFF);\n\tout->pre_hash_size = SHA256_DIGEST_LENGTH;\n\tsc_log(ctx, \"Pre hash:%s\", sc_dump_hex(out->pre_hash, out->pre_hash_size));", "\tpre_hash_Nl = sha256.Nl - (sha256.Nl % (sizeof(sha256.data) * 8));\n\tfor (ii=0; ii<hh_size; ii++) {\n\t\tout->counter[ii] = (sha256.Nh >> 8*(hh_size-1-ii)) &0xFF;\n\t\tout->counter[hh_size+ii] = (pre_hash_Nl >> 8*(hh_size-1-ii)) &0xFF;\n\t}\n\tfor (ii=0, out->counter_long=0; ii<(int)sizeof(out->counter); ii++)\n\t\tout->counter_long = out->counter_long*0x100 + out->counter[ii];\n\tsc_log(ctx, \"Pre counter(%li):%s\", out->counter_long, sc_dump_hex(out->counter, sizeof(out->counter)));", "\tif (sha256.num) {\n\t\tmemcpy(out->last_block, in + in_len - sha256.num, sha256.num);\n\t\tout->last_block_size = sha256.num;\n\t\tsc_log(ctx, \"Last block(%\"SC_FORMAT_LEN_SIZE_T\"u):%s\",\n\t\t out->last_block_size,\n\t\t sc_dump_hex(out->last_block, out->last_block_size));\n\t}", "\tSHA256_Final(out->hash, &sha256);\n\tout->hash_size = SHA256_DIGEST_LENGTH;\n\tsc_log(ctx, \"Expected digest %s\\n\", sc_dump_hex(out->hash, out->hash_size));", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}\n#endif", "\nstatic int\niasecc_compute_signature_dst(struct sc_card *card,\n\t\tconst unsigned char *in, size_t in_len, unsigned char *out, size_t out_len)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data;\n\tstruct sc_security_env *env = &prv->security_env;\n\tstruct iasecc_qsign_data qsign_data;\n\tstruct sc_apdu apdu;\n\tsize_t offs = 0, hash_len = 0;\n\tunsigned char sbuf[SC_MAX_APDU_BUFFER_SIZE];\n\tunsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE];\n\tint rv = SC_SUCCESS;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx,\n\t \"iasecc_compute_signature_dst() input length %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t in_len);\n\tif (env->operation != SC_SEC_OPERATION_SIGN)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"It's not SC_SEC_OPERATION_SIGN\");\n\telse if (!(prv->key_size & 0x1E0) || (prv->key_size & ~0x1E0))\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"Invalid key size for SC_SEC_OPERATION_SIGN\");", "\tmemset(&qsign_data, 0, sizeof(qsign_data));\n\tif (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA1) {\n\t\trv = iasecc_qsign_data_sha1(card->ctx, in, in_len, &qsign_data);\n\t}\n\telse if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA256) {\n#if OPENSSL_VERSION_NUMBER >= 0x00908000L\n\t\trv = iasecc_qsign_data_sha256(card->ctx, in, in_len, &qsign_data);\n#else\n\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"SHA256 is not supported by OpenSSL previous to v0.9.8\");\n#endif\n\t}\n\telse\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"Need RSA_HASH_SHA1 or RSA_HASH_SHA256 algorithm\");\n\tLOG_TEST_RET(ctx, rv, \"Cannot get QSign data\");", "\tsc_log(ctx,\n\t \"iasecc_compute_signature_dst() hash_len %\"SC_FORMAT_LEN_SIZE_T\"u; key_size %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t hash_len, prv->key_size);", "\tmemset(sbuf, 0, sizeof(sbuf));\n\tsbuf[offs++] = 0x90;\n\tif (qsign_data.counter_long) {\n\t\tsbuf[offs++] = qsign_data.hash_size + 8;\n\t\tmemcpy(sbuf + offs, qsign_data.pre_hash, qsign_data.pre_hash_size);\n\t\toffs += qsign_data.pre_hash_size;\n\t\tmemcpy(sbuf + offs, qsign_data.counter, sizeof(qsign_data.counter));\n\t\toffs += sizeof(qsign_data.counter);\n\t}\n\telse {\n\t\tsbuf[offs++] = 0;\n\t}", "\tsbuf[offs++] = 0x80;\n\tsbuf[offs++] = qsign_data.last_block_size;\n\tmemcpy(sbuf + offs, qsign_data.last_block, qsign_data.last_block_size);\n\toffs += qsign_data.last_block_size;", "\tsc_log(ctx,\n\t \"iasecc_compute_signature_dst() offs %\"SC_FORMAT_LEN_SIZE_T\"u; OP(meth:%X,ref:%X)\",\n\t offs, prv->op_method, prv->op_ref);\n\tif (prv->op_method == SC_AC_SCB && (prv->op_ref & IASECC_SCB_METHOD_SM))\n\t\tLOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, \"Not yet\");", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x2A, 0x90, 0xA0);\n\tapdu.data = sbuf;\n\tapdu.datalen = offs;\n\tapdu.lc = offs;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"Compute signature failed\");", "\tsc_log(ctx, \"iasecc_compute_signature_dst() partial hash OK\");", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0x2A, 0x9E, 0x9A);\n\tapdu.resp = rbuf;\n\tapdu.resplen = prv->key_size;\n\tapdu.le = prv->key_size;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"Compute signature failed\");", "\tsc_log(ctx,\n\t \"iasecc_compute_signature_dst() DST resplen %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t apdu.resplen);\n\tif (apdu.resplen > out_len)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, \"Result buffer too small for the DST signature\");", "\tmemcpy(out, apdu.resp, apdu.resplen);", "\tLOG_FUNC_RETURN(ctx, apdu.resplen);\n}", "\nstatic int\niasecc_compute_signature_at(struct sc_card *card,\n\t\tconst unsigned char *in, size_t in_len, unsigned char *out, size_t out_len)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data;\n\tstruct sc_security_env *env = &prv->security_env;\n\tstruct sc_apdu apdu;\n\tsize_t offs = 0, sz = 0;\n\tunsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE];\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tif (env->operation != SC_SEC_OPERATION_AUTHENTICATE)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, \"It's not SC_SEC_OPERATION_AUTHENTICATE\");", "\tsc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x88, 0x00, 0x00);\n\tapdu.datalen = in_len;\n\tapdu.data = in;\n\tapdu.lc = in_len;\n\tapdu.resp = rbuf;\n\tapdu.resplen = sizeof(rbuf);\n\tapdu.le = 0x100;", "\trv = sc_transmit_apdu(card, &apdu);\n\tLOG_TEST_RET(ctx, rv, \"APDU transmit failed\");\n\trv = sc_check_sw(card, apdu.sw1, apdu.sw2);\n\tLOG_TEST_RET(ctx, rv, \"Compute signature failed\");", "\tdo {\n\t\tif (offs + apdu.resplen > out_len)\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, \"Buffer too small to return signature\");", "\t\tmemcpy(out + offs, rbuf, apdu.resplen);\n\t\toffs += apdu.resplen;", "\t\tif (apdu.sw1 == 0x90 && apdu.sw2 == 0x00)\n\t\t\tbreak;", "\t\tif (apdu.sw1 == 0x61) {\n\t\t\tsz = apdu.sw2 == 0x00 ? 0x100 : apdu.sw2;\n\t\t\trv = iso_ops->get_response(card, &sz, rbuf);\n\t\t\tLOG_TEST_RET(ctx, rv, \"Get response error\");", "\t\t\tapdu.resplen = rv;\n\t\t}\n\t\telse {\n\t\t\tLOG_TEST_RET(ctx, SC_ERROR_INTERNAL, \"Impossible error: SW1 is not 0x90 neither 0x61\");\n\t\t}", "\t} while(rv > 0);", "\tLOG_FUNC_RETURN(ctx, offs);\n}", "\nstatic int\niasecc_compute_signature(struct sc_card *card,\n\t\tconst unsigned char *in, size_t in_len, unsigned char *out, size_t out_len)\n{\n\tstruct sc_context *ctx;\n\tstruct iasecc_private_data *prv;\n\tstruct sc_security_env *env;", "\tif (!card || !in || !out)\n\t\treturn SC_ERROR_INVALID_ARGUMENTS;", "\tctx = card->ctx;\n\tprv = (struct iasecc_private_data *) card->drv_data;\n\tenv = &prv->security_env;", "\tLOG_FUNC_CALLED(ctx);\n\tsc_log(ctx,\n\t \"inlen %\"SC_FORMAT_LEN_SIZE_T\"u, outlen %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t in_len, out_len);", "\tif (env->operation == SC_SEC_OPERATION_SIGN)\n\t\treturn iasecc_compute_signature_dst(card, in, in_len, out, out_len);\n\telse if (env->operation == SC_SEC_OPERATION_AUTHENTICATE)\n\t\treturn iasecc_compute_signature_at(card, in, in_len, out, out_len);", "\tLOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);\n}", "\nstatic int\niasecc_read_public_key(struct sc_card *card, unsigned type,\n\t\tstruct sc_path *key_path, unsigned ref, unsigned size,\n\t\tunsigned char **out, size_t *out_len)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_sdo sdo;\n\tstruct sc_pkcs15_bignum bn[2];\n\tstruct sc_pkcs15_pubkey_rsa rsa_key;\n\tint rv;", "\tLOG_FUNC_CALLED(ctx);\n\tif (type != SC_ALGORITHM_RSA)\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);", "\tsc_log(ctx, \"read public kay(ref:%i;size:%i)\", ref, size);", "\tmemset(&sdo, 0, sizeof(sdo));\n\tsdo.sdo_class = IASECC_SDO_CLASS_RSA_PUBLIC;\n\tsdo.sdo_ref = ref & ~IASECC_OBJECT_REF_LOCAL;", "\trv = iasecc_sdo_get_data(card, &sdo);\n\tLOG_TEST_RET(ctx, rv, \"failed to read public key: cannot get RSA SDO data\");", "\tif (out)\n\t\t*out = NULL;\n\tif (out_len)\n\t\t*out_len = 0;", "\tbn[0].data = (unsigned char *) malloc(sdo.data.pub_key.n.size);\n\tif (!bn[0].data)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, \"failed to read public key: cannot allocate modulus\");\n\tbn[0].len = sdo.data.pub_key.n.size;\n\tmemcpy(bn[0].data, sdo.data.pub_key.n.value, sdo.data.pub_key.n.size);", "\tbn[1].data = (unsigned char *) malloc(sdo.data.pub_key.e.size);\n\tif (!bn[1].data)\n\t\tLOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, \"failed to read public key: cannot allocate exponent\");\n\tbn[1].len = sdo.data.pub_key.e.size;\n\tmemcpy(bn[1].data, sdo.data.pub_key.e.value, sdo.data.pub_key.e.size);", "\trsa_key.modulus = bn[0];\n\trsa_key.exponent = bn[1];", "\trv = sc_pkcs15_encode_pubkey_rsa(ctx, &rsa_key, out, out_len);\n\tLOG_TEST_RET(ctx, rv, \"failed to read public key: cannot encode RSA public key\");", "\tif (out && out_len)\n\t\tsc_log(ctx, \"encoded public key: %s\", sc_dump_hex(*out, *out_len));", "\tif (bn[0].data)\n\t\tfree(bn[0].data);\n\tif (bn[1].data)\n\t\tfree(bn[1].data);", "\tiasecc_sdo_free_fields(card, &sdo);", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic int\niasecc_get_free_reference(struct sc_card *card, struct iasecc_ctl_get_free_reference *ctl_data)\n{\n\tstruct sc_context *ctx = card->ctx;\n\tstruct iasecc_sdo *sdo = NULL;\n\tint idx, rv;", "\tLOG_FUNC_CALLED(ctx);", "\tif ((ctl_data->key_size % 0x40) || ctl_data->index < 1 || (ctl_data->index > IASECC_OBJECT_REF_MAX))\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);", "\tsc_log(ctx, \"get reference for key(index:%i,usage:%X,access:%X)\", ctl_data->index, ctl_data->usage, ctl_data->access);\n\t/* TODO: when looking for the slot for the signature keys, check also PSO_SIGNATURE ACL */\n\tfor (idx = ctl_data->index; idx <= IASECC_OBJECT_REF_MAX; idx++) {\n\t\tunsigned char sdo_tag[3] = {\n\t\t\tIASECC_SDO_TAG_HEADER, IASECC_OBJECT_REF_LOCAL | IASECC_SDO_CLASS_RSA_PRIVATE, idx\n\t\t};\n\t\tsize_t sz;", "\t\tif (sdo)\n\t\t\tiasecc_sdo_free(card, sdo);", "\t\trv = iasecc_sdo_allocate_and_parse(card, sdo_tag, 3, &sdo);\n\t\tLOG_TEST_RET(ctx, rv, \"cannot parse SDO data\");", "\t\trv = iasecc_sdo_get_data(card, sdo);\n\t\tif (rv == SC_ERROR_DATA_OBJECT_NOT_FOUND) {\n\t\t\tiasecc_sdo_free(card, sdo);", "\t\t\tsc_log(ctx, \"found empty key slot %i\", idx);\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t\tLOG_TEST_RET(ctx, rv, \"get new key reference failed\");", "\t\tsz = *(sdo->docp.size.value + 0) * 0x100 + *(sdo->docp.size.value + 1);\n\t\tsc_log(ctx,\n\t\t \"SDO(idx:%i) size %\"SC_FORMAT_LEN_SIZE_T\"u; key_size %\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t\t idx, sz, ctl_data->key_size);", "\t\tif (sz != ctl_data->key_size / 8) {\n\t\t\tsc_log(ctx,\n\t\t\t \"key index %i ignored: different key sizes %\"SC_FORMAT_LEN_SIZE_T\"u/%\"SC_FORMAT_LEN_SIZE_T\"u\",\n\t\t\t idx, sz, ctl_data->key_size / 8);\n\t\t\tcontinue;\n\t\t}", "\t\tif (sdo->docp.non_repudiation.value) {\n\t\t\tsc_log(ctx, \"non repudiation flag %X\", sdo->docp.non_repudiation.value[0]);\n\t\t\tif ((ctl_data->usage & SC_PKCS15_PRKEY_USAGE_NONREPUDIATION) && !(*sdo->docp.non_repudiation.value)) {\n\t\t\t\tsc_log(ctx, \"key index %i ignored: need non repudiation\", idx);\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tif (!(ctl_data->usage & SC_PKCS15_PRKEY_USAGE_NONREPUDIATION) && *sdo->docp.non_repudiation.value) {\n\t\t\t\tsc_log(ctx, \"key index %i ignored: don't need non-repudiation\", idx);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}", "\t\tif (ctl_data->access & SC_PKCS15_PRKEY_ACCESS_LOCAL) {\n\t\t\tif (sdo->docp.scbs[IASECC_ACLS_RSAKEY_GENERATE] == IASECC_SCB_NEVER) {\n\t\t\t\tsc_log(ctx, \"key index %i ignored: GENERATE KEY not allowed\", idx);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (sdo->docp.scbs[IASECC_ACLS_RSAKEY_PUT_DATA] == IASECC_SCB_NEVER) {\n\t\t\t\tsc_log(ctx, \"key index %i ignored: PUT DATA not allowed\", idx);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}", "\t\tif ((ctl_data->usage & SC_PKCS15_PRKEY_USAGE_NONREPUDIATION) && (ctl_data->usage & SC_PKCS15_PRKEY_USAGE_SIGN)) {\n\t\t\tif (sdo->docp.scbs[IASECC_ACLS_RSAKEY_PSO_SIGN] == IASECC_SCB_NEVER) {\n\t\t\t\tsc_log(ctx, \"key index %i ignored: PSO SIGN not allowed\", idx);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\telse if (ctl_data->usage & SC_PKCS15_PRKEY_USAGE_SIGN) {\n\t\t\tif (sdo->docp.scbs[IASECC_ACLS_RSAKEY_INTERNAL_AUTH] == IASECC_SCB_NEVER) {\n\t\t\t\tsc_log(ctx, \"key index %i ignored: INTERNAL AUTHENTICATE not allowed\", idx);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}", "\t\tif (ctl_data->usage & (SC_PKCS15_PRKEY_USAGE_DECRYPT | SC_PKCS15_PRKEY_USAGE_UNWRAP)) {\n\t\t\tif (sdo->docp.scbs[IASECC_ACLS_RSAKEY_PSO_DECIPHER] == IASECC_SCB_NEVER) {\n\t\t\t\tsc_log(ctx, \"key index %i ignored: PSO DECIPHER not allowed\", idx);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}", "\t\tbreak;\n\t}", "\tctl_data->index = idx;", "\tif (idx > IASECC_OBJECT_REF_MAX)\n\t\tLOG_FUNC_RETURN(ctx, SC_ERROR_DATA_OBJECT_NOT_FOUND);", "\tLOG_FUNC_RETURN(ctx, SC_SUCCESS);\n}", "\nstatic struct sc_card_driver *\nsc_get_driver(void)\n{\n\tstruct sc_card_driver *iso_drv = sc_get_iso7816_driver();", "\tif (!iso_ops)\n\t\tiso_ops = iso_drv->ops;", "\tiasecc_ops = *iso_ops;", "\tiasecc_ops.match_card = iasecc_match_card;\n\tiasecc_ops.init = iasecc_init;\n\tiasecc_ops.finish = iasecc_finish;\n\tiasecc_ops.read_binary = iasecc_read_binary;\n\t/*\twrite_binary: ISO7816 implementation works\t*/\n\t/*\tupdate_binary: ISO7816 implementation works\t*/\n\tiasecc_ops.erase_binary = iasecc_erase_binary;\n\t/*\tresize_binary\t*/\n\t/* \tread_record: Untested\t*/\n\t/*\twrite_record: Untested\t*/\n\t/*\tappend_record: Untested\t*/\n\t/*\tupdate_record: Untested\t*/\n\tiasecc_ops.select_file = iasecc_select_file;\n\t/*\tget_response: Untested\t*/\n\t/*\tget_challenge: ISO7816 implementation works\t*/\n\tiasecc_ops.logout = iasecc_logout;\n\t/*\trestore_security_env\t*/\n\tiasecc_ops.set_security_env = iasecc_set_security_env;\n\tiasecc_ops.decipher = iasecc_decipher;\n\tiasecc_ops.compute_signature = iasecc_compute_signature;\n\tiasecc_ops.create_file = iasecc_create_file;\n\tiasecc_ops.delete_file = iasecc_delete_file;\n\t/*\tlist_files\t*/\n\tiasecc_ops.check_sw = iasecc_check_sw;\n\tiasecc_ops.card_ctl = iasecc_card_ctl;\n\tiasecc_ops.process_fci = iasecc_process_fci;\n\t/*\tconstruct_fci: Not needed\t*/\n\tiasecc_ops.pin_cmd = iasecc_pin_cmd;\n\t/*\tget_data: Not implemented\t*/\n\t/*\tput_data: Not implemented\t*/\n\t/*\tdelete_record: Not implemented\t*/", "\tiasecc_ops.read_public_key = iasecc_read_public_key;", "\treturn &iasecc_drv;\n}", "struct sc_card_driver *\nsc_get_iasecc_driver(void)\n{\n\treturn sc_get_driver();\n}", "#else", "/* we need to define the functions below to export them */\n#include \"errors.h\"", "int\niasecc_se_get_info()\n{\n\treturn SC_ERROR_NOT_SUPPORTED;\n}", "#endif /* ENABLE_OPENSSL */" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [840], "buggy_code_start_loc": [830], "filenames": ["src/libopensc/card-iasecc.c"], "fixing_code_end_loc": [840], "fixing_code_start_loc": [830], "message": "Endless recursion when handling responses from an IAS-ECC card in iasecc_select_file in libopensc/card-iasecc.c in OpenSC before 0.19.0-rc1 could be used by attackers able to supply crafted smartcards to hang or crash the opensc library using programs.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:opensc_project:opensc:*:*:*:*:*:*:*:*", "matchCriteriaId": "85C3EC93-1A01-4E7D-9730-F8429C1CD145", "versionEndExcluding": null, "versionEndIncluding": "0.18.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Endless recursion when handling responses from an IAS-ECC card in iasecc_select_file in libopensc/card-iasecc.c in OpenSC before 0.19.0-rc1 could be used by attackers able to supply crafted smartcards to hang or crash the opensc library using programs."}, {"lang": "es", "value": "Una recursi\u00f3n infinita al manejar las respuestas de una tarjeta IAS-ECC en iasecc_select_file en libopensc/card-iasecc.c en OpenSC en versiones anteriores a la 0.19.0-rc1 podr\u00eda ser empleada por atacantes para proporcionar smartcards manipuladas para provocar el bloqueo o el cierre inesperado de la librer\u00eda opensc mediante programas."}], "evaluatorComment": null, "id": "CVE-2018-16426", "lastModified": "2019-10-03T00:03:26.223", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 2.1, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "PHYSICAL", "availabilityImpact": "HIGH", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:P/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 0.7, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-09-04T00:29:01.293", "references": [{"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2019:2154"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/OpenSC/OpenSC/commit/03628449b75a93787eb2359412a3980365dda49b#diff-f8c0128e14031ed9307d47f10f601b54"}, {"source": "cve@mitre.org", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/OpenSC/OpenSC/releases/tag/0.19.0-rc1"}, {"source": "cve@mitre.org", "tags": null, "url": "https://lists.debian.org/debian-lts-announce/2019/09/msg00009.html"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://www.x41-dsec.de/lab/advisories/x41-2018-002-OpenSC/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-674"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/OpenSC/OpenSC/commit/03628449b75a93787eb2359412a3980365dda49b#diff-f8c0128e14031ed9307d47f10f601b54"}, "type": "CWE-674"}
198
Determine whether the {function_name} code is vulnerable or not.
[ "#!/usr/bin/python", "import os\nimport re\nimport sys\nimport glob\nimport requests\nimport argparse\nfrom time import sleep\nfrom json import loads", "try:\n from urllib.parse import urlencode\nexcept ImportError: # pragma: no cover\n from urllib import urlencode", "try:\n from shlex import quote\nexcept ImportError: # pragma: no cover\n from pipes import quote", "import subprocess", "# https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning\nimport logging\nlogging.captureWarnings(True)", "\nversion = VERSION = __version__ = '2.0.15'", "COLOR = True", "is_merge_commit = re.compile(r'^Merge\\s\\w{40}\\sinto\\s\\w{40}$')", "remove_token = re.compile(r'token=[^\\&]+').sub", "", "\nignored_path = re.compile(r'(/vendor)|'\n r'(/js/generated/coverage)|'\n r'(/__pycache__)|'\n r'(/coverage/instrumented)|'\n r'(/build/lib)|'\n r'(/htmlcov)|'\n r'(/node_modules)|'\n r'(/\\.yarn-cache)|'\n r'(\\.egg-info)|'\n r'(/\\.git)|'\n r'(/\\.hg)|'\n r'(/\\.tox)|'\n r'(/\\.?v?(irtual)?envs?)', re.I).search", "ignored_report = re.compile('.*('\n r'(/\\.coverage.*)|'\n r'(\\.coveragerc)|'\n r'(\\.egg)|'\n r'(\\.gif)|'\n r'(\\.ini)|'\n r'(\\.less)|'\n r'(\\.jpeg)|'\n r'(\\.jpg)|'\n r'(\\.md)|'\n r'(\\.png)|'\n r'(\\.p?sql)|'\n r'(\\.whl)|'\n r'(\\.cpp)|'\n r'(\\.pyc?)|'\n r'(\\.cfg)|'\n r'(\\.class)|'\n r'(\\.js)|'\n r'(\\.html)|'\n r'(\\.sh)|'\n r'(\\.tar\\.gz)|'\n r'(\\.yml)|'\n r'(\\.xcconfig)|'\n r'(\\.data)|'\n r'(coverage\\.db)|'\n r'(\\.?codecov\\.yml)|'\n r'(coverage\\.jade)|'\n r'(include\\.lst)|'\n r'(inputFiles\\.lst)|'\n r'(createdFiles\\.lst)|'\n r'(scoverage\\.measurements\\..*)|'\n r'(test_.*_coverage\\.txt)|'\n r'(conftest_.*\\.c\\.gcov)'\n ')$', re.I).match", "is_report = re.compile('.*('\n r'([^/]*coverage[^/]*)|'\n r'(\\.gcov)|'\n r'(\\.lcov)|'\n r'(\\.lst)|'\n r'(clover\\.xml)|'\n r'(cobertura\\.xml)|'\n r'(coverage-final\\.json)|'\n r'(coverage-summary\\.json)|'\n r'(gcov\\.info)|'\n r'(([^/]*\\.)?codecov\\.[^/]*)|'\n r'(jacoco[^/]*\\.xml)|'\n r'(lcov\\.info)|'\n r'(luacov\\.report\\.out)|'\n r'(nosetests\\.xml)|'\n r'(report\\.xml)'\n ')$', re.I).match", "opj = os.path.join # for faster access", "\ndef write(text, color=None):\n global COLOR\n if COLOR:\n text = text.replace('==>', '\\033[90m==>\\033[0m')\n text = text.replace(' +', ' \\033[32m+\\033[0m')\n text = text.replace('XX>', '\\033[31mXX>\\033[0m')\n if text[:6] == 'Error:':\n text = '\\033[41mError:\\033[0m\\033[91m%s\\033[0m' % text[6:]\n elif text[:4] == 'Tip:':\n text = '\\033[42mTip:\\033[0m\\033[32m%s\\033[0m' % text[4:]\n elif text.strip()[:4] == 'http':\n text = '\\033[92m%s\\033[0m' % text\n elif text[:7] == 'Codecov':\n text = \"\"\"\n _____ _\n / ____| | |\n | | ___ __| | ___ ___ _____ __\n | | / _ \\ / _ |/ _ \\/ __/ _ \\ \\ / /\n | |___| (_) | (_| | __/ (_| (_) \\ V /\n \\_____\\___/ \\____|\\___|\\___\\___/ \\_/\n %s\\n\"\"\" % text.split(' ')[1]\n elif color == 'red':\n text = '\\033[91m%s\\033[0m' % text\n elif color == 'green':\n text = '\\033[92m%s\\033[0m' % text", " sys.stdout.write(text + '\\n')", "\ndef fopen(path):\n try:\n if sys.version_info < (3, 0):\n with open(path, 'r') as f:\n return f.read()\n else:\n try:\n with open(path, 'r', encoding='utf-8') as f:\n return f.read()\n except UnicodeDecodeError:\n with open(path, 'r', encoding='ISO-8859-1') as f:\n return f.read()\n except Exception as e:\n # on none of that works. just print the issue and continue\n write(' - Ignored: ' + str(e))", "\ndef read(filepath):\n try:\n report = fopen(filepath)\n if report is None:\n return\n write(' + %s bytes=%d' % (filepath, os.path.getsize(filepath)))\n return '# path=' + filepath + '\\n' + report\n except Exception as e:\n # Ex: No such file or directory, skip them\n write(' - Ignored: ' + str(e))", "\ndef check_output(cmd, **popen_args):\n from subprocess import Popen, PIPE, CalledProcessError\n process = Popen(cmd, stdout=PIPE, **popen_args)\n output, _ = process.communicate()\n if process.returncode:\n raise CalledProcessError(process.returncode, cmd)\n else:\n assert process.returncode == 0\n return output.decode('utf-8')", "\ndef try_to_run(cmd, shell=True):\n try:\n return check_output(cmd, shell=shell)\n except subprocess.CalledProcessError as e:\n write(' Error running `%s`: %s' % (cmd, e.output or str(e)))", "def run_python_coverage(args):\n \"\"\"Run the Python coverage tool\n \n If it's importable in this Python, launch it using 'python -m'.\n Otherwise, look it up on PATH like any other command.\n \"\"\"\n try:\n import coverage\n except ImportError:\n # Coverage is not installed on this Python. Hope it's on PATH.\n try_to_run(['coverage'] + args, shell=False)\n else:\n # Coverage is installed on this Python. Run it as a module.\n try_to_run([sys.executable, '-m', 'coverage'] + args, shell=False)", "def remove_non_ascii(data):\n try:\n return data.decode('utf8') + ''\n except:\n return ''.join([i if ord(i) < 128 else '' for i in data])", "\ndef _add_env_if_not_empty(lst, value):\n if os.getenv(value) is not None:\n lst.add(value)", "\ndef main(*argv, **kwargs):\n root = os.getcwd()", " # Build Parser\n # ------------\n parser = argparse.ArgumentParser(prog='codecov', add_help=True,\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"Upload reports to Codecov\"\"\")\n basics = parser.add_argument_group('======================== Basics ========================')\n basics.add_argument('--version', action='version', version='Codecov py-v'+version+\" - https://codecov.io/\")\n basics.add_argument('--token', '-t', default=os.getenv(\"CODECOV_TOKEN\"), help=\"Private repository token or @filename for file containing the token. Defaults to $CODECOV_TOKEN. Not required for public repositories on Travis CI, CircleCI and AppVeyor\")\n basics.add_argument('--file', '-f', nargs=\"*\", default=None, help=\"Target a specific file for uploading\")\n basics.add_argument('--flags', '-F', nargs=\"*\", default=None, help=\"Flag these uploaded files with custom labels\")\n basics.add_argument('--env', '-e', nargs=\"*\", default=None, help=\"Store environment variables to help distinguish CI builds.\")\n basics.add_argument('--required', action=\"store_true\", default=False, help=\"If Codecov fails it will exit 1 - possibly failing the CI build.\")\n basics.add_argument('--name', '-n', default=None, help=\"Custom defined name of the upload. Visible in Codecov UI.\")", " gcov = parser.add_argument_group('======================== gcov ========================')\n gcov.add_argument('--gcov-root', default=None, help=\"Project root directory when preparing gcov\")\n gcov.add_argument('--gcov-glob', nargs=\"*\", default=[], help=\"Paths to ignore during gcov gathering\")\n gcov.add_argument('--gcov-exec', default='gcov', help=\"gcov executable to run. Defaults to 'gcov'\")\n gcov.add_argument('--gcov-args', default='', help=\"extra arguments to pass to gcov\")", " advanced = parser.add_argument_group('======================== Advanced ========================')\n advanced.add_argument('-X', '--disable', nargs=\"*\", default=[], help=\"Disable features. Accepting **search** to disable crawling through directories, **detect** to disable detecting CI provider, **gcov** disable gcov commands, `pycov` disables running python `coverage xml`, **fix** to disable report adjustments https://docs.codecov.io/docs/fixing-reports\")\n advanced.add_argument('--root', default=None, help=\"Project directory. Default: current direcory or provided in CI environment variables\")\n advanced.add_argument('--commit', '-c', default=None, help=\"Commit SHA, set automatically\")\n advanced.add_argument('--prefix', '-P', default=None, help=\"Prefix network paths to help resolve paths: https://github.com/codecov/support/issues/472\")\n advanced.add_argument('--branch', '-b', default=None, help=\"Branch name\")\n advanced.add_argument('--build', default=None, help=\"Specify a custom build number to distinguish CI jobs, provided automatically for supported CI companies\")\n advanced.add_argument('--pr', default=None, help=\"Specify a custom pr number, provided automatically for supported CI companies\")\n advanced.add_argument('--tag', default=None, help=\"Git tag\")", " enterprise = parser.add_argument_group('======================== Enterprise ========================')\n enterprise.add_argument('--slug', '-r', default=os.getenv(\"CODECOV_SLUG\"), help=\"Specify repository slug for Enterprise ex. owner/repo\")\n enterprise.add_argument('--url', '-u', default=os.getenv(\"CODECOV_URL\", \"https://codecov.io\"), help=\"Your Codecov endpoint\")\n enterprise.add_argument('--cacert', default=os.getenv(\"CODECOV_CACERT\", os.getenv(\"CURL_CA_BUNDLE\")), help=\"Certificate pem bundle used to verify with your Codecov instance\")", " debugging = parser.add_argument_group('======================== Debugging ========================')\n debugging.add_argument('--dump', action=\"store_true\", help=\"Dump collected data and do not send to Codecov\")\n debugging.add_argument('-v', '--verbose', action=\"store_true\", help=\"Be verbose, e.g. dump the collected data\")\n debugging.add_argument('--no-color', action=\"store_true\", help=\"Do not output with color\")", " # Parse Arguments\n # ---------------\n if argv:\n codecov = parser.parse_args(argv)\n else:\n codecov = parser.parse_args()", " global COLOR\n COLOR = not codecov.no_color", " include_env = set()", " # add from cli\n if codecov.env:\n # -e VAR1,VAR2 or -e VAR1 -e VAR2\n for env in codecov.env:\n for e in env.split(','):\n include_env.add(e.strip())", " # add from env\n if os.getenv(\"CODECOV_ENV\"):\n for env in os.getenv(\"CODECOV_ENV\").split(','):\n include_env.add(env.strip())", " write('Codecov v'+version)\n query = dict(commit='', branch='', job='', pr='', build_url='',\n token=codecov.token)\n language = None", " if os.getenv('TOXENV'):\n _add_env_if_not_empty(include_env, 'TOXENV')", " # Detect CI\n # ---------\n if 'detect' in codecov.disable:\n write('XX> Detecting CI provider disabled.')", " else:\n write('==> Detecting CI provider')\n # -------\n # Jenkins\n # -------\n if os.getenv('JENKINS_URL'):\n # https://wiki.jenkins-ci.org/display/JENKINS/Building+a+software+project\n # https://wiki.jenkins-ci.org/display/JENKINS/GitHub+pull+request+builder+plugin#GitHubpullrequestbuilderplugin-EnvironmentVariables\n query.update(dict(branch=os.getenv('ghprbSourceBranch') or os.getenv('GIT_BRANCH') or os.getenv('BRANCH_NAME'),\n service='jenkins',\n commit=os.getenv('ghprbActualCommit') or os.getenv('GIT_COMMIT'),\n pr=os.getenv('ghprbPullId') or os.getenv('CHANGE_ID'),\n build=os.getenv('BUILD_NUMBER'),\n build_url=os.getenv('BUILD_URL')))\n root = os.getenv('WORKSPACE') or root\n write(' Jenkins Detected')", " # ---------\n # Travis CI\n # ---------\n elif os.getenv('CI') == 'true' and os.getenv('TRAVIS') == \"true\" and os.getenv('SHIPPABLE') != 'true':\n # http://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables\n query.update(dict(branch=os.getenv('TRAVIS_BRANCH'),\n service='travis',\n build=os.getenv('TRAVIS_JOB_NUMBER'),\n pr=os.getenv('TRAVIS_PULL_REQUEST'),\n job=os.getenv('TRAVIS_JOB_ID'),\n tag=os.getenv('TRAVIS_TAG'),\n slug=os.getenv('TRAVIS_REPO_SLUG'),\n commit=os.getenv('TRAVIS_COMMIT')))\n root = os.getenv('TRAVIS_BUILD_DIR') or root\n write(' Travis Detected')\n language = (list(filter(lambda l: os.getenv('TRAVIS_%s_VERSION' % l.upper()),\n ('dart', 'go', 'haxe', 'jdk', 'julia', 'node', 'otp', 'xcode',\n 'perl', 'php', 'python', 'r', 'ruby', 'rust', 'scala'))) + [''])[0]", " _add_env_if_not_empty(include_env, 'TRAVIS_OS_NAME')\n if language:\n _add_env_if_not_empty(include_env, 'TRAVIS_%s_VERSION' % language.upper())", " # --------\n # Codeship\n # --------\n elif os.getenv('CI') == 'true' and os.getenv('CI_NAME') == 'codeship':\n # https://www.codeship.io/documentation/continuous-integration/set-environment-variables/\n query.update(dict(branch=os.getenv('CI_BRANCH'),\n service='codeship',\n build=os.getenv('CI_BUILD_NUMBER'),\n build_url=os.getenv('CI_BUILD_URL'),\n commit=os.getenv('CI_COMMIT_ID')))\n write(' Codeship Detected')", " # ---------\n # Buildkite\n # ---------\n elif os.getenv('CI') == 'true' and os.getenv('BUILDKITE') == 'true':\n # https://buildkite.com/docs/guides/environment-variables\n query.update(dict(branch=os.getenv('BUILDKITE_BRANCH'),\n service='buildkite',\n build=os.getenv('BUILDKITE_BUILD_NUMBER') + '.' + os.getenv('BUILDKITE_JOB_ID'),\n slug=os.getenv('BUILDKITE_PROJECT_SLUG'),\n build_url=os.getenv('BUILDKITE_BUILD_URL'),\n commit=os.getenv('BUILDKITE_COMMIT')))\n write(' Buildkite Detected')", " # ---------\n # Circle CI\n # ---------\n elif os.getenv('CI') == 'true' and os.getenv('CIRCLECI') == 'true':\n # https://circleci.com/docs/environment-variables\n query.update(dict(branch=os.getenv('CIRCLE_BRANCH'),\n service='circleci',\n build=os.getenv('CIRCLE_BUILD_NUM') + \".\" + os.getenv('CIRCLE_NODE_INDEX'),\n job=os.getenv('CIRCLE_BUILD_NUM') + \".\" + os.getenv('CIRCLE_NODE_INDEX'),\n pr=os.getenv('CIRCLE_PR_NUMBER'),\n slug=os.getenv('CIRCLE_PROJECT_USERNAME') + \"/\" + os.getenv('CIRCLE_PROJECT_REPONAME'),\n commit=os.getenv('CIRCLE_SHA1')))\n write(' Circle CI Detected')", " # ---------\n # Semaphore\n # ---------\n elif os.getenv('CI') == 'true' and os.getenv('SEMAPHORE') == 'true':\n # https://semaphoreapp.com/docs/available-environment-variables.html\n query.update(dict(branch=os.getenv('BRANCH_NAME'),\n service='semaphore',\n build=os.getenv('SEMAPHORE_BUILD_NUMBER') + '.' + os.getenv('SEMAPHORE_CURRENT_THREAD'),\n slug=os.getenv('SEMAPHORE_REPO_SLUG'),\n commit=os.getenv('REVISION')))\n write(' Semaphore Detected')", " # ----------\n # Greenhouse\n # ----------\n elif os.getenv('GREENHOUSE') == 'true':\n # http://docs.greenhouseci.com/docs/environment-variables-files\n query.update(dict(branch=os.getenv('GREENHOUSE_BRANCH'),\n service='greenhouse',\n build=os.getenv('GREENHOUSE_BUILD_NUMBER'),\n build_url=os.getenv('GREENHOUSE_BUILD_URL'),\n pr=os.getenv('GREENHOUSE_PULL_REQUEST'),\n commit=os.getenv('GREENHOUSE_COMMIT')))\n write(' Greenhouse Detected')", " # --------\n # drone.io\n # --------\n elif os.getenv('CI') == \"drone\" and os.getenv('DRONE') == \"true\":\n # http://docs.drone.io/env.html\n query.update(dict(branch=os.getenv('DRONE_BRANCH'),\n service='drone.io',\n build=os.getenv('DRONE_BUILD_NUMBER'),\n build_url=os.getenv('DRONE_BUILD_LINK')))\n root = os.getenv('DRONE_BUILD_DIR') or root\n write(' Drone Detected')", " # --------\n # TeamCity\n # --------\n elif os.getenv('TEAMCITY_VERSION'):\n # https://confluence.jetbrains.com/plugins/servlet/mobile#content/view/74847298\n query.update(dict(service='teamcity',\n build=os.getenv('BUILD_NUMBER'),\n commit=os.getenv('BUILD_VCS_NUMBER')))\n write(' TeamCity CI Detected')", " # --------\n # AppVeyor\n # --------\n elif os.getenv('CI', 'false').lower() == 'true' and os.getenv('APPVEYOR', 'false').lower() == 'true':\n # http://www.appveyor.com/docs/environment-variables\n query.update(dict(branch=os.getenv('APPVEYOR_REPO_BRANCH'),\n service=\"appveyor\",\n job='/'.join((os.getenv('APPVEYOR_ACCOUNT_NAME'), os.getenv('APPVEYOR_PROJECT_SLUG'), os.getenv('APPVEYOR_BUILD_VERSION'))),\n build=os.getenv('APPVEYOR_JOB_ID'),\n pr=os.getenv('APPVEYOR_PULL_REQUEST_NUMBER'),\n slug=os.getenv('APPVEYOR_REPO_NAME'),\n commit=os.getenv('APPVEYOR_REPO_COMMIT')))\n write(' AppVeyor Detected')\n codecov.disable.append('search')", " # -------\n # Wercker\n # -------\n elif os.getenv('CI') == \"true\" and os.getenv('WERCKER_GIT_BRANCH'):\n # http://devcenter.wercker.com/articles/steps/variables.html\n query.update(dict(branch=os.getenv('WERCKER_GIT_BRANCH'),\n service=\"wercker\",\n build=os.getenv('WERCKER_MAIN_PIPELINE_STARTED'),\n slug=os.getenv('WERCKER_GIT_OWNER') + '/' + os.getenv('WERCKER_GIT_REPOSITORY'),\n commit=os.getenv('WERCKER_GIT_COMMIT')))\n write(' Wercker Detected')", " # ------\n # Magnum\n # ------\n elif os.getenv('CI') == \"true\" and os.getenv('MAGNUM') == 'true':\n # https://magnum-ci.com/docs/environment\n query.update(dict(service=\"magnum\",\n branch=os.getenv('CI_BRANCH'),\n build=os.getenv('CI_BUILD_NUMBER'),\n commit=os.getenv('CI_COMMIT')))\n write(' Magnum Detected')", " # ---------\n # Shippable\n # ---------\n elif os.getenv('SHIPPABLE') == \"true\":\n # http://docs.shippable.com/en/latest/config.html#common-environment-variables\n query.update(dict(branch=os.getenv('BRANCH'),\n service='shippable',\n build=os.getenv('BUILD_NUMBER'),\n build_url=os.getenv('BUILD_URL'),\n pr=os.getenv('PULL_REQUEST'),\n slug=os.getenv('REPO_NAME'),\n commit=os.getenv('COMMIT')))\n write(' Shippable Detected')", " # ---------\n # Gitlab CI\n # ---------\n elif os.getenv('CI_SERVER_NAME', '').startswith(\"GitLab\"):\n # http://doc.gitlab.com/ci/examples/README.html#environmental-variables\n # https://gitlab.com/gitlab-org/gitlab-ci-runner/blob/master/lib/build.rb#L96\n query.update(dict(service='gitlab',\n branch=os.getenv('CI_BUILD_REF_NAME'),\n build=os.getenv('CI_BUILD_ID'),\n commit=os.getenv('CI_BUILD_REF')))\n if os.getenv('CI_PROJECT_DIR', '').startswith('/'):\n root = os.getenv('CI_PROJECT_DIR')\n else:\n root = os.getenv('HOME') + '/' + os.getenv('CI_PROJECT_DIR', '')", " if os.getenv('CI_BUILD_REPO'):\n query['slug'] = os.getenv('CI_BUILD_REPO').split('/', 3)[-1].replace('.git', '')\n elif os.getenv('CI_REPOSITORY_URL'):\n query['slug'] = os.getenv('CI_REPOSITORY_URL').split('/', 3)[-1].replace('.git', '')", " write(' Gitlab CI Detected')", " else:\n query.update(dict(commit=os.getenv('VCS_COMMIT_ID', ''),\n branch=os.getenv('VCS_BRANCH_NAME', ''),\n pr=os.getenv('VCS_PULL_REQUEST', ''),\n slug=os.getenv('VCS_SLUG', ''),\n build_url=os.getenv('CI_BUILD_URL', ''),\n build=os.getenv('CI_BUILD_ID', '')))", " # ------\n # git/hg\n # ------\n if not query.get('branch'):\n try:\n # find branch, commit, repo from git command\n branch = try_to_run('git rev-parse --abbrev-ref HEAD || hg branch')\n query['branch'] = branch if branch != 'HEAD' else ''\n write(' -> Got branch from git/hg')", " except:\n write(' x> Failed to get branch from git/hg')", " if not query.get('commit'):\n try:\n query['commit'] = try_to_run(\"git rev-parse HEAD || hg id -i --debug | tr -d '+'\")\n write(' -> Got sha from git/hg')", " except: # pragma: no cover\n write(' x> Failed to get sha from git/hg')", " # Update Query\n # ------------\n if codecov.name:\n query['name'] = codecov.name", " if codecov.flags:\n query['flags'] = ','.join(codecov.flags)", " if codecov.build:\n query['build'] = codecov.build", " if codecov.pr:\n query['pr'] = codecov.pr", " if codecov.commit:\n query['commit'] = codecov.commit", " elif query['pr'] and query['pr'] != 'false':\n # Merge Commits\n # -------------\n res = try_to_run('git log -1 --pretty=%B')\n if res and is_merge_commit.match(res.strip()):\n query['commit'] = res.split(' ')[1]\n write(' Fixing merge commit SHA')", " if codecov.slug:\n query['slug'] = codecov.slug", " if codecov.branch:\n query['branch'] = codecov.branch", " if codecov.tag:\n query['tag'] = codecov.tag", " if codecov.root:\n root = codecov.root", " root = quote(root)", " # Upload\n # ------\n try:\n write('==> Preparing upload')", " # Read token from file\n # --------------------\n if query.get('token') and query.get('token')[0] == '@':\n write(' Reading token from file')\n query['token'] = fopen(opj(os.getcwd(), query['token'][1:])).strip()", " assert query.get('commit') not in ('', None), \"Commit sha is missing. Please specify via --commit=:sha\"", " # Build TOC\n # ---------\n toc = str((try_to_run('cd %s && git ls-files' % root) or\n try_to_run('git ls-files') or\n try_to_run('cd %s && hg locate' % root) or\n try_to_run('hg locate') or '').strip())", " if codecov.prefix:\n prefix = codecov.prefix.strip('/')\n toc = '{}/{}'.format(\n prefix,\n toc.replace('\\n', '\\n{}/'.format(prefix))\n )", " # Detect codecov.yml location\n yaml_location = re.search(\n r'\\.?codecov\\.ya?ml$',\n toc,\n re.M\n )\n if yaml_location:\n yaml_location = yaml_location.group()\n yaml_path = opj(root, yaml_location)\n if os.path.exists(yaml_path):\n query['yaml'] = yaml_location\n yaml = fopen(yaml_path)\n _token = re.search(\n r'token: (\\'|\\\")?([0-9a-f]{8}(-?[0-9a-f]{4}){3}-?[0-9a-f]{12})',\n yaml,\n re.M\n )\n if _token:\n query['token'] = _token.groups()[1]", " _slug = re.search(\n r'slug: (\\'|\\\")?([\\w\\-\\.\\+]+\\/[\\w\\-\\.\\+]+)',\n yaml,\n re.M\n )\n if _slug:\n query['slug'] = _slug.groups()[1]", " assert query.get('job') or query.get('token'), \"Missing repository upload token\"", " # Processing gcov\n # ---------------\n if 'gcov' in codecov.disable:\n write('XX> Skip processing gcov')", " else:\n dont_search_here = (\n \"-not -path './bower_components/**' \"\n \"-not -path './node_modules/**' \"\n \"-not -path './vendor/**'\"\n )\n write('==> Processing gcov (disable by -X gcov)')\n cmd = \"find %s %s -type f -name '*.gcno' %s -exec %s -pb %s {} +\" % (", " (codecov.gcov_root or root),", " dont_search_here,\n \" \".join(map(lambda a: \"-not -path '%s'\" % a, codecov.gcov_glob)),", " (codecov.gcov_exec or ''),\n (codecov.gcov_args or ''))", " write(' Executing gcov (%s)' % cmd)\n try_to_run(cmd)", " # Collect Reports\n # ---------------\n write('==> Collecting reports')\n reports = []", " if 'search' in codecov.disable:\n write('XX> Searching for reports disabled')\n else:", " # Detect .bowerrc\n # ---------------\n bower_components = '/bower_components'\n bowerrc = opj(root, '.bowerrc')\n if os.path.exists(bowerrc):\n write(' Detecting .bowerrc file')\n try:\n bower_components = '/' + (loads(fopen(bowerrc)).get('directory') or 'bower_components').replace('./', '').strip('/')\n write(' .bowerrc detected, ignoring ' + bower_components)\n except Exception as e:\n write(' .bowerrc parsing error: ' + str(e))", " # Find reports\n # ------------\n for _root, dirs, files in os.walk(root):\n # need to replace('\\\\', '/') for Windows\n if not ignored_path(_root.replace('\\\\', '/')) and bower_components not in _root.replace('\\\\', '/'):\n # add data to tboc\n for filepath in files:\n fullpath = opj(_root, filepath)\n if not codecov.file and is_report(fullpath.replace('\\\\', '/')) and not ignored_report(fullpath.replace('\\\\', '/')):\n # found report\n reports.append(read(fullpath))", " # Read Reports\n # ------------\n if codecov.file:\n write(' Targeting specific files')\n reports.extend(filter(bool, map(read, codecov.file)))", " elif 'pycov' not in codecov.disable:\n # Call `coverage xml` when .coverage exists\n # -----------------------------------------\n # Ran from current directory\n if glob.glob(opj(os.getcwd(), '.coverage.*')):\n write(' Merging coverage reports')\n # The `-a` option is mandatory here. If we\n # have a `.coverage` in the current directory, calling\n # without the option would delete the previous data\n run_python_coverage(['combine', '-a'])", " if os.path.exists(opj(os.getcwd(), '.coverage')) and not os.path.exists(opj(os.getcwd(), 'coverage.xml')):\n write(' Generating coverage xml reports for Python')\n # using `-i` to ignore \"No source for code\" error\n run_python_coverage(['xml', '-i'])\n reports.append(read(opj(os.getcwd(), 'coverage.xml')))", " reports = list(filter(bool, reports))\n assert len(reports) > 0, \"No coverage report found\"", " # Storing Environment\n # -------------------\n env = ''\n if include_env:\n write('==> Appending environment variables')\n for k in include_env:\n if k:\n write(' + ' + k)", " env = '\\n'.join([\"%s=%s\" % (k, os.getenv(k, '')) for k in include_env if k]) + '\\n<<<<<< ENV'", " # join reports together\n reports = '\\n'.join((env, (toc or ''), '<<<<<< network',\n '\\n<<<<<< EOF\\n'.join(reports),\n '<<<<<< EOF'))", " query['package'] = \"py\" + VERSION\n urlargs = (urlencode(dict([(k, v.strip()) for k, v in query.items() if v not in ('', None)]))).replace(\"+\", \"%20\")", " result = ''\n if codecov.dump:\n write('-------------------- Debug --------------------')\n write(' .url ' + codecov.url)\n write(' .query ' + remove_token('token=<secret>', urlargs))\n write(reports)\n write('-------------------- EOF --------------------')\n else:\n write('==> Uploading')\n write(' .url ' + codecov.url)\n write(' .query ' + remove_token('token=<secret>', urlargs))\n if codecov.verbose:\n write('-------------------- Reports --------------------')\n write(reports)\n write('-------------------------------------------------')", " s3 = None\n trys = 0\n while trys < 3:\n trys += 1\n if 's3' not in codecov.disable:\n try:\n write(' Pinging Codecov...')\n res = requests.post('%s/upload/v4?%s' % (codecov.url, urlargs),\n verify=codecov.cacert,\n headers={'Accept': 'text/plain',\n 'X-Reduced-Redundancy': 'false'})\n if res.status_code in (400, 406):\n raise Exception(res.text)", " elif res.status_code < 500:\n assert res.status_code == 200\n res = res.text.strip().split()\n result, upload_url = res[0], res[1]", " # Handle reports encoding for Python 2 and 3\n if not isinstance(reports, bytes):\n reports = reports.encode('utf-8')", " write(' Uploading to S3...')\n s3 = requests.put(upload_url, data=reports,\n headers={'Content-Type': 'text/plain',\n 'x-amz-acl': 'public-read'})\n s3.raise_for_status()\n assert s3.status_code == 200\n write(' ' + result)\n break\n else:\n # try again\n continue", " except AssertionError:\n write(' Direct to s3 failed. Using backup v2 endpoint.')", " write(' Uploading to Codecov...')\n # just incase, try traditional upload\n res = requests.post('%s/upload/v2?%s' % (codecov.url, urlargs),\n verify=codecov.cacert,\n data='\\n'.join((reports, s3.reason if s3 else '', s3.text if s3 else '')),\n headers={\"Accept\": \"text/plain\"})\n if res.status_code < 500:\n write(' ' + res.text)\n res.raise_for_status()\n result = res.text\n return", " write(' Retrying... in %ds' % (trys * 30))\n sleep(trys * 30)", " except Exception as e:\n write('Error: ' + str(e))\n if kwargs.get('debug'):\n raise", " write('')\n # detect language\n if language:\n write('Tip: See an example %s repo: https://github.com/codecov/example-%s' % (language, language))\n else:\n write('Tip: See all example repositories: https://github.com/codecov?query=example')", " write('Support channels:', 'green')\n write(' Email: hello@codecov.io\\n'\n ' IRC: #codecov\\n'\n ' Gitter: https://gitter.im/codecov/support\\n'\n ' Twitter: @codecov\\n')\n sys.exit(1 if codecov.required else 0)", " else:\n if kwargs.get('debug'):\n return dict(reports=reports, codecov=codecov, query=query, urlargs=urlargs, result=result)", "\nif __name__ == '__main__':\n main()" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [632, 317], "buggy_code_start_loc": [35, 317], "filenames": ["codecov/__init__.py", "tests/test.py"], "fixing_code_end_loc": [636, 321], "fixing_code_start_loc": [36, 318], "message": "This affects the package codecov before 2.0.16. The vulnerability occurs due to not sanitizing gcov arguments before being being provided to the popen method.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:codecov:codecov-python:*:*:*:*:*:*:*:*", "matchCriteriaId": "2F99FFF5-0477-4713-8BBB-0A3113209F50", "versionEndExcluding": "2.0.16", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "This affects the package codecov before 2.0.16. The vulnerability occurs due to not sanitizing gcov arguments before being being provided to the popen method."}, {"lang": "es", "value": "Esto afecta al paquete codecov versiones anteriores a 2.0.16. La vulnerabilidad es producida debido a que no son saneados los argumentos de gcov antes de ser proporcionados al m\u00e9todo popen"}], "evaluatorComment": null, "id": "CVE-2019-10800", "lastModified": "2022-11-08T03:09:17.037", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "report@snyk.io", "type": "Secondary"}]}, "published": "2022-07-13T12:15:08.150", "references": [{"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codecov/codecov-python/commit/2a80aa434f74feb31242b6f213b75ce63ae97902"}, {"source": "report@snyk.io", "tags": ["Exploit", "Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-PYTHON-CODECOV-552149"}], "sourceIdentifier": "report@snyk.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-88"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/codecov/codecov-python/commit/2a80aa434f74feb31242b6f213b75ce63ae97902"}, "type": "CWE-88"}
199
Determine whether the {function_name} code is vulnerable or not.
[ "#!/usr/bin/python", "import os\nimport re\nimport sys\nimport glob\nimport requests\nimport argparse\nfrom time import sleep\nfrom json import loads", "try:\n from urllib.parse import urlencode\nexcept ImportError: # pragma: no cover\n from urllib import urlencode", "try:\n from shlex import quote\nexcept ImportError: # pragma: no cover\n from pipes import quote", "import subprocess", "# https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning\nimport logging\nlogging.captureWarnings(True)", "\nversion = VERSION = __version__ = '2.0.15'", "COLOR = True", "is_merge_commit = re.compile(r'^Merge\\s\\w{40}\\sinto\\s\\w{40}$')", "remove_token = re.compile(r'token=[^\\&]+').sub", "\ndef sanitize_arg(replacement, arg):\n return re.sub(r'[\\&]+', replacement, arg, 0, re.MULTILINE)\n", "\nignored_path = re.compile(r'(/vendor)|'\n r'(/js/generated/coverage)|'\n r'(/__pycache__)|'\n r'(/coverage/instrumented)|'\n r'(/build/lib)|'\n r'(/htmlcov)|'\n r'(/node_modules)|'\n r'(/\\.yarn-cache)|'\n r'(\\.egg-info)|'\n r'(/\\.git)|'\n r'(/\\.hg)|'\n r'(/\\.tox)|'\n r'(/\\.?v?(irtual)?envs?)', re.I).search", "ignored_report = re.compile('.*('\n r'(/\\.coverage.*)|'\n r'(\\.coveragerc)|'\n r'(\\.egg)|'\n r'(\\.gif)|'\n r'(\\.ini)|'\n r'(\\.less)|'\n r'(\\.jpeg)|'\n r'(\\.jpg)|'\n r'(\\.md)|'\n r'(\\.png)|'\n r'(\\.p?sql)|'\n r'(\\.whl)|'\n r'(\\.cpp)|'\n r'(\\.pyc?)|'\n r'(\\.cfg)|'\n r'(\\.class)|'\n r'(\\.js)|'\n r'(\\.html)|'\n r'(\\.sh)|'\n r'(\\.tar\\.gz)|'\n r'(\\.yml)|'\n r'(\\.xcconfig)|'\n r'(\\.data)|'\n r'(coverage\\.db)|'\n r'(\\.?codecov\\.yml)|'\n r'(coverage\\.jade)|'\n r'(include\\.lst)|'\n r'(inputFiles\\.lst)|'\n r'(createdFiles\\.lst)|'\n r'(scoverage\\.measurements\\..*)|'\n r'(test_.*_coverage\\.txt)|'\n r'(conftest_.*\\.c\\.gcov)'\n ')$', re.I).match", "is_report = re.compile('.*('\n r'([^/]*coverage[^/]*)|'\n r'(\\.gcov)|'\n r'(\\.lcov)|'\n r'(\\.lst)|'\n r'(clover\\.xml)|'\n r'(cobertura\\.xml)|'\n r'(coverage-final\\.json)|'\n r'(coverage-summary\\.json)|'\n r'(gcov\\.info)|'\n r'(([^/]*\\.)?codecov\\.[^/]*)|'\n r'(jacoco[^/]*\\.xml)|'\n r'(lcov\\.info)|'\n r'(luacov\\.report\\.out)|'\n r'(nosetests\\.xml)|'\n r'(report\\.xml)'\n ')$', re.I).match", "opj = os.path.join # for faster access", "\ndef write(text, color=None):\n global COLOR\n if COLOR:\n text = text.replace('==>', '\\033[90m==>\\033[0m')\n text = text.replace(' +', ' \\033[32m+\\033[0m')\n text = text.replace('XX>', '\\033[31mXX>\\033[0m')\n if text[:6] == 'Error:':\n text = '\\033[41mError:\\033[0m\\033[91m%s\\033[0m' % text[6:]\n elif text[:4] == 'Tip:':\n text = '\\033[42mTip:\\033[0m\\033[32m%s\\033[0m' % text[4:]\n elif text.strip()[:4] == 'http':\n text = '\\033[92m%s\\033[0m' % text\n elif text[:7] == 'Codecov':\n text = \"\"\"\n _____ _\n / ____| | |\n | | ___ __| | ___ ___ _____ __\n | | / _ \\ / _ |/ _ \\/ __/ _ \\ \\ / /\n | |___| (_) | (_| | __/ (_| (_) \\ V /\n \\_____\\___/ \\____|\\___|\\___\\___/ \\_/\n %s\\n\"\"\" % text.split(' ')[1]\n elif color == 'red':\n text = '\\033[91m%s\\033[0m' % text\n elif color == 'green':\n text = '\\033[92m%s\\033[0m' % text", " sys.stdout.write(text + '\\n')", "\ndef fopen(path):\n try:\n if sys.version_info < (3, 0):\n with open(path, 'r') as f:\n return f.read()\n else:\n try:\n with open(path, 'r', encoding='utf-8') as f:\n return f.read()\n except UnicodeDecodeError:\n with open(path, 'r', encoding='ISO-8859-1') as f:\n return f.read()\n except Exception as e:\n # on none of that works. just print the issue and continue\n write(' - Ignored: ' + str(e))", "\ndef read(filepath):\n try:\n report = fopen(filepath)\n if report is None:\n return\n write(' + %s bytes=%d' % (filepath, os.path.getsize(filepath)))\n return '# path=' + filepath + '\\n' + report\n except Exception as e:\n # Ex: No such file or directory, skip them\n write(' - Ignored: ' + str(e))", "\ndef check_output(cmd, **popen_args):\n from subprocess import Popen, PIPE, CalledProcessError\n process = Popen(cmd, stdout=PIPE, **popen_args)\n output, _ = process.communicate()\n if process.returncode:\n raise CalledProcessError(process.returncode, cmd)\n else:\n assert process.returncode == 0\n return output.decode('utf-8')", "\ndef try_to_run(cmd, shell=True):\n try:\n return check_output(cmd, shell=shell)\n except subprocess.CalledProcessError as e:\n write(' Error running `%s`: %s' % (cmd, e.output or str(e)))", "def run_python_coverage(args):\n \"\"\"Run the Python coverage tool\n \n If it's importable in this Python, launch it using 'python -m'.\n Otherwise, look it up on PATH like any other command.\n \"\"\"\n try:\n import coverage\n except ImportError:\n # Coverage is not installed on this Python. Hope it's on PATH.\n try_to_run(['coverage'] + args, shell=False)\n else:\n # Coverage is installed on this Python. Run it as a module.\n try_to_run([sys.executable, '-m', 'coverage'] + args, shell=False)", "def remove_non_ascii(data):\n try:\n return data.decode('utf8') + ''\n except:\n return ''.join([i if ord(i) < 128 else '' for i in data])", "\ndef _add_env_if_not_empty(lst, value):\n if os.getenv(value) is not None:\n lst.add(value)", "\ndef main(*argv, **kwargs):\n root = os.getcwd()", " # Build Parser\n # ------------\n parser = argparse.ArgumentParser(prog='codecov', add_help=True,\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"Upload reports to Codecov\"\"\")\n basics = parser.add_argument_group('======================== Basics ========================')\n basics.add_argument('--version', action='version', version='Codecov py-v'+version+\" - https://codecov.io/\")\n basics.add_argument('--token', '-t', default=os.getenv(\"CODECOV_TOKEN\"), help=\"Private repository token or @filename for file containing the token. Defaults to $CODECOV_TOKEN. Not required for public repositories on Travis CI, CircleCI and AppVeyor\")\n basics.add_argument('--file', '-f', nargs=\"*\", default=None, help=\"Target a specific file for uploading\")\n basics.add_argument('--flags', '-F', nargs=\"*\", default=None, help=\"Flag these uploaded files with custom labels\")\n basics.add_argument('--env', '-e', nargs=\"*\", default=None, help=\"Store environment variables to help distinguish CI builds.\")\n basics.add_argument('--required', action=\"store_true\", default=False, help=\"If Codecov fails it will exit 1 - possibly failing the CI build.\")\n basics.add_argument('--name', '-n', default=None, help=\"Custom defined name of the upload. Visible in Codecov UI.\")", " gcov = parser.add_argument_group('======================== gcov ========================')\n gcov.add_argument('--gcov-root', default=None, help=\"Project root directory when preparing gcov\")\n gcov.add_argument('--gcov-glob', nargs=\"*\", default=[], help=\"Paths to ignore during gcov gathering\")\n gcov.add_argument('--gcov-exec', default='gcov', help=\"gcov executable to run. Defaults to 'gcov'\")\n gcov.add_argument('--gcov-args', default='', help=\"extra arguments to pass to gcov\")", " advanced = parser.add_argument_group('======================== Advanced ========================')\n advanced.add_argument('-X', '--disable', nargs=\"*\", default=[], help=\"Disable features. Accepting **search** to disable crawling through directories, **detect** to disable detecting CI provider, **gcov** disable gcov commands, `pycov` disables running python `coverage xml`, **fix** to disable report adjustments https://docs.codecov.io/docs/fixing-reports\")\n advanced.add_argument('--root', default=None, help=\"Project directory. Default: current direcory or provided in CI environment variables\")\n advanced.add_argument('--commit', '-c', default=None, help=\"Commit SHA, set automatically\")\n advanced.add_argument('--prefix', '-P', default=None, help=\"Prefix network paths to help resolve paths: https://github.com/codecov/support/issues/472\")\n advanced.add_argument('--branch', '-b', default=None, help=\"Branch name\")\n advanced.add_argument('--build', default=None, help=\"Specify a custom build number to distinguish CI jobs, provided automatically for supported CI companies\")\n advanced.add_argument('--pr', default=None, help=\"Specify a custom pr number, provided automatically for supported CI companies\")\n advanced.add_argument('--tag', default=None, help=\"Git tag\")", " enterprise = parser.add_argument_group('======================== Enterprise ========================')\n enterprise.add_argument('--slug', '-r', default=os.getenv(\"CODECOV_SLUG\"), help=\"Specify repository slug for Enterprise ex. owner/repo\")\n enterprise.add_argument('--url', '-u', default=os.getenv(\"CODECOV_URL\", \"https://codecov.io\"), help=\"Your Codecov endpoint\")\n enterprise.add_argument('--cacert', default=os.getenv(\"CODECOV_CACERT\", os.getenv(\"CURL_CA_BUNDLE\")), help=\"Certificate pem bundle used to verify with your Codecov instance\")", " debugging = parser.add_argument_group('======================== Debugging ========================')\n debugging.add_argument('--dump', action=\"store_true\", help=\"Dump collected data and do not send to Codecov\")\n debugging.add_argument('-v', '--verbose', action=\"store_true\", help=\"Be verbose, e.g. dump the collected data\")\n debugging.add_argument('--no-color', action=\"store_true\", help=\"Do not output with color\")", " # Parse Arguments\n # ---------------\n if argv:\n codecov = parser.parse_args(argv)\n else:\n codecov = parser.parse_args()", " global COLOR\n COLOR = not codecov.no_color", " include_env = set()", " # add from cli\n if codecov.env:\n # -e VAR1,VAR2 or -e VAR1 -e VAR2\n for env in codecov.env:\n for e in env.split(','):\n include_env.add(e.strip())", " # add from env\n if os.getenv(\"CODECOV_ENV\"):\n for env in os.getenv(\"CODECOV_ENV\").split(','):\n include_env.add(env.strip())", " write('Codecov v'+version)\n query = dict(commit='', branch='', job='', pr='', build_url='',\n token=codecov.token)\n language = None", " if os.getenv('TOXENV'):\n _add_env_if_not_empty(include_env, 'TOXENV')", " # Detect CI\n # ---------\n if 'detect' in codecov.disable:\n write('XX> Detecting CI provider disabled.')", " else:\n write('==> Detecting CI provider')\n # -------\n # Jenkins\n # -------\n if os.getenv('JENKINS_URL'):\n # https://wiki.jenkins-ci.org/display/JENKINS/Building+a+software+project\n # https://wiki.jenkins-ci.org/display/JENKINS/GitHub+pull+request+builder+plugin#GitHubpullrequestbuilderplugin-EnvironmentVariables\n query.update(dict(branch=os.getenv('ghprbSourceBranch') or os.getenv('GIT_BRANCH') or os.getenv('BRANCH_NAME'),\n service='jenkins',\n commit=os.getenv('ghprbActualCommit') or os.getenv('GIT_COMMIT'),\n pr=os.getenv('ghprbPullId') or os.getenv('CHANGE_ID'),\n build=os.getenv('BUILD_NUMBER'),\n build_url=os.getenv('BUILD_URL')))\n root = os.getenv('WORKSPACE') or root\n write(' Jenkins Detected')", " # ---------\n # Travis CI\n # ---------\n elif os.getenv('CI') == 'true' and os.getenv('TRAVIS') == \"true\" and os.getenv('SHIPPABLE') != 'true':\n # http://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables\n query.update(dict(branch=os.getenv('TRAVIS_BRANCH'),\n service='travis',\n build=os.getenv('TRAVIS_JOB_NUMBER'),\n pr=os.getenv('TRAVIS_PULL_REQUEST'),\n job=os.getenv('TRAVIS_JOB_ID'),\n tag=os.getenv('TRAVIS_TAG'),\n slug=os.getenv('TRAVIS_REPO_SLUG'),\n commit=os.getenv('TRAVIS_COMMIT')))\n root = os.getenv('TRAVIS_BUILD_DIR') or root\n write(' Travis Detected')\n language = (list(filter(lambda l: os.getenv('TRAVIS_%s_VERSION' % l.upper()),\n ('dart', 'go', 'haxe', 'jdk', 'julia', 'node', 'otp', 'xcode',\n 'perl', 'php', 'python', 'r', 'ruby', 'rust', 'scala'))) + [''])[0]", " _add_env_if_not_empty(include_env, 'TRAVIS_OS_NAME')\n if language:\n _add_env_if_not_empty(include_env, 'TRAVIS_%s_VERSION' % language.upper())", " # --------\n # Codeship\n # --------\n elif os.getenv('CI') == 'true' and os.getenv('CI_NAME') == 'codeship':\n # https://www.codeship.io/documentation/continuous-integration/set-environment-variables/\n query.update(dict(branch=os.getenv('CI_BRANCH'),\n service='codeship',\n build=os.getenv('CI_BUILD_NUMBER'),\n build_url=os.getenv('CI_BUILD_URL'),\n commit=os.getenv('CI_COMMIT_ID')))\n write(' Codeship Detected')", " # ---------\n # Buildkite\n # ---------\n elif os.getenv('CI') == 'true' and os.getenv('BUILDKITE') == 'true':\n # https://buildkite.com/docs/guides/environment-variables\n query.update(dict(branch=os.getenv('BUILDKITE_BRANCH'),\n service='buildkite',\n build=os.getenv('BUILDKITE_BUILD_NUMBER') + '.' + os.getenv('BUILDKITE_JOB_ID'),\n slug=os.getenv('BUILDKITE_PROJECT_SLUG'),\n build_url=os.getenv('BUILDKITE_BUILD_URL'),\n commit=os.getenv('BUILDKITE_COMMIT')))\n write(' Buildkite Detected')", " # ---------\n # Circle CI\n # ---------\n elif os.getenv('CI') == 'true' and os.getenv('CIRCLECI') == 'true':\n # https://circleci.com/docs/environment-variables\n query.update(dict(branch=os.getenv('CIRCLE_BRANCH'),\n service='circleci',\n build=os.getenv('CIRCLE_BUILD_NUM') + \".\" + os.getenv('CIRCLE_NODE_INDEX'),\n job=os.getenv('CIRCLE_BUILD_NUM') + \".\" + os.getenv('CIRCLE_NODE_INDEX'),\n pr=os.getenv('CIRCLE_PR_NUMBER'),\n slug=os.getenv('CIRCLE_PROJECT_USERNAME') + \"/\" + os.getenv('CIRCLE_PROJECT_REPONAME'),\n commit=os.getenv('CIRCLE_SHA1')))\n write(' Circle CI Detected')", " # ---------\n # Semaphore\n # ---------\n elif os.getenv('CI') == 'true' and os.getenv('SEMAPHORE') == 'true':\n # https://semaphoreapp.com/docs/available-environment-variables.html\n query.update(dict(branch=os.getenv('BRANCH_NAME'),\n service='semaphore',\n build=os.getenv('SEMAPHORE_BUILD_NUMBER') + '.' + os.getenv('SEMAPHORE_CURRENT_THREAD'),\n slug=os.getenv('SEMAPHORE_REPO_SLUG'),\n commit=os.getenv('REVISION')))\n write(' Semaphore Detected')", " # ----------\n # Greenhouse\n # ----------\n elif os.getenv('GREENHOUSE') == 'true':\n # http://docs.greenhouseci.com/docs/environment-variables-files\n query.update(dict(branch=os.getenv('GREENHOUSE_BRANCH'),\n service='greenhouse',\n build=os.getenv('GREENHOUSE_BUILD_NUMBER'),\n build_url=os.getenv('GREENHOUSE_BUILD_URL'),\n pr=os.getenv('GREENHOUSE_PULL_REQUEST'),\n commit=os.getenv('GREENHOUSE_COMMIT')))\n write(' Greenhouse Detected')", " # --------\n # drone.io\n # --------\n elif os.getenv('CI') == \"drone\" and os.getenv('DRONE') == \"true\":\n # http://docs.drone.io/env.html\n query.update(dict(branch=os.getenv('DRONE_BRANCH'),\n service='drone.io',\n build=os.getenv('DRONE_BUILD_NUMBER'),\n build_url=os.getenv('DRONE_BUILD_LINK')))\n root = os.getenv('DRONE_BUILD_DIR') or root\n write(' Drone Detected')", " # --------\n # TeamCity\n # --------\n elif os.getenv('TEAMCITY_VERSION'):\n # https://confluence.jetbrains.com/plugins/servlet/mobile#content/view/74847298\n query.update(dict(service='teamcity',\n build=os.getenv('BUILD_NUMBER'),\n commit=os.getenv('BUILD_VCS_NUMBER')))\n write(' TeamCity CI Detected')", " # --------\n # AppVeyor\n # --------\n elif os.getenv('CI', 'false').lower() == 'true' and os.getenv('APPVEYOR', 'false').lower() == 'true':\n # http://www.appveyor.com/docs/environment-variables\n query.update(dict(branch=os.getenv('APPVEYOR_REPO_BRANCH'),\n service=\"appveyor\",\n job='/'.join((os.getenv('APPVEYOR_ACCOUNT_NAME'), os.getenv('APPVEYOR_PROJECT_SLUG'), os.getenv('APPVEYOR_BUILD_VERSION'))),\n build=os.getenv('APPVEYOR_JOB_ID'),\n pr=os.getenv('APPVEYOR_PULL_REQUEST_NUMBER'),\n slug=os.getenv('APPVEYOR_REPO_NAME'),\n commit=os.getenv('APPVEYOR_REPO_COMMIT')))\n write(' AppVeyor Detected')\n codecov.disable.append('search')", " # -------\n # Wercker\n # -------\n elif os.getenv('CI') == \"true\" and os.getenv('WERCKER_GIT_BRANCH'):\n # http://devcenter.wercker.com/articles/steps/variables.html\n query.update(dict(branch=os.getenv('WERCKER_GIT_BRANCH'),\n service=\"wercker\",\n build=os.getenv('WERCKER_MAIN_PIPELINE_STARTED'),\n slug=os.getenv('WERCKER_GIT_OWNER') + '/' + os.getenv('WERCKER_GIT_REPOSITORY'),\n commit=os.getenv('WERCKER_GIT_COMMIT')))\n write(' Wercker Detected')", " # ------\n # Magnum\n # ------\n elif os.getenv('CI') == \"true\" and os.getenv('MAGNUM') == 'true':\n # https://magnum-ci.com/docs/environment\n query.update(dict(service=\"magnum\",\n branch=os.getenv('CI_BRANCH'),\n build=os.getenv('CI_BUILD_NUMBER'),\n commit=os.getenv('CI_COMMIT')))\n write(' Magnum Detected')", " # ---------\n # Shippable\n # ---------\n elif os.getenv('SHIPPABLE') == \"true\":\n # http://docs.shippable.com/en/latest/config.html#common-environment-variables\n query.update(dict(branch=os.getenv('BRANCH'),\n service='shippable',\n build=os.getenv('BUILD_NUMBER'),\n build_url=os.getenv('BUILD_URL'),\n pr=os.getenv('PULL_REQUEST'),\n slug=os.getenv('REPO_NAME'),\n commit=os.getenv('COMMIT')))\n write(' Shippable Detected')", " # ---------\n # Gitlab CI\n # ---------\n elif os.getenv('CI_SERVER_NAME', '').startswith(\"GitLab\"):\n # http://doc.gitlab.com/ci/examples/README.html#environmental-variables\n # https://gitlab.com/gitlab-org/gitlab-ci-runner/blob/master/lib/build.rb#L96\n query.update(dict(service='gitlab',\n branch=os.getenv('CI_BUILD_REF_NAME'),\n build=os.getenv('CI_BUILD_ID'),\n commit=os.getenv('CI_BUILD_REF')))\n if os.getenv('CI_PROJECT_DIR', '').startswith('/'):\n root = os.getenv('CI_PROJECT_DIR')\n else:\n root = os.getenv('HOME') + '/' + os.getenv('CI_PROJECT_DIR', '')", " if os.getenv('CI_BUILD_REPO'):\n query['slug'] = os.getenv('CI_BUILD_REPO').split('/', 3)[-1].replace('.git', '')\n elif os.getenv('CI_REPOSITORY_URL'):\n query['slug'] = os.getenv('CI_REPOSITORY_URL').split('/', 3)[-1].replace('.git', '')", " write(' Gitlab CI Detected')", " else:\n query.update(dict(commit=os.getenv('VCS_COMMIT_ID', ''),\n branch=os.getenv('VCS_BRANCH_NAME', ''),\n pr=os.getenv('VCS_PULL_REQUEST', ''),\n slug=os.getenv('VCS_SLUG', ''),\n build_url=os.getenv('CI_BUILD_URL', ''),\n build=os.getenv('CI_BUILD_ID', '')))", " # ------\n # git/hg\n # ------\n if not query.get('branch'):\n try:\n # find branch, commit, repo from git command\n branch = try_to_run('git rev-parse --abbrev-ref HEAD || hg branch')\n query['branch'] = branch if branch != 'HEAD' else ''\n write(' -> Got branch from git/hg')", " except:\n write(' x> Failed to get branch from git/hg')", " if not query.get('commit'):\n try:\n query['commit'] = try_to_run(\"git rev-parse HEAD || hg id -i --debug | tr -d '+'\")\n write(' -> Got sha from git/hg')", " except: # pragma: no cover\n write(' x> Failed to get sha from git/hg')", " # Update Query\n # ------------\n if codecov.name:\n query['name'] = codecov.name", " if codecov.flags:\n query['flags'] = ','.join(codecov.flags)", " if codecov.build:\n query['build'] = codecov.build", " if codecov.pr:\n query['pr'] = codecov.pr", " if codecov.commit:\n query['commit'] = codecov.commit", " elif query['pr'] and query['pr'] != 'false':\n # Merge Commits\n # -------------\n res = try_to_run('git log -1 --pretty=%B')\n if res and is_merge_commit.match(res.strip()):\n query['commit'] = res.split(' ')[1]\n write(' Fixing merge commit SHA')", " if codecov.slug:\n query['slug'] = codecov.slug", " if codecov.branch:\n query['branch'] = codecov.branch", " if codecov.tag:\n query['tag'] = codecov.tag", " if codecov.root:\n root = codecov.root", " root = quote(root)", " # Upload\n # ------\n try:\n write('==> Preparing upload')", " # Read token from file\n # --------------------\n if query.get('token') and query.get('token')[0] == '@':\n write(' Reading token from file')\n query['token'] = fopen(opj(os.getcwd(), query['token'][1:])).strip()", " assert query.get('commit') not in ('', None), \"Commit sha is missing. Please specify via --commit=:sha\"", " # Build TOC\n # ---------\n toc = str((try_to_run('cd %s && git ls-files' % root) or\n try_to_run('git ls-files') or\n try_to_run('cd %s && hg locate' % root) or\n try_to_run('hg locate') or '').strip())", " if codecov.prefix:\n prefix = codecov.prefix.strip('/')\n toc = '{}/{}'.format(\n prefix,\n toc.replace('\\n', '\\n{}/'.format(prefix))\n )", " # Detect codecov.yml location\n yaml_location = re.search(\n r'\\.?codecov\\.ya?ml$',\n toc,\n re.M\n )\n if yaml_location:\n yaml_location = yaml_location.group()\n yaml_path = opj(root, yaml_location)\n if os.path.exists(yaml_path):\n query['yaml'] = yaml_location\n yaml = fopen(yaml_path)\n _token = re.search(\n r'token: (\\'|\\\")?([0-9a-f]{8}(-?[0-9a-f]{4}){3}-?[0-9a-f]{12})',\n yaml,\n re.M\n )\n if _token:\n query['token'] = _token.groups()[1]", " _slug = re.search(\n r'slug: (\\'|\\\")?([\\w\\-\\.\\+]+\\/[\\w\\-\\.\\+]+)',\n yaml,\n re.M\n )\n if _slug:\n query['slug'] = _slug.groups()[1]", " assert query.get('job') or query.get('token'), \"Missing repository upload token\"", " # Processing gcov\n # ---------------\n if 'gcov' in codecov.disable:\n write('XX> Skip processing gcov')", " else:\n dont_search_here = (\n \"-not -path './bower_components/**' \"\n \"-not -path './node_modules/**' \"\n \"-not -path './vendor/**'\"\n )\n write('==> Processing gcov (disable by -X gcov)')\n cmd = \"find %s %s -type f -name '*.gcno' %s -exec %s -pb %s {} +\" % (", " (sanitize_arg('', codecov.gcov_root or root)),", " dont_search_here,\n \" \".join(map(lambda a: \"-not -path '%s'\" % a, codecov.gcov_glob)),", " (sanitize_arg('', codecov.gcov_exec or '')),\n (sanitize_arg('', codecov.gcov_args or '')))", " write(' Executing gcov (%s)' % cmd)\n try_to_run(cmd)", " # Collect Reports\n # ---------------\n write('==> Collecting reports')\n reports = []", " if 'search' in codecov.disable:\n write('XX> Searching for reports disabled')\n else:", " # Detect .bowerrc\n # ---------------\n bower_components = '/bower_components'\n bowerrc = opj(root, '.bowerrc')\n if os.path.exists(bowerrc):\n write(' Detecting .bowerrc file')\n try:\n bower_components = '/' + (loads(fopen(bowerrc)).get('directory') or 'bower_components').replace('./', '').strip('/')\n write(' .bowerrc detected, ignoring ' + bower_components)\n except Exception as e:\n write(' .bowerrc parsing error: ' + str(e))", " # Find reports\n # ------------\n for _root, dirs, files in os.walk(root):\n # need to replace('\\\\', '/') for Windows\n if not ignored_path(_root.replace('\\\\', '/')) and bower_components not in _root.replace('\\\\', '/'):\n # add data to tboc\n for filepath in files:\n fullpath = opj(_root, filepath)\n if not codecov.file and is_report(fullpath.replace('\\\\', '/')) and not ignored_report(fullpath.replace('\\\\', '/')):\n # found report\n reports.append(read(fullpath))", " # Read Reports\n # ------------\n if codecov.file:\n write(' Targeting specific files')\n reports.extend(filter(bool, map(read, codecov.file)))", " elif 'pycov' not in codecov.disable:\n # Call `coverage xml` when .coverage exists\n # -----------------------------------------\n # Ran from current directory\n if glob.glob(opj(os.getcwd(), '.coverage.*')):\n write(' Merging coverage reports')\n # The `-a` option is mandatory here. If we\n # have a `.coverage` in the current directory, calling\n # without the option would delete the previous data\n run_python_coverage(['combine', '-a'])", " if os.path.exists(opj(os.getcwd(), '.coverage')) and not os.path.exists(opj(os.getcwd(), 'coverage.xml')):\n write(' Generating coverage xml reports for Python')\n # using `-i` to ignore \"No source for code\" error\n run_python_coverage(['xml', '-i'])\n reports.append(read(opj(os.getcwd(), 'coverage.xml')))", " reports = list(filter(bool, reports))\n assert len(reports) > 0, \"No coverage report found\"", " # Storing Environment\n # -------------------\n env = ''\n if include_env:\n write('==> Appending environment variables')\n for k in include_env:\n if k:\n write(' + ' + k)", " env = '\\n'.join([\"%s=%s\" % (k, os.getenv(k, '')) for k in include_env if k]) + '\\n<<<<<< ENV'", " # join reports together\n reports = '\\n'.join((env, (toc or ''), '<<<<<< network',\n '\\n<<<<<< EOF\\n'.join(reports),\n '<<<<<< EOF'))", " query['package'] = \"py\" + VERSION\n urlargs = (urlencode(dict([(k, v.strip()) for k, v in query.items() if v not in ('', None)]))).replace(\"+\", \"%20\")", " result = ''\n if codecov.dump:\n write('-------------------- Debug --------------------')\n write(' .url ' + codecov.url)\n write(' .query ' + remove_token('token=<secret>', urlargs))\n write(reports)\n write('-------------------- EOF --------------------')\n else:\n write('==> Uploading')\n write(' .url ' + codecov.url)\n write(' .query ' + remove_token('token=<secret>', urlargs))\n if codecov.verbose:\n write('-------------------- Reports --------------------')\n write(reports)\n write('-------------------------------------------------')", " s3 = None\n trys = 0\n while trys < 3:\n trys += 1\n if 's3' not in codecov.disable:\n try:\n write(' Pinging Codecov...')\n res = requests.post('%s/upload/v4?%s' % (codecov.url, urlargs),\n verify=codecov.cacert,\n headers={'Accept': 'text/plain',\n 'X-Reduced-Redundancy': 'false'})\n if res.status_code in (400, 406):\n raise Exception(res.text)", " elif res.status_code < 500:\n assert res.status_code == 200\n res = res.text.strip().split()\n result, upload_url = res[0], res[1]", " # Handle reports encoding for Python 2 and 3\n if not isinstance(reports, bytes):\n reports = reports.encode('utf-8')", " write(' Uploading to S3...')\n s3 = requests.put(upload_url, data=reports,\n headers={'Content-Type': 'text/plain',\n 'x-amz-acl': 'public-read'})\n s3.raise_for_status()\n assert s3.status_code == 200\n write(' ' + result)\n break\n else:\n # try again\n continue", " except AssertionError:\n write(' Direct to s3 failed. Using backup v2 endpoint.')", " write(' Uploading to Codecov...')\n # just incase, try traditional upload\n res = requests.post('%s/upload/v2?%s' % (codecov.url, urlargs),\n verify=codecov.cacert,\n data='\\n'.join((reports, s3.reason if s3 else '', s3.text if s3 else '')),\n headers={\"Accept\": \"text/plain\"})\n if res.status_code < 500:\n write(' ' + res.text)\n res.raise_for_status()\n result = res.text\n return", " write(' Retrying... in %ds' % (trys * 30))\n sleep(trys * 30)", " except Exception as e:\n write('Error: ' + str(e))\n if kwargs.get('debug'):\n raise", " write('')\n # detect language\n if language:\n write('Tip: See an example %s repo: https://github.com/codecov/example-%s' % (language, language))\n else:\n write('Tip: See all example repositories: https://github.com/codecov?query=example')", " write('Support channels:', 'green')\n write(' Email: hello@codecov.io\\n'\n ' IRC: #codecov\\n'\n ' Gitter: https://gitter.im/codecov/support\\n'\n ' Twitter: @codecov\\n')\n sys.exit(1 if codecov.required else 0)", " else:\n if kwargs.get('debug'):\n return dict(reports=reports, codecov=codecov, query=query, urlargs=urlargs, result=result)", "\nif __name__ == '__main__':\n main()" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [632, 317], "buggy_code_start_loc": [35, 317], "filenames": ["codecov/__init__.py", "tests/test.py"], "fixing_code_end_loc": [636, 321], "fixing_code_start_loc": [36, 318], "message": "This affects the package codecov before 2.0.16. The vulnerability occurs due to not sanitizing gcov arguments before being being provided to the popen method.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:codecov:codecov-python:*:*:*:*:*:*:*:*", "matchCriteriaId": "2F99FFF5-0477-4713-8BBB-0A3113209F50", "versionEndExcluding": "2.0.16", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "This affects the package codecov before 2.0.16. The vulnerability occurs due to not sanitizing gcov arguments before being being provided to the popen method."}, {"lang": "es", "value": "Esto afecta al paquete codecov versiones anteriores a 2.0.16. La vulnerabilidad es producida debido a que no son saneados los argumentos de gcov antes de ser proporcionados al m\u00e9todo popen"}], "evaluatorComment": null, "id": "CVE-2019-10800", "lastModified": "2022-11-08T03:09:17.037", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "report@snyk.io", "type": "Secondary"}]}, "published": "2022-07-13T12:15:08.150", "references": [{"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codecov/codecov-python/commit/2a80aa434f74feb31242b6f213b75ce63ae97902"}, {"source": "report@snyk.io", "tags": ["Exploit", "Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-PYTHON-CODECOV-552149"}], "sourceIdentifier": "report@snyk.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-88"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/codecov/codecov-python/commit/2a80aa434f74feb31242b6f213b75ce63ae97902"}, "type": "CWE-88"}
199
Determine whether the {function_name} code is vulnerable or not.
[ "import os\nimport sys\nimport pickle\nimport itertools\nfrom ddt import ddt, data\nfrom mock import patch, Mock\nimport unittest", "import subprocess", "import codecov", "\n@ddt\nclass TestUploader(unittest.TestCase):\n maxDiff = None\n here = os.path.dirname(__file__)\n bowerrc = os.path.join(os.path.dirname(__file__), '../.bowerrc')\n token = os.path.join(os.path.dirname(__file__), '../.token')\n jacoco = os.path.join(os.path.dirname(__file__), '../jacoco.xml')\n filepath = os.path.join(os.path.dirname(__file__), 'coverage.xml')\n coverage = os.path.join(os.path.dirname(__file__), '../.coverage')\n defaults = dict(commit='a', branch='a', token='a')", " @classmethod\n def setUpClass(self):\n self._env = os.environ.copy()", " @classmethod\n def tearDownClass(self):\n os.environ = self._env", " def setUp(self):\n # set all environ back\n os.environ['CI'] = \"true\"\n for key in (\"TRAVIS\", \"TRAVIS_BRANCH\", \"TRAVIS_COMMIT\", \"TRAVIS_BUILD_DIR\", \"TRAVIS_JOB_ID\", \"TRAVIS_PULL_REQUEST\",\n \"CI_NAME\", \"CI_BRANCH\", \"CI_COMMIT_ID\", \"SHIPPABLE\",\n \"CI_BUILD_NUMBER\", \"MAGNUM\", \"CI_COMMIT\", \"APPVEYOR_ACCOUNT_NAME\", \"APPVEYOR_PROJECT_SLUG\", \"APPVEYOR_PULL_REQUEST_NUMBER\",\n \"CIRCLECI\", \"CIRCLE_BRANCH\", \"CIRCLE_ARTIFACTS\", \"CIRCLE_SHA1\", \"CIRCLE_NODE_INDEX\", \"CIRCLE_PR_NUMBER\",\n \"SEMAPHORE\", \"BRANCH_NAME\", \"SEMAPHORE_PROJECT_DIR\", \"REVISION\",\n \"BUILDKITE\", \"BUILDKITE_BUILD_NUMBER\", \"BUILDKITE_JOB_ID\", \"BUILDKITE_BRANCH\", \"BUILDKITE_PROJECT_SLUG\", \"BUILDKITE_COMMIT\",\n \"DRONE\", \"DRONE_BRANCH\", \"DRONE_BUILD_DIR\", \"JENKINS_URL\", \"TRAVIS_TAG\",\n \"GIT_BRANCH\", \"GIT_COMMIT\", \"WORKSPACE\", \"BUILD_NUMBER\", \"CI_BUILD_URL\", \"SEMAPHORE_REPO_SLUG\", \"SEMAPHORE_CURRENT_THREAD\",\n \"DRONE_BUILD_LINK\", \"TRAVIS_REPO_SLUG\", \"CODECOV_TOKEN\", \"APPVEYOR\", \"APPVEYOR_REPO_BRANCH\",\n \"APPVEYOR_BUILD_VERSION\", \"APPVEYOR_JOB_ID\", \"APPVEYOR_REPO_NAME\", \"APPVEYOR_REPO_COMMIT\", \"WERCKER_GIT_BRANCH\",\n \"WERCKER_MAIN_PIPELINE_STARTED\", \"WERCKER_GIT_OWNER\", \"WERCKER_GIT_REPOSITORY\",\n \"CI_BUILD_REF_NAME\", \"CI_BUILD_ID\", \"CI_BUILD_REPO\", \"CI_PROJECT_DIR\", \"CI_BUILD_REF\", \"CI_SERVER_NAME\",\n \"ghprbActualCommit\", \"ghprbSourceBranch\", \"ghprbPullId\", \"WERCKER_GIT_COMMIT\", \"CHANGE_ID\"):\n os.environ[key] = \"\"", " def tearDown(self):\n self.delete(self.filepath, self.coverage, self.jacoco, self.bowerrc)\n self.delete('hello', 'hello.c', 'hello.gcda', 'hello.c.gcov', 'hello.gcno')", " def set_env(self, **kwargs):\n for key in kwargs:\n os.environ[key] = str(kwargs[key])", " def run_cli(self, dump=True, *args, **kwargs):\n inline = list(itertools.chain(*[['--%s' % key, str(value)] for key, value in kwargs.items() if value]))\n if dump:\n inline.append('--dump')\n inline.extend(args)\n return codecov.main(*inline, debug=True)", " def fake_report(self):\n with open(self.filepath, 'w+') as f:\n f.write('__data__')", " def delete(self, *paths):\n for path in paths:\n if os.path.exists(path):\n os.remove(path)\n path = os.path.join(os.path.dirname(__file__), '../', path)\n if os.path.exists(path):\n os.remove(path)", " @data('vendor', 'node_modules', 'js/generated/coverage', '__pycache__', 'coverage/instrumented',\n 'build/lib', 'htmlcov', '.egg-info', '.git', '.tox', 'venv', '.venv-python-2.7')\n def test_ignored_path(self, path):\n self.assertTrue(bool(codecov.ignored_path('/home/ubuntu/' + path)), path + ' should be ignored')\n self.assertTrue(bool(codecov.ignored_path('/home/ubuntu/' + path + '/more paths')), path + ' should be ignored')", " @data('coverage.xml', 'jacoco.xml', 'jacocoTestResults.xml', 'coverage.txt',\n 'gcov.lst', 'cov.gcov', 'info.lcov', 'clover.xml', 'cobertura.xml',\n 'luacov.report.out', 'gcov.info', 'nosetests.xml')\n def test_is_report(self, path):\n self.assertFalse(bool(codecov.ignored_report('/home/file/' + path)), path + ' should not be ignored')\n self.assertTrue(bool(codecov.is_report('/home/file/' + path)), path + ' should be a report')", " @data('.coverage.worker10', 'coverage.jade', 'include.lst', 'inputFiles.lst',\n 'createdFiles.lst', 'scoverage.measurements.blackandwhite.xml', 'test_hello_coverage.txt',\n 'conftest_blackwhite.c.gcov')\n def test_ignore_report(self, path):\n self.assertTrue(bool(codecov.ignored_report('/home/file/' + path)), path + ' should be ignored')", " def test_command(self):\n try:\n self.run_cli(True, '--help')\n except SystemExit as e:\n self.assertEqual(str(e), '0')\n else:\n raise Exception(\"help not shown\")", " def test_exits_0(self):\n try:\n sys.argv = ['']\n codecov.main()\n except SystemExit as e:\n self.assertEqual(str(e), '0')\n else:\n raise Exception(\"did not exit\")", " def test_exits_1(self):\n try:\n sys.argv = ['']\n codecov.main('--required')\n except SystemExit as e:\n self.assertEqual(str(e), '1')\n else:\n raise Exception(\"did not exit\")", " @unittest.skipIf(os.getenv('CI') == \"True\" and os.getenv('APPVEYOR') == 'True', 'Skip AppVeyor CI test')\n def test_returns_none(self):\n with patch('requests.post') as post:\n with patch('requests.put') as put:\n post.return_value = Mock(status_code=200, text='target\\ns3')\n put.return_value = Mock(status_code=200)\n with open(self.filepath, 'w+') as f:\n f.write('coverage data')\n sys.argv = ['', '--commit=8ed84d96bc225deff66605486180cd555366806b',\n '--branch=master',\n '--token=473c8c5b-10ee-4d83-86c6-bfd72a185a27']\n self.assertEqual(codecov.main(), None)\n assert post.called and put.called", " @unittest.skipIf(os.getenv('CI') == \"True\" and os.getenv('APPVEYOR') == 'True', 'Skip AppVeyor CI test')\n def test_send(self):\n with patch('requests.post') as post:\n with patch('requests.put') as put:\n post.return_value = Mock(status_code=200, text='target\\ns3')\n put.return_value = Mock(status_code=200)\n with open(self.filepath, 'w+') as f:\n f.write('coverage data')\n res = self.run_cli(False, commit='a'*40, branch='master', token='<token>')\n self.assertEqual(res['result'].strip(), 'target')\n assert 'https://codecov.io/upload/v4?' in post.call_args[0][0]\n assert 'commit=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' in post.call_args[0][0]\n assert 'token=%3Ctoken%3E' in post.call_args[0][0]\n assert 'branch=master' in post.call_args[0][0]\n assert u'tests/test.py'.encode(\"utf-8\") in put.call_args[1]['data']", " def test_send_error(self):\n with patch('requests.post') as post:\n post.return_value = Mock(status_code=400, text='error')\n with open(self.filepath, 'w+') as f:\n f.write('coverage data')\n try:\n self.run_cli(False, token='not-a-token', commit='a'*40, branch='master')\n except Exception:\n pass\n else:\n raise Exception('400 never raised')", " @data((dict(commit='sha'), 'Missing repository upload token'), )\n def test_require_branch(self, dd):\n (kwargs, reason) = dd\n # this is so we dont get branch for local git\n self.set_env(JENKINS_URL='hello')\n try:\n self.run_cli(**kwargs)\n except AssertionError as e:\n self.assertEqual(str(e), reason)\n else:\n raise Exception(\"Did not raise AssertionError\")", " @unittest.skipIf(os.getenv('CI') == \"True\" and os.getenv('APPVEYOR') == 'True', 'Skip AppVeyor CI test')\n def test_read_token_file(self):\n with open(self.token, 'w+') as f:\n f.write('a')\n with open(self.filepath, 'w+') as f:\n f.write('coverage data')\n res = self.run_cli(token='@'+self.token, commit='a', branch='b')\n self.assertIn('token=a', res['urlargs'])", " def test_bowerrc(self):\n with open(self.bowerrc, 'w+') as f:\n f.write('{\"directory\": \"tests\"}')\n with open(self.filepath, 'w+') as f:\n f.write('coverage data')\n try:\n self.run_cli(**self.defaults)\n except AssertionError as e:\n self.assertEqual(str(e), \"No coverage report found\")\n else:\n raise Exception(\"Did not raise AssertionError\")", " def test_disable_search(self):\n self.fake_report()\n try:\n self.run_cli(disable='search', token='a', branch='b', commit='c')\n except AssertionError as e:\n self.assertEqual(str(e), \"No coverage report found\")\n else:\n raise Exception(\"Did not raise AssertionError\")", " @unittest.skipIf(os.getenv('CI') == \"True\" and os.getenv('APPVEYOR') == 'True', 'Skip AppVeyor CI test')\n def test_prefix(self):\n self.fake_report()\n res = self.run_cli(prefix='/foo/bar/', dump=True, token='a', branch='b', commit='c')\n assert '\\nfoo/bar/.gitignore' in res['reports']", " def write_c(self):\n c = '\\n'.join(('#include <stdio.h>',\n 'static int t = 1;'\n 'int main()', '{',\n 'if (t)', 'printf(\"on this line\\\\n\");',\n 'else', 'printf(\"but not here\\\\n\");',\n 'return 0;', '}'))\n with open(os.path.join(os.path.dirname(__file__), '../hello.c'), 'w+') as f:\n f.write(c)\n codecov.try_to_run('clang -coverage -O0 hello.c -o hello && ./hello')", " def test_disable_gcov(self):\n if self._env.get('TRAVIS') == 'true':\n self.write_c()\n try:\n self.run_cli(disable='gcov', token='a', branch='b', commit='c')\n except AssertionError as e:\n self.assertEqual(os.path.exists('hello.c.gcov'), False)\n self.assertEqual(str(e), \"No coverage report found\")\n else:\n raise Exception(\"Did not raise AssertionError\")\n else:\n self.skipTest(\"Skipped, works on Travis only.\")", " def test_gcov(self):\n self.skipTest(\"Need to fix this test...\")\n # if self._env.get('TRAVIS') == 'true':\n # self.write_c()\n # output = self.run_cli(token='a', branch='b', commit='c')\n # self.assertEqual(os.path.exists('hello.c.gcov'), True)\n # report = output['reports'].split('<<<<<< network\\n')[1].splitlines()\n # self.assertIn('hello.c.gcov', report[0])\n # else:\n # self.skipTest(\"Skipped, works on Travis only.\")", " def test_disable_detect(self):\n self.set_env(JENKINS_URL='a', GIT_BRANCH='b', GIT_COMMIT='c', CODECOV_TOKEN='d')\n self.fake_report()\n try:\n self.run_cli(disable='detect')\n except AssertionError as e:\n self.assertEqual(str(e), \"Commit sha is missing. Please specify via --commit=:sha\")\n else:\n raise Exception(\"Did not raise AssertionError\")", " @unittest.skipIf(os.getenv('CI') == \"True\" and os.getenv('APPVEYOR') == 'True', 'Skip AppVeyor CI test')\n def test_bowerrc_none(self):\n with open(self.bowerrc, 'w+') as f:\n f.write('{\"other_key\": \"tests\"}')\n with open(self.filepath, 'w+') as f:\n f.write('coverage data')\n res = self.run_cli(**self.defaults)\n self.assertIn('tests/test.py', res['reports'])", " @unittest.skipIf(os.getenv('CI') == \"True\" and os.getenv('APPVEYOR') == 'True', 'Skip AppVeyor CI test')\n def test_discovers(self):\n with open(self.jacoco, 'w+') as f:\n f.write('<jacoco></jacoco>')\n with open(self.filepath, 'w+') as f:\n f.write('coverage data')\n res = self.run_cli(**self.defaults)\n self.assertIn('coverage.xml', res['reports'])\n self.assertIn('coverage data', res['reports'])\n self.assertIn('jacoco.xml', res['reports'])\n self.assertIn('<jacoco></jacoco>', res['reports'])", " def test_not_jacoco(self):\n with open(self.filepath, 'w+') as f:\n f.write('<data>')\n res = self.run_cli(file='tests/coverage.xml', **self.defaults)\n res = res['reports'].split('<<<<<< network\\n')[1].splitlines()\n self.assertEqual(res[0], '# path=tests/coverage.xml')\n self.assertEqual(res[1], '<data>')", " def test_run_coverage(self):\n self.skipTest('Not sure how to pull off atm')\n with open(self.coverage, 'w+') as f:\n f.write(pickle.dumps())\n res = self.run_cli(**self.defaults)\n self.assertIn('<?xml version=\"1.0\" ?>', res['reports'])", " def test_run_coverage_fails(self):\n with open(self.coverage, 'w+') as f:\n f.write('bad data')\n try:\n self.run_cli(**self.defaults)\n except AssertionError as e:\n self.assertEqual(str(e), 'No coverage report found')\n else:\n raise Exception(\"Did not raise AssertionError\")", " def test_include_env(self):\n self.set_env(HELLO='WORLD')\n self.fake_report()\n res = self.run_cli(env='HELLO', file=self.filepath, **self.defaults)\n self.assertIn('HELLO=WORLD', res['reports'])", " def test_none_found(self):\n try:\n self.run_cli(**self.defaults)\n except AssertionError as e:\n self.assertEqual(str(e), \"No coverage report found\")\n else:\n raise Exception(\"Did not raise AssertionError\")\n", "", " @unittest.skipUnless(os.getenv('JENKINS_URL'), 'Skip Jenkins CI test')\n def test_ci_jenkins(self):\n self.set_env(BUILD_URL='https://....',\n JENKINS_URL='https://....',\n GIT_BRANCH='master',\n GIT_COMMIT='c739768fcac68144a3a6d82305b9c4106934d31a',\n BUILD_NUMBER='41',\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'jenkins')\n self.assertEqual(res['query']['commit'], 'c739768fcac68144a3a6d82305b9c4106934d31a')\n self.assertEqual(res['query']['build'], '41')\n self.assertEqual(res['query']['build_url'], 'https://....')\n self.assertEqual(res['query']['pr'], '')\n self.assertEqual(res['query']['branch'], 'master')\n self.assertEqual(res['codecov'].token, 'token')", " @unittest.skipUnless(os.getenv('JENKINS_URL'), 'Skip Jenkins CI test')\n def test_ci_jenkins_env(self):\n self.set_env(JENKINS_URL='https://....',\n BUILD_URL='https://....',\n ghprbSourceBranch='master',\n ghprbActualCommit='c739768fcac68144a3a6d82305b9c4106934d31a',\n ghprbPullId='1',\n BUILD_NUMBER='41',\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'jenkins')\n self.assertEqual(res['query']['commit'], 'c739768fcac68144a3a6d82305b9c4106934d31a')\n self.assertEqual(res['query']['build'], '41')\n self.assertEqual(res['query']['build_url'], 'https://....')\n self.assertEqual(res['query']['pr'], '1')\n self.assertEqual(res['query']['branch'], 'master')\n self.assertEqual(res['codecov'].token, 'token')", " @unittest.skipUnless(os.getenv('JENKINS_URL'), 'Skip Jenkins CI test')\n def test_ci_jenkins_blue_ocean(self):\n self.set_env(JENKINS_URL='https://....',\n BUILD_URL='https://....',\n BRANCH_NAME='master',\n CHANGE_ID='1',\n BUILD_NUMBER='41',\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'jenkins')\n self.assertEqual(res['query']['commit'], codecov.check_output((\"git\", \"rev-parse\", \"HEAD\")))\n self.assertEqual(res['query']['build'], '41')\n self.assertEqual(res['query']['build_url'], 'https://....')\n self.assertEqual(res['query']['pr'], '1')\n self.assertEqual(res['query']['branch'], 'master')\n self.assertEqual(res['codecov'].token, 'token')", " @unittest.skipUnless(os.getenv('CI') == 'true'\n and os.getenv('TRAVIS') == \"true\"\n and os.getenv('SHIPPABLE') != 'true',\n 'Skip Travis CI test')\n def test_ci_travis(self):\n self.set_env(TRAVIS=\"true\",\n TRAVIS_BRANCH=\"master\",\n TRAVIS_COMMIT=\"c739768fcac68144a3a6d82305b9c4106934d31a\",\n TRAVIS_REPO_SLUG='owner/repo',\n TRAVIS_JOB_ID=\"33116958\",\n TRAVIS_TAG=\"v1.1.1\",\n TRAVIS_JOB_NUMBER=\"4.1\")\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'travis')\n self.assertEqual(res['query']['commit'], 'c739768fcac68144a3a6d82305b9c4106934d31a')\n self.assertEqual(res['query']['build'], '4.1')\n self.assertEqual(res['query']['pr'], '')\n self.assertEqual(res['query']['tag'], 'v1.1.1')\n self.assertEqual(res['query']['slug'], 'owner/repo')\n self.assertEqual(res['query']['branch'], 'master')\n self.assertEqual(res['codecov'].token, '')", " @unittest.skipUnless(os.getenv('CI') == 'true' and os.getenv('CI_NAME') == 'codeship', 'Skip Codeship CI test')\n def test_ci_codeship(self):\n self.set_env(CI_NAME='codeship',\n CI_BRANCH='master',\n CI_BUILD_NUMBER='20',\n CI_BUILD_URL='https://codeship.io/build/1',\n CI_COMMIT_ID='743b04806ea677403aa2ff26c6bdeb85005de658',\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'codeship')\n self.assertEqual(res['query']['commit'], '743b04806ea677403aa2ff26c6bdeb85005de658')\n self.assertEqual(res['query']['build'], '20')\n self.assertEqual(res['query']['build_url'], 'https://codeship.io/build/1')\n self.assertEqual(res['query']['pr'], '')\n self.assertEqual(res['query']['branch'], 'master')\n self.assertEqual(res['codecov'].token, 'token')", " @unittest.skipUnless(os.getenv('CI') == 'true' and os.getenv('CIRCLECI') == 'true', 'Skip Circle CI test')\n def test_ci_circleci(self):\n self.set_env(CIRCLECI='true',\n CIRCLE_BUILD_NUM='57',\n CIRCLE_NODE_INDEX='1',\n CIRCLE_PR_NUMBER='1',\n CIRCLE_BRANCH='master',\n CIRCLE_PROJECT_USERNAME='owner',\n CIRCLE_PROJECT_REPONAME='repo',\n CIRCLE_SHA1='d653b934ed59c1a785cc1cc79d08c9aaa4eba73b')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'circleci')\n self.assertEqual(res['query']['commit'], 'd653b934ed59c1a785cc1cc79d08c9aaa4eba73b')\n self.assertEqual(res['query']['build'], '57.1')\n self.assertEqual(res['query']['pr'], '1')\n self.assertEqual(res['query']['slug'], 'owner/repo')\n self.assertEqual(res['query']['branch'], 'master')", " @unittest.skipUnless(os.getenv('CI') == 'true' and os.getenv('BUILDKITE') == 'true', 'Skip BuildKit CI test')\n def test_ci_buildkite(self):\n self.set_env(CI='true',\n BUILDKITE='true',\n BUILDKITE_BUILD_NUMBER='57',\n BUILDKITE_JOB_ID='1',\n BUILDKITE_BRANCH='master',\n BUILDKITE_PROJECT_SLUG='owner/repo',\n BUILDKITE_COMMIT='d653b934ed59c1a785cc1cc79d08c9aaa4eba73b',\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'buildkite')\n self.assertEqual(res['query']['commit'], 'd653b934ed59c1a785cc1cc79d08c9aaa4eba73b')\n self.assertEqual(res['query']['build'], '57.1')\n self.assertEqual(res['query']['slug'], 'owner/repo')\n self.assertEqual(res['query']['branch'], 'master')\n self.assertEqual(res['codecov'].token, 'token')", " @unittest.skipUnless(os.getenv('CI') == 'true' and os.getenv('SEMAPHORE') == 'true', 'Skip Semaphore CI test')\n def test_ci_semaphore(self):\n self.set_env(SEMAPHORE='true',\n BRANCH_NAME='master',\n SEMAPHORE_BUILD_NUMBER='10',\n SEMAPHORE_CURRENT_THREAD='1',\n SEMAPHORE_REPO_SLUG='owner/repo',\n REVISION='743b04806ea677403aa2ff26c6bdeb85005de658',\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'semaphore')\n self.assertEqual(res['query']['commit'], '743b04806ea677403aa2ff26c6bdeb85005de658')\n self.assertEqual(res['query']['build'], '10.1')\n self.assertEqual(res['query']['slug'], 'owner/repo')\n self.assertEqual(res['query']['branch'], 'master')", " @unittest.skipUnless(os.getenv('CI') == \"drone\" and os.getenv('DRONE') == \"true\", 'Skip Drone CI test')\n def test_ci_drone(self):\n self.set_env(CI='drone',\n DRONE='true',\n DRONE_BUILD_NUMBER='10',\n DRONE_BRANCH='master',\n DRONE_BUILD_LINK='https://drone.io/github/builds/1',\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'drone.io')\n self.assertEqual(res['query']['commit'], codecov.check_output((\"git\", \"rev-parse\", \"HEAD\")))\n self.assertEqual(res['query']['build'], '10')\n self.assertEqual(res['query']['build_url'], 'https://drone.io/github/builds/1')\n self.assertEqual(res['codecov'].token, 'token')", " @unittest.skipUnless(os.getenv('SHIPPABLE') == \"true\", 'Skip Shippable CI test')\n def test_ci_shippable(self):\n self.set_env(SHIPPABLE='true',\n BUILD_NUMBER='10',\n REPO_NAME='owner/repo',\n BRANCH='master',\n BUILD_URL='https://shippable.com/...',\n COMMIT='743b04806ea677403aa2ff26c6bdeb85005de658',\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'shippable')\n self.assertEqual(res['query']['commit'], '743b04806ea677403aa2ff26c6bdeb85005de658')\n self.assertEqual(res['query']['build'], '10')\n self.assertEqual(res['query']['slug'], 'owner/repo')\n self.assertEqual(res['query']['build_url'], 'https://shippable.com/...')\n self.assertEqual(res['codecov'].token, 'token')", " # @unittest.skipUnless(os.getenv('CI') == \"True\" and os.getenv('APPVEYOR') == 'True', 'Skip AppVeyor CI test')\n @unittest.skip('Skip AppVeyor test')\n def test_ci_appveyor(self):\n self.set_env(APPVEYOR='True',\n CI='True',\n APPVEYOR_JOB_ID='9r2qufuu8',\n APPVEYOR_BUILD_VERSION='1.2.3',\n APPVEYOR_ACCOUNT_NAME='owner',\n APPVEYOR_PROJECT_SLUG='repo',\n APPVEYOR_PULL_REQUEST_NUMBER='1',\n APPVEYOR_REPO_BRANCH='master',\n APPVEYOR_REPO_NAME='owner/repo',\n APPVEYOR_REPO_COMMIT='d653b934ed59c1a785cc1cc79d08c9aaa4eba73b',\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli(file=self.filepath)\n self.assertEqual(res['query']['service'], 'appveyor')\n self.assertEqual(res['query']['commit'], 'd653b934ed59c1a785cc1cc79d08c9aaa4eba73b')\n self.assertEqual(res['query']['job'], 'owner/repo/1.2.3')\n self.assertEqual(res['query']['build'], '9r2qufuu8')\n self.assertEqual(res['query']['slug'], 'owner/repo')\n self.assertEqual(res['query']['pr'], '1')\n self.assertEqual(res['codecov'].token, 'token')", " @unittest.skipUnless(os.getenv('CI') == \"true\" and os.getenv('WERCKER_GIT_BRANCH'), 'Skip Wercker CI test')\n def test_ci_wercker(self):\n self.set_env(WERCKER_GIT_BRANCH='master',\n WERCKER_MAIN_PIPELINE_STARTED='1399372237',\n WERCKER_GIT_OWNER='owner',\n WERCKER_GIT_REPOSITORY='repo',\n WERCKER_GIT_COMMIT='d653b934ed59c1a785cc1cc79d08c9aaa4eba73b',\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'wercker')\n self.assertEqual(res['query']['commit'], 'd653b934ed59c1a785cc1cc79d08c9aaa4eba73b')\n self.assertEqual(res['query']['build'], '1399372237')\n self.assertEqual(res['query']['slug'], 'owner/repo')\n self.assertEqual(res['codecov'].token, 'token')", " @unittest.skipUnless(os.getenv('CI') == \"true\" and os.getenv('MAGNUM') == 'true', 'Skip Magnum CI test')\n def test_ci_magnum(self):\n self.set_env(CI_BRANCH='master',\n CI_BUILD_NUMBER='1399372237',\n MAGNUM='true',\n CI='true',\n CI_COMMIT='d653b934ed59c1a785cc1cc79d08c9aaa4eba73b',\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'magnum')\n self.assertEqual(res['query']['commit'], 'd653b934ed59c1a785cc1cc79d08c9aaa4eba73b')\n self.assertEqual(res['query']['build'], '1399372237')\n self.assertEqual(res['codecov'].token, 'token')", " @unittest.skipUnless(os.getenv('CI_SERVER_NAME', '').startswith(\"GitLab\"), 'Skip GitLab CI test')\n def test_ci_gitlab(self):\n self.set_env(CI_BUILD_REF_NAME='master',\n CI_BUILD_ID='1399372237',\n CI_BUILD_REPO='https://gitlab.com/owner/repo.git',\n CI_SERVER_NAME='GitLab CI',\n CI_BUILD_REF='d653b934ed59c1a785cc1cc79d08c9aaa4eba73b',\n HOME='/',\n CI_PROJECT_DIR=os.getcwd().strip('/'),\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'gitlab')\n self.assertEqual(res['query']['commit'], 'd653b934ed59c1a785cc1cc79d08c9aaa4eba73b')\n self.assertEqual(res['query']['build'], '1399372237')\n self.assertEqual(res['query']['slug'], 'owner/repo')\n self.assertEqual(res['codecov'].token, 'token')", " @unittest.skip('Skip CI None')\n def test_ci_none(self):\n self.set_env(CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli(build=10,\n commit='d653b934ed59c1a785cc1cc79d08c9aaa4eba73b',\n slug='owner/repo',\n token='token')\n self.assertEqual(res['query'].get('service'), None)\n self.assertEqual(res['query']['commit'], 'd653b934ed59c1a785cc1cc79d08c9aaa4eba73b')\n self.assertEqual(res['query']['build'], '10')\n self.assertEqual(res['query']['slug'], 'owner/repo')\n self.assertEqual(res['codecov'].token, 'token')" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [632, 317], "buggy_code_start_loc": [35, 317], "filenames": ["codecov/__init__.py", "tests/test.py"], "fixing_code_end_loc": [636, 321], "fixing_code_start_loc": [36, 318], "message": "This affects the package codecov before 2.0.16. The vulnerability occurs due to not sanitizing gcov arguments before being being provided to the popen method.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:codecov:codecov-python:*:*:*:*:*:*:*:*", "matchCriteriaId": "2F99FFF5-0477-4713-8BBB-0A3113209F50", "versionEndExcluding": "2.0.16", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "This affects the package codecov before 2.0.16. The vulnerability occurs due to not sanitizing gcov arguments before being being provided to the popen method."}, {"lang": "es", "value": "Esto afecta al paquete codecov versiones anteriores a 2.0.16. La vulnerabilidad es producida debido a que no son saneados los argumentos de gcov antes de ser proporcionados al m\u00e9todo popen"}], "evaluatorComment": null, "id": "CVE-2019-10800", "lastModified": "2022-11-08T03:09:17.037", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "report@snyk.io", "type": "Secondary"}]}, "published": "2022-07-13T12:15:08.150", "references": [{"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codecov/codecov-python/commit/2a80aa434f74feb31242b6f213b75ce63ae97902"}, {"source": "report@snyk.io", "tags": ["Exploit", "Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-PYTHON-CODECOV-552149"}], "sourceIdentifier": "report@snyk.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-88"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/codecov/codecov-python/commit/2a80aa434f74feb31242b6f213b75ce63ae97902"}, "type": "CWE-88"}
199
Determine whether the {function_name} code is vulnerable or not.
[ "import os\nimport sys\nimport pickle\nimport itertools\nfrom ddt import ddt, data\nfrom mock import patch, Mock\nimport unittest", "import subprocess", "import codecov", "\n@ddt\nclass TestUploader(unittest.TestCase):\n maxDiff = None\n here = os.path.dirname(__file__)\n bowerrc = os.path.join(os.path.dirname(__file__), '../.bowerrc')\n token = os.path.join(os.path.dirname(__file__), '../.token')\n jacoco = os.path.join(os.path.dirname(__file__), '../jacoco.xml')\n filepath = os.path.join(os.path.dirname(__file__), 'coverage.xml')\n coverage = os.path.join(os.path.dirname(__file__), '../.coverage')\n defaults = dict(commit='a', branch='a', token='a')", " @classmethod\n def setUpClass(self):\n self._env = os.environ.copy()", " @classmethod\n def tearDownClass(self):\n os.environ = self._env", " def setUp(self):\n # set all environ back\n os.environ['CI'] = \"true\"\n for key in (\"TRAVIS\", \"TRAVIS_BRANCH\", \"TRAVIS_COMMIT\", \"TRAVIS_BUILD_DIR\", \"TRAVIS_JOB_ID\", \"TRAVIS_PULL_REQUEST\",\n \"CI_NAME\", \"CI_BRANCH\", \"CI_COMMIT_ID\", \"SHIPPABLE\",\n \"CI_BUILD_NUMBER\", \"MAGNUM\", \"CI_COMMIT\", \"APPVEYOR_ACCOUNT_NAME\", \"APPVEYOR_PROJECT_SLUG\", \"APPVEYOR_PULL_REQUEST_NUMBER\",\n \"CIRCLECI\", \"CIRCLE_BRANCH\", \"CIRCLE_ARTIFACTS\", \"CIRCLE_SHA1\", \"CIRCLE_NODE_INDEX\", \"CIRCLE_PR_NUMBER\",\n \"SEMAPHORE\", \"BRANCH_NAME\", \"SEMAPHORE_PROJECT_DIR\", \"REVISION\",\n \"BUILDKITE\", \"BUILDKITE_BUILD_NUMBER\", \"BUILDKITE_JOB_ID\", \"BUILDKITE_BRANCH\", \"BUILDKITE_PROJECT_SLUG\", \"BUILDKITE_COMMIT\",\n \"DRONE\", \"DRONE_BRANCH\", \"DRONE_BUILD_DIR\", \"JENKINS_URL\", \"TRAVIS_TAG\",\n \"GIT_BRANCH\", \"GIT_COMMIT\", \"WORKSPACE\", \"BUILD_NUMBER\", \"CI_BUILD_URL\", \"SEMAPHORE_REPO_SLUG\", \"SEMAPHORE_CURRENT_THREAD\",\n \"DRONE_BUILD_LINK\", \"TRAVIS_REPO_SLUG\", \"CODECOV_TOKEN\", \"APPVEYOR\", \"APPVEYOR_REPO_BRANCH\",\n \"APPVEYOR_BUILD_VERSION\", \"APPVEYOR_JOB_ID\", \"APPVEYOR_REPO_NAME\", \"APPVEYOR_REPO_COMMIT\", \"WERCKER_GIT_BRANCH\",\n \"WERCKER_MAIN_PIPELINE_STARTED\", \"WERCKER_GIT_OWNER\", \"WERCKER_GIT_REPOSITORY\",\n \"CI_BUILD_REF_NAME\", \"CI_BUILD_ID\", \"CI_BUILD_REPO\", \"CI_PROJECT_DIR\", \"CI_BUILD_REF\", \"CI_SERVER_NAME\",\n \"ghprbActualCommit\", \"ghprbSourceBranch\", \"ghprbPullId\", \"WERCKER_GIT_COMMIT\", \"CHANGE_ID\"):\n os.environ[key] = \"\"", " def tearDown(self):\n self.delete(self.filepath, self.coverage, self.jacoco, self.bowerrc)\n self.delete('hello', 'hello.c', 'hello.gcda', 'hello.c.gcov', 'hello.gcno')", " def set_env(self, **kwargs):\n for key in kwargs:\n os.environ[key] = str(kwargs[key])", " def run_cli(self, dump=True, *args, **kwargs):\n inline = list(itertools.chain(*[['--%s' % key, str(value)] for key, value in kwargs.items() if value]))\n if dump:\n inline.append('--dump')\n inline.extend(args)\n return codecov.main(*inline, debug=True)", " def fake_report(self):\n with open(self.filepath, 'w+') as f:\n f.write('__data__')", " def delete(self, *paths):\n for path in paths:\n if os.path.exists(path):\n os.remove(path)\n path = os.path.join(os.path.dirname(__file__), '../', path)\n if os.path.exists(path):\n os.remove(path)", " @data('vendor', 'node_modules', 'js/generated/coverage', '__pycache__', 'coverage/instrumented',\n 'build/lib', 'htmlcov', '.egg-info', '.git', '.tox', 'venv', '.venv-python-2.7')\n def test_ignored_path(self, path):\n self.assertTrue(bool(codecov.ignored_path('/home/ubuntu/' + path)), path + ' should be ignored')\n self.assertTrue(bool(codecov.ignored_path('/home/ubuntu/' + path + '/more paths')), path + ' should be ignored')", " @data('coverage.xml', 'jacoco.xml', 'jacocoTestResults.xml', 'coverage.txt',\n 'gcov.lst', 'cov.gcov', 'info.lcov', 'clover.xml', 'cobertura.xml',\n 'luacov.report.out', 'gcov.info', 'nosetests.xml')\n def test_is_report(self, path):\n self.assertFalse(bool(codecov.ignored_report('/home/file/' + path)), path + ' should not be ignored')\n self.assertTrue(bool(codecov.is_report('/home/file/' + path)), path + ' should be a report')", " @data('.coverage.worker10', 'coverage.jade', 'include.lst', 'inputFiles.lst',\n 'createdFiles.lst', 'scoverage.measurements.blackandwhite.xml', 'test_hello_coverage.txt',\n 'conftest_blackwhite.c.gcov')\n def test_ignore_report(self, path):\n self.assertTrue(bool(codecov.ignored_report('/home/file/' + path)), path + ' should be ignored')", " def test_command(self):\n try:\n self.run_cli(True, '--help')\n except SystemExit as e:\n self.assertEqual(str(e), '0')\n else:\n raise Exception(\"help not shown\")", " def test_exits_0(self):\n try:\n sys.argv = ['']\n codecov.main()\n except SystemExit as e:\n self.assertEqual(str(e), '0')\n else:\n raise Exception(\"did not exit\")", " def test_exits_1(self):\n try:\n sys.argv = ['']\n codecov.main('--required')\n except SystemExit as e:\n self.assertEqual(str(e), '1')\n else:\n raise Exception(\"did not exit\")", " @unittest.skipIf(os.getenv('CI') == \"True\" and os.getenv('APPVEYOR') == 'True', 'Skip AppVeyor CI test')\n def test_returns_none(self):\n with patch('requests.post') as post:\n with patch('requests.put') as put:\n post.return_value = Mock(status_code=200, text='target\\ns3')\n put.return_value = Mock(status_code=200)\n with open(self.filepath, 'w+') as f:\n f.write('coverage data')\n sys.argv = ['', '--commit=8ed84d96bc225deff66605486180cd555366806b',\n '--branch=master',\n '--token=473c8c5b-10ee-4d83-86c6-bfd72a185a27']\n self.assertEqual(codecov.main(), None)\n assert post.called and put.called", " @unittest.skipIf(os.getenv('CI') == \"True\" and os.getenv('APPVEYOR') == 'True', 'Skip AppVeyor CI test')\n def test_send(self):\n with patch('requests.post') as post:\n with patch('requests.put') as put:\n post.return_value = Mock(status_code=200, text='target\\ns3')\n put.return_value = Mock(status_code=200)\n with open(self.filepath, 'w+') as f:\n f.write('coverage data')\n res = self.run_cli(False, commit='a'*40, branch='master', token='<token>')\n self.assertEqual(res['result'].strip(), 'target')\n assert 'https://codecov.io/upload/v4?' in post.call_args[0][0]\n assert 'commit=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' in post.call_args[0][0]\n assert 'token=%3Ctoken%3E' in post.call_args[0][0]\n assert 'branch=master' in post.call_args[0][0]\n assert u'tests/test.py'.encode(\"utf-8\") in put.call_args[1]['data']", " def test_send_error(self):\n with patch('requests.post') as post:\n post.return_value = Mock(status_code=400, text='error')\n with open(self.filepath, 'w+') as f:\n f.write('coverage data')\n try:\n self.run_cli(False, token='not-a-token', commit='a'*40, branch='master')\n except Exception:\n pass\n else:\n raise Exception('400 never raised')", " @data((dict(commit='sha'), 'Missing repository upload token'), )\n def test_require_branch(self, dd):\n (kwargs, reason) = dd\n # this is so we dont get branch for local git\n self.set_env(JENKINS_URL='hello')\n try:\n self.run_cli(**kwargs)\n except AssertionError as e:\n self.assertEqual(str(e), reason)\n else:\n raise Exception(\"Did not raise AssertionError\")", " @unittest.skipIf(os.getenv('CI') == \"True\" and os.getenv('APPVEYOR') == 'True', 'Skip AppVeyor CI test')\n def test_read_token_file(self):\n with open(self.token, 'w+') as f:\n f.write('a')\n with open(self.filepath, 'w+') as f:\n f.write('coverage data')\n res = self.run_cli(token='@'+self.token, commit='a', branch='b')\n self.assertIn('token=a', res['urlargs'])", " def test_bowerrc(self):\n with open(self.bowerrc, 'w+') as f:\n f.write('{\"directory\": \"tests\"}')\n with open(self.filepath, 'w+') as f:\n f.write('coverage data')\n try:\n self.run_cli(**self.defaults)\n except AssertionError as e:\n self.assertEqual(str(e), \"No coverage report found\")\n else:\n raise Exception(\"Did not raise AssertionError\")", " def test_disable_search(self):\n self.fake_report()\n try:\n self.run_cli(disable='search', token='a', branch='b', commit='c')\n except AssertionError as e:\n self.assertEqual(str(e), \"No coverage report found\")\n else:\n raise Exception(\"Did not raise AssertionError\")", " @unittest.skipIf(os.getenv('CI') == \"True\" and os.getenv('APPVEYOR') == 'True', 'Skip AppVeyor CI test')\n def test_prefix(self):\n self.fake_report()\n res = self.run_cli(prefix='/foo/bar/', dump=True, token='a', branch='b', commit='c')\n assert '\\nfoo/bar/.gitignore' in res['reports']", " def write_c(self):\n c = '\\n'.join(('#include <stdio.h>',\n 'static int t = 1;'\n 'int main()', '{',\n 'if (t)', 'printf(\"on this line\\\\n\");',\n 'else', 'printf(\"but not here\\\\n\");',\n 'return 0;', '}'))\n with open(os.path.join(os.path.dirname(__file__), '../hello.c'), 'w+') as f:\n f.write(c)\n codecov.try_to_run('clang -coverage -O0 hello.c -o hello && ./hello')", " def test_disable_gcov(self):\n if self._env.get('TRAVIS') == 'true':\n self.write_c()\n try:\n self.run_cli(disable='gcov', token='a', branch='b', commit='c')\n except AssertionError as e:\n self.assertEqual(os.path.exists('hello.c.gcov'), False)\n self.assertEqual(str(e), \"No coverage report found\")\n else:\n raise Exception(\"Did not raise AssertionError\")\n else:\n self.skipTest(\"Skipped, works on Travis only.\")", " def test_gcov(self):\n self.skipTest(\"Need to fix this test...\")\n # if self._env.get('TRAVIS') == 'true':\n # self.write_c()\n # output = self.run_cli(token='a', branch='b', commit='c')\n # self.assertEqual(os.path.exists('hello.c.gcov'), True)\n # report = output['reports'].split('<<<<<< network\\n')[1].splitlines()\n # self.assertIn('hello.c.gcov', report[0])\n # else:\n # self.skipTest(\"Skipped, works on Travis only.\")", " def test_disable_detect(self):\n self.set_env(JENKINS_URL='a', GIT_BRANCH='b', GIT_COMMIT='c', CODECOV_TOKEN='d')\n self.fake_report()\n try:\n self.run_cli(disable='detect')\n except AssertionError as e:\n self.assertEqual(str(e), \"Commit sha is missing. Please specify via --commit=:sha\")\n else:\n raise Exception(\"Did not raise AssertionError\")", " @unittest.skipIf(os.getenv('CI') == \"True\" and os.getenv('APPVEYOR') == 'True', 'Skip AppVeyor CI test')\n def test_bowerrc_none(self):\n with open(self.bowerrc, 'w+') as f:\n f.write('{\"other_key\": \"tests\"}')\n with open(self.filepath, 'w+') as f:\n f.write('coverage data')\n res = self.run_cli(**self.defaults)\n self.assertIn('tests/test.py', res['reports'])", " @unittest.skipIf(os.getenv('CI') == \"True\" and os.getenv('APPVEYOR') == 'True', 'Skip AppVeyor CI test')\n def test_discovers(self):\n with open(self.jacoco, 'w+') as f:\n f.write('<jacoco></jacoco>')\n with open(self.filepath, 'w+') as f:\n f.write('coverage data')\n res = self.run_cli(**self.defaults)\n self.assertIn('coverage.xml', res['reports'])\n self.assertIn('coverage data', res['reports'])\n self.assertIn('jacoco.xml', res['reports'])\n self.assertIn('<jacoco></jacoco>', res['reports'])", " def test_not_jacoco(self):\n with open(self.filepath, 'w+') as f:\n f.write('<data>')\n res = self.run_cli(file='tests/coverage.xml', **self.defaults)\n res = res['reports'].split('<<<<<< network\\n')[1].splitlines()\n self.assertEqual(res[0], '# path=tests/coverage.xml')\n self.assertEqual(res[1], '<data>')", " def test_run_coverage(self):\n self.skipTest('Not sure how to pull off atm')\n with open(self.coverage, 'w+') as f:\n f.write(pickle.dumps())\n res = self.run_cli(**self.defaults)\n self.assertIn('<?xml version=\"1.0\" ?>', res['reports'])", " def test_run_coverage_fails(self):\n with open(self.coverage, 'w+') as f:\n f.write('bad data')\n try:\n self.run_cli(**self.defaults)\n except AssertionError as e:\n self.assertEqual(str(e), 'No coverage report found')\n else:\n raise Exception(\"Did not raise AssertionError\")", " def test_include_env(self):\n self.set_env(HELLO='WORLD')\n self.fake_report()\n res = self.run_cli(env='HELLO', file=self.filepath, **self.defaults)\n self.assertIn('HELLO=WORLD', res['reports'])", " def test_none_found(self):\n try:\n self.run_cli(**self.defaults)\n except AssertionError as e:\n self.assertEqual(str(e), \"No coverage report found\")\n else:\n raise Exception(\"Did not raise AssertionError\")\n", " def test_sanitize_arg(self):\n self.assertEqual(codecov.sanitize_arg('', '& echo test > vuln1.txt'), ' echo test > vuln1.txt')\n", " @unittest.skipUnless(os.getenv('JENKINS_URL'), 'Skip Jenkins CI test')\n def test_ci_jenkins(self):\n self.set_env(BUILD_URL='https://....',\n JENKINS_URL='https://....',\n GIT_BRANCH='master',\n GIT_COMMIT='c739768fcac68144a3a6d82305b9c4106934d31a',\n BUILD_NUMBER='41',\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'jenkins')\n self.assertEqual(res['query']['commit'], 'c739768fcac68144a3a6d82305b9c4106934d31a')\n self.assertEqual(res['query']['build'], '41')\n self.assertEqual(res['query']['build_url'], 'https://....')\n self.assertEqual(res['query']['pr'], '')\n self.assertEqual(res['query']['branch'], 'master')\n self.assertEqual(res['codecov'].token, 'token')", " @unittest.skipUnless(os.getenv('JENKINS_URL'), 'Skip Jenkins CI test')\n def test_ci_jenkins_env(self):\n self.set_env(JENKINS_URL='https://....',\n BUILD_URL='https://....',\n ghprbSourceBranch='master',\n ghprbActualCommit='c739768fcac68144a3a6d82305b9c4106934d31a',\n ghprbPullId='1',\n BUILD_NUMBER='41',\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'jenkins')\n self.assertEqual(res['query']['commit'], 'c739768fcac68144a3a6d82305b9c4106934d31a')\n self.assertEqual(res['query']['build'], '41')\n self.assertEqual(res['query']['build_url'], 'https://....')\n self.assertEqual(res['query']['pr'], '1')\n self.assertEqual(res['query']['branch'], 'master')\n self.assertEqual(res['codecov'].token, 'token')", " @unittest.skipUnless(os.getenv('JENKINS_URL'), 'Skip Jenkins CI test')\n def test_ci_jenkins_blue_ocean(self):\n self.set_env(JENKINS_URL='https://....',\n BUILD_URL='https://....',\n BRANCH_NAME='master',\n CHANGE_ID='1',\n BUILD_NUMBER='41',\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'jenkins')\n self.assertEqual(res['query']['commit'], codecov.check_output((\"git\", \"rev-parse\", \"HEAD\")))\n self.assertEqual(res['query']['build'], '41')\n self.assertEqual(res['query']['build_url'], 'https://....')\n self.assertEqual(res['query']['pr'], '1')\n self.assertEqual(res['query']['branch'], 'master')\n self.assertEqual(res['codecov'].token, 'token')", " @unittest.skipUnless(os.getenv('CI') == 'true'\n and os.getenv('TRAVIS') == \"true\"\n and os.getenv('SHIPPABLE') != 'true',\n 'Skip Travis CI test')\n def test_ci_travis(self):\n self.set_env(TRAVIS=\"true\",\n TRAVIS_BRANCH=\"master\",\n TRAVIS_COMMIT=\"c739768fcac68144a3a6d82305b9c4106934d31a\",\n TRAVIS_REPO_SLUG='owner/repo',\n TRAVIS_JOB_ID=\"33116958\",\n TRAVIS_TAG=\"v1.1.1\",\n TRAVIS_JOB_NUMBER=\"4.1\")\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'travis')\n self.assertEqual(res['query']['commit'], 'c739768fcac68144a3a6d82305b9c4106934d31a')\n self.assertEqual(res['query']['build'], '4.1')\n self.assertEqual(res['query']['pr'], '')\n self.assertEqual(res['query']['tag'], 'v1.1.1')\n self.assertEqual(res['query']['slug'], 'owner/repo')\n self.assertEqual(res['query']['branch'], 'master')\n self.assertEqual(res['codecov'].token, '')", " @unittest.skipUnless(os.getenv('CI') == 'true' and os.getenv('CI_NAME') == 'codeship', 'Skip Codeship CI test')\n def test_ci_codeship(self):\n self.set_env(CI_NAME='codeship',\n CI_BRANCH='master',\n CI_BUILD_NUMBER='20',\n CI_BUILD_URL='https://codeship.io/build/1',\n CI_COMMIT_ID='743b04806ea677403aa2ff26c6bdeb85005de658',\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'codeship')\n self.assertEqual(res['query']['commit'], '743b04806ea677403aa2ff26c6bdeb85005de658')\n self.assertEqual(res['query']['build'], '20')\n self.assertEqual(res['query']['build_url'], 'https://codeship.io/build/1')\n self.assertEqual(res['query']['pr'], '')\n self.assertEqual(res['query']['branch'], 'master')\n self.assertEqual(res['codecov'].token, 'token')", " @unittest.skipUnless(os.getenv('CI') == 'true' and os.getenv('CIRCLECI') == 'true', 'Skip Circle CI test')\n def test_ci_circleci(self):\n self.set_env(CIRCLECI='true',\n CIRCLE_BUILD_NUM='57',\n CIRCLE_NODE_INDEX='1',\n CIRCLE_PR_NUMBER='1',\n CIRCLE_BRANCH='master',\n CIRCLE_PROJECT_USERNAME='owner',\n CIRCLE_PROJECT_REPONAME='repo',\n CIRCLE_SHA1='d653b934ed59c1a785cc1cc79d08c9aaa4eba73b')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'circleci')\n self.assertEqual(res['query']['commit'], 'd653b934ed59c1a785cc1cc79d08c9aaa4eba73b')\n self.assertEqual(res['query']['build'], '57.1')\n self.assertEqual(res['query']['pr'], '1')\n self.assertEqual(res['query']['slug'], 'owner/repo')\n self.assertEqual(res['query']['branch'], 'master')", " @unittest.skipUnless(os.getenv('CI') == 'true' and os.getenv('BUILDKITE') == 'true', 'Skip BuildKit CI test')\n def test_ci_buildkite(self):\n self.set_env(CI='true',\n BUILDKITE='true',\n BUILDKITE_BUILD_NUMBER='57',\n BUILDKITE_JOB_ID='1',\n BUILDKITE_BRANCH='master',\n BUILDKITE_PROJECT_SLUG='owner/repo',\n BUILDKITE_COMMIT='d653b934ed59c1a785cc1cc79d08c9aaa4eba73b',\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'buildkite')\n self.assertEqual(res['query']['commit'], 'd653b934ed59c1a785cc1cc79d08c9aaa4eba73b')\n self.assertEqual(res['query']['build'], '57.1')\n self.assertEqual(res['query']['slug'], 'owner/repo')\n self.assertEqual(res['query']['branch'], 'master')\n self.assertEqual(res['codecov'].token, 'token')", " @unittest.skipUnless(os.getenv('CI') == 'true' and os.getenv('SEMAPHORE') == 'true', 'Skip Semaphore CI test')\n def test_ci_semaphore(self):\n self.set_env(SEMAPHORE='true',\n BRANCH_NAME='master',\n SEMAPHORE_BUILD_NUMBER='10',\n SEMAPHORE_CURRENT_THREAD='1',\n SEMAPHORE_REPO_SLUG='owner/repo',\n REVISION='743b04806ea677403aa2ff26c6bdeb85005de658',\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'semaphore')\n self.assertEqual(res['query']['commit'], '743b04806ea677403aa2ff26c6bdeb85005de658')\n self.assertEqual(res['query']['build'], '10.1')\n self.assertEqual(res['query']['slug'], 'owner/repo')\n self.assertEqual(res['query']['branch'], 'master')", " @unittest.skipUnless(os.getenv('CI') == \"drone\" and os.getenv('DRONE') == \"true\", 'Skip Drone CI test')\n def test_ci_drone(self):\n self.set_env(CI='drone',\n DRONE='true',\n DRONE_BUILD_NUMBER='10',\n DRONE_BRANCH='master',\n DRONE_BUILD_LINK='https://drone.io/github/builds/1',\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'drone.io')\n self.assertEqual(res['query']['commit'], codecov.check_output((\"git\", \"rev-parse\", \"HEAD\")))\n self.assertEqual(res['query']['build'], '10')\n self.assertEqual(res['query']['build_url'], 'https://drone.io/github/builds/1')\n self.assertEqual(res['codecov'].token, 'token')", " @unittest.skipUnless(os.getenv('SHIPPABLE') == \"true\", 'Skip Shippable CI test')\n def test_ci_shippable(self):\n self.set_env(SHIPPABLE='true',\n BUILD_NUMBER='10',\n REPO_NAME='owner/repo',\n BRANCH='master',\n BUILD_URL='https://shippable.com/...',\n COMMIT='743b04806ea677403aa2ff26c6bdeb85005de658',\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'shippable')\n self.assertEqual(res['query']['commit'], '743b04806ea677403aa2ff26c6bdeb85005de658')\n self.assertEqual(res['query']['build'], '10')\n self.assertEqual(res['query']['slug'], 'owner/repo')\n self.assertEqual(res['query']['build_url'], 'https://shippable.com/...')\n self.assertEqual(res['codecov'].token, 'token')", " # @unittest.skipUnless(os.getenv('CI') == \"True\" and os.getenv('APPVEYOR') == 'True', 'Skip AppVeyor CI test')\n @unittest.skip('Skip AppVeyor test')\n def test_ci_appveyor(self):\n self.set_env(APPVEYOR='True',\n CI='True',\n APPVEYOR_JOB_ID='9r2qufuu8',\n APPVEYOR_BUILD_VERSION='1.2.3',\n APPVEYOR_ACCOUNT_NAME='owner',\n APPVEYOR_PROJECT_SLUG='repo',\n APPVEYOR_PULL_REQUEST_NUMBER='1',\n APPVEYOR_REPO_BRANCH='master',\n APPVEYOR_REPO_NAME='owner/repo',\n APPVEYOR_REPO_COMMIT='d653b934ed59c1a785cc1cc79d08c9aaa4eba73b',\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli(file=self.filepath)\n self.assertEqual(res['query']['service'], 'appveyor')\n self.assertEqual(res['query']['commit'], 'd653b934ed59c1a785cc1cc79d08c9aaa4eba73b')\n self.assertEqual(res['query']['job'], 'owner/repo/1.2.3')\n self.assertEqual(res['query']['build'], '9r2qufuu8')\n self.assertEqual(res['query']['slug'], 'owner/repo')\n self.assertEqual(res['query']['pr'], '1')\n self.assertEqual(res['codecov'].token, 'token')", " @unittest.skipUnless(os.getenv('CI') == \"true\" and os.getenv('WERCKER_GIT_BRANCH'), 'Skip Wercker CI test')\n def test_ci_wercker(self):\n self.set_env(WERCKER_GIT_BRANCH='master',\n WERCKER_MAIN_PIPELINE_STARTED='1399372237',\n WERCKER_GIT_OWNER='owner',\n WERCKER_GIT_REPOSITORY='repo',\n WERCKER_GIT_COMMIT='d653b934ed59c1a785cc1cc79d08c9aaa4eba73b',\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'wercker')\n self.assertEqual(res['query']['commit'], 'd653b934ed59c1a785cc1cc79d08c9aaa4eba73b')\n self.assertEqual(res['query']['build'], '1399372237')\n self.assertEqual(res['query']['slug'], 'owner/repo')\n self.assertEqual(res['codecov'].token, 'token')", " @unittest.skipUnless(os.getenv('CI') == \"true\" and os.getenv('MAGNUM') == 'true', 'Skip Magnum CI test')\n def test_ci_magnum(self):\n self.set_env(CI_BRANCH='master',\n CI_BUILD_NUMBER='1399372237',\n MAGNUM='true',\n CI='true',\n CI_COMMIT='d653b934ed59c1a785cc1cc79d08c9aaa4eba73b',\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'magnum')\n self.assertEqual(res['query']['commit'], 'd653b934ed59c1a785cc1cc79d08c9aaa4eba73b')\n self.assertEqual(res['query']['build'], '1399372237')\n self.assertEqual(res['codecov'].token, 'token')", " @unittest.skipUnless(os.getenv('CI_SERVER_NAME', '').startswith(\"GitLab\"), 'Skip GitLab CI test')\n def test_ci_gitlab(self):\n self.set_env(CI_BUILD_REF_NAME='master',\n CI_BUILD_ID='1399372237',\n CI_BUILD_REPO='https://gitlab.com/owner/repo.git',\n CI_SERVER_NAME='GitLab CI',\n CI_BUILD_REF='d653b934ed59c1a785cc1cc79d08c9aaa4eba73b',\n HOME='/',\n CI_PROJECT_DIR=os.getcwd().strip('/'),\n CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli()\n self.assertEqual(res['query']['service'], 'gitlab')\n self.assertEqual(res['query']['commit'], 'd653b934ed59c1a785cc1cc79d08c9aaa4eba73b')\n self.assertEqual(res['query']['build'], '1399372237')\n self.assertEqual(res['query']['slug'], 'owner/repo')\n self.assertEqual(res['codecov'].token, 'token')", " @unittest.skip('Skip CI None')\n def test_ci_none(self):\n self.set_env(CODECOV_TOKEN='token')\n self.fake_report()\n res = self.run_cli(build=10,\n commit='d653b934ed59c1a785cc1cc79d08c9aaa4eba73b',\n slug='owner/repo',\n token='token')\n self.assertEqual(res['query'].get('service'), None)\n self.assertEqual(res['query']['commit'], 'd653b934ed59c1a785cc1cc79d08c9aaa4eba73b')\n self.assertEqual(res['query']['build'], '10')\n self.assertEqual(res['query']['slug'], 'owner/repo')\n self.assertEqual(res['codecov'].token, 'token')" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [632, 317], "buggy_code_start_loc": [35, 317], "filenames": ["codecov/__init__.py", "tests/test.py"], "fixing_code_end_loc": [636, 321], "fixing_code_start_loc": [36, 318], "message": "This affects the package codecov before 2.0.16. The vulnerability occurs due to not sanitizing gcov arguments before being being provided to the popen method.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:codecov:codecov-python:*:*:*:*:*:*:*:*", "matchCriteriaId": "2F99FFF5-0477-4713-8BBB-0A3113209F50", "versionEndExcluding": "2.0.16", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "This affects the package codecov before 2.0.16. The vulnerability occurs due to not sanitizing gcov arguments before being being provided to the popen method."}, {"lang": "es", "value": "Esto afecta al paquete codecov versiones anteriores a 2.0.16. La vulnerabilidad es producida debido a que no son saneados los argumentos de gcov antes de ser proporcionados al m\u00e9todo popen"}], "evaluatorComment": null, "id": "CVE-2019-10800", "lastModified": "2022-11-08T03:09:17.037", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "report@snyk.io", "type": "Secondary"}]}, "published": "2022-07-13T12:15:08.150", "references": [{"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/codecov/codecov-python/commit/2a80aa434f74feb31242b6f213b75ce63ae97902"}, {"source": "report@snyk.io", "tags": ["Exploit", "Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-PYTHON-CODECOV-552149"}], "sourceIdentifier": "report@snyk.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-88"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/codecov/codecov-python/commit/2a80aa434f74feb31242b6f213b75ce63ae97902"}, "type": "CWE-88"}
199
Determine whether the {function_name} code is vulnerable or not.
[ "/******************************************************\nCopyright (c) 2011-2013 Percona LLC and/or its affiliates.", "Streaming implementation for XtraBackup.", "This program is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; version 2 of the License.", "This program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.", "You should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA", "*******************************************************/", "#include <mysql_version.h>\n#include <my_base.h>\n#include \"common.h\"\n#include \"datasink.h\"\n#include \"xbstream.h\"", "typedef struct {\n\txb_wstream_t\t*xbstream;\n\tds_file_t\t*dest_file;\n\tpthread_mutex_t\tmutex;\n} ds_stream_ctxt_t;", "typedef struct {\n\txb_wstream_file_t\t*xbstream_file;\n\tds_stream_ctxt_t\t*stream_ctxt;\n} ds_stream_file_t;", "/***********************************************************************\nGeneral streaming interface */", "static ds_ctxt_t *xbstream_init(const char *root);\nstatic ds_file_t *xbstream_open(ds_ctxt_t *ctxt, const char *path,\n\t\t\t MY_STAT *mystat);\nstatic int xbstream_write(ds_file_t *file, const uchar *buf, size_t len);\nstatic int xbstream_close(ds_file_t *file);\nstatic void xbstream_deinit(ds_ctxt_t *ctxt);", "datasink_t datasink_xbstream = {\n\t&xbstream_init,\n\t&xbstream_open,\n\t&xbstream_write,\n\t&xbstream_close,\n\t&dummy_remove,\n\t&xbstream_deinit\n};", "static\nssize_t\nmy_xbstream_write_callback(xb_wstream_file_t *f __attribute__((unused)),\n\t\t void *userdata, const void *buf, size_t len)\n{\n\tds_stream_ctxt_t\t*stream_ctxt;", "\tstream_ctxt = (ds_stream_ctxt_t *) userdata;", "\txb_ad(stream_ctxt != NULL);\n\txb_ad(stream_ctxt->dest_file != NULL);", "\tif (!ds_write(stream_ctxt->dest_file, buf, len)) {\n\t\treturn len;\n\t}\n\treturn -1;\n}", "static\nds_ctxt_t *\nxbstream_init(const char *root __attribute__((unused)))\n{\n\tds_ctxt_t\t\t*ctxt;\n\tds_stream_ctxt_t\t*stream_ctxt;\n\txb_wstream_t *xbstream;", "\tctxt = (ds_ctxt_t *)my_malloc(sizeof(ds_ctxt_t) + sizeof(ds_stream_ctxt_t),\n\t\t\t MYF(MY_FAE));\n\tstream_ctxt = (ds_stream_ctxt_t *)(ctxt + 1);", "\tif (pthread_mutex_init(&stream_ctxt->mutex, NULL)) {\n\t\tmsg(\"xbstream_init: pthread_mutex_init() failed.\");\n\t\tgoto err;\n\t}", "\txbstream = xb_stream_write_new();\n\tif (xbstream == NULL) {\n\t\tmsg(\"xb_stream_write_new() failed.\");\n\t\tgoto err;\n\t}\n\tstream_ctxt->xbstream = xbstream;\n\tstream_ctxt->dest_file = NULL;", "\tctxt->ptr = stream_ctxt;", "\treturn ctxt;", "err:\n\tmy_free(ctxt);\n\treturn NULL;\n}", "static\nds_file_t *\nxbstream_open(ds_ctxt_t *ctxt, const char *path, MY_STAT *mystat)\n{\n\tds_file_t\t\t*file;\n\tds_stream_file_t\t*stream_file;\n\tds_stream_ctxt_t\t*stream_ctxt;\n\tds_ctxt_t\t\t*dest_ctxt;\n\txb_wstream_t\t\t*xbstream;\n\txb_wstream_file_t\t*xbstream_file;", "\n\txb_ad(ctxt->pipe_ctxt != NULL);\n\tdest_ctxt = ctxt->pipe_ctxt;", "\tstream_ctxt = (ds_stream_ctxt_t *) ctxt->ptr;", "\tpthread_mutex_lock(&stream_ctxt->mutex);\n\tif (stream_ctxt->dest_file == NULL) {\n\t\tstream_ctxt->dest_file = ds_open(dest_ctxt, path, mystat);", "\t\tif (stream_ctxt->dest_file == NULL) {\n\t\t\treturn NULL;\n\t\t}", "\t}\n\tpthread_mutex_unlock(&stream_ctxt->mutex);", "", "\n\tfile = (ds_file_t *) my_malloc(sizeof(ds_file_t) +\n\t\t\t\t sizeof(ds_stream_file_t),\n\t\t\t\t MYF(MY_FAE));", "", "\tstream_file = (ds_stream_file_t *) (file + 1);", "\txbstream = stream_ctxt->xbstream;", "\txbstream_file = xb_stream_write_open(xbstream, path, mystat,\n\t\t stream_ctxt,\n\t\t\t\t\t my_xbstream_write_callback);", "\tif (xbstream_file == NULL) {\n\t\tmsg(\"xb_stream_write_open() failed.\");\n\t\tgoto err;\n\t}", "\tstream_file->xbstream_file = xbstream_file;\n\tstream_file->stream_ctxt = stream_ctxt;\n\tfile->ptr = stream_file;\n\tfile->path = stream_ctxt->dest_file->path;", "\treturn file;", "err:\n\tif (stream_ctxt->dest_file) {\n\t\tds_close(stream_ctxt->dest_file);\n\t\tstream_ctxt->dest_file = NULL;\n\t}\n\tmy_free(file);", "\treturn NULL;\n}", "static\nint\nxbstream_write(ds_file_t *file, const uchar *buf, size_t len)\n{\n\tds_stream_file_t\t*stream_file;\n\txb_wstream_file_t\t*xbstream_file;", "\n\tstream_file = (ds_stream_file_t *) file->ptr;", "\txbstream_file = stream_file->xbstream_file;", "\tif (xb_stream_write_data(xbstream_file, buf, len)) {\n\t\tmsg(\"xb_stream_write_data() failed.\");\n\t\treturn 1;\n\t}", "\treturn 0;\n}", "static\nint\nxbstream_close(ds_file_t *file)\n{\n\tds_stream_file_t\t*stream_file;\n\tint\t\t\trc = 0;", "\tstream_file = (ds_stream_file_t *)file->ptr;", "\trc = xb_stream_write_close(stream_file->xbstream_file);", "\tmy_free(file);", "\treturn rc;\n}", "static\nvoid\nxbstream_deinit(ds_ctxt_t *ctxt)\n{\n\tds_stream_ctxt_t\t*stream_ctxt;", "\tstream_ctxt = (ds_stream_ctxt_t *) ctxt->ptr;", "\tif (xb_stream_write_done(stream_ctxt->xbstream)) {\n\t\tmsg(\"xb_stream_done() failed.\");\n\t}", "\tif (stream_ctxt->dest_file) {\n\t\tds_close(stream_ctxt->dest_file);\n\t\tstream_ctxt->dest_file = NULL;\n\t}", "\tpthread_mutex_destroy(&stream_ctxt->mutex);", "\tmy_free(ctxt);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [137], "buggy_code_start_loc": [129], "filenames": ["extra/mariabackup/ds_xbstream.cc"], "fixing_code_end_loc": [142], "fixing_code_start_loc": [128], "message": "MariaDB Server before 10.7 is vulnerable to Denial of Service. In extra/mariabackup/ds_xbstream.cc, when an error occurs (stream_ctxt->dest_file == NULL) while executing the method xbstream_open, the held lock is not released correctly, which allows local users to trigger a denial of service due to the deadlock.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mariadb:mariadb:*:*:*:*:*:*:*:*", "matchCriteriaId": "0A447A17-E295-4F60-AC74-E04F843E9FE8", "versionEndExcluding": "10.2.41", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mariadb:mariadb:*:*:*:*:*:*:*:*", "matchCriteriaId": "705DFD55-1C4B-41E3-BD84-EE76F9B497E2", "versionEndExcluding": "10.3.32", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "10.3.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:mariadb:mariadb:*:*:*:*:*:*:*:*", "matchCriteriaId": "A8F611A5-866A-4E49-9689-0A47B05FA738", "versionEndExcluding": "10.4.22", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "10.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:mariadb:mariadb:*:*:*:*:*:*:*:*", "matchCriteriaId": "0A15558C-2B98-4AA5-9775-A1A4374D7BD6", "versionEndExcluding": "10.5.13", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "10.5.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:mariadb:mariadb:*:*:*:*:*:*:*:*", "matchCriteriaId": "73DE2000-2CBA-4811-AD1F-F6EB3B9E4556", "versionEndExcluding": "10.6.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "10.6.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "MariaDB Server before 10.7 is vulnerable to Denial of Service. In extra/mariabackup/ds_xbstream.cc, when an error occurs (stream_ctxt->dest_file == NULL) while executing the method xbstream_open, the held lock is not released correctly, which allows local users to trigger a denial of service due to the deadlock."}, {"lang": "es", "value": "MariaDB Server versiones anteriores a 10.7, es vulnerable a una denegaci\u00f3n de servicio. En el archivo xtra/mariabackup/ds_xbstream.cc, cuando es producido un error (stream_ctxt-)dest_file == NULL) mientras es ejecutado el m\u00e9todo xbstream_open, el bloqueo mantenido no es liberado correctamente, lo que permite a usuarios locales desencadenar una denegaci\u00f3n de servicio debido al bloqueo"}], "evaluatorComment": null, "id": "CVE-2022-31621", "lastModified": "2022-11-05T01:55:18.800", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 2.1, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-05-25T21:15:08.573", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/MariaDB/server/commit/b1351c15946349f9daa7e5297fb2ac6f3139e4a8"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Permissions Required", "Third Party Advisory"], "url": "https://jira.mariadb.org/browse/MDEV-26574?filter=-2"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.netapp.com/advisory/ntap-20220707-0006/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-667"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/MariaDB/server/commit/b1351c15946349f9daa7e5297fb2ac6f3139e4a8"}, "type": "CWE-667"}
200
Determine whether the {function_name} code is vulnerable or not.
[ "/******************************************************\nCopyright (c) 2011-2013 Percona LLC and/or its affiliates.", "Streaming implementation for XtraBackup.", "This program is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; version 2 of the License.", "This program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.", "You should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA", "*******************************************************/", "#include <mysql_version.h>\n#include <my_base.h>\n#include \"common.h\"\n#include \"datasink.h\"\n#include \"xbstream.h\"", "typedef struct {\n\txb_wstream_t\t*xbstream;\n\tds_file_t\t*dest_file;\n\tpthread_mutex_t\tmutex;\n} ds_stream_ctxt_t;", "typedef struct {\n\txb_wstream_file_t\t*xbstream_file;\n\tds_stream_ctxt_t\t*stream_ctxt;\n} ds_stream_file_t;", "/***********************************************************************\nGeneral streaming interface */", "static ds_ctxt_t *xbstream_init(const char *root);\nstatic ds_file_t *xbstream_open(ds_ctxt_t *ctxt, const char *path,\n\t\t\t MY_STAT *mystat);\nstatic int xbstream_write(ds_file_t *file, const uchar *buf, size_t len);\nstatic int xbstream_close(ds_file_t *file);\nstatic void xbstream_deinit(ds_ctxt_t *ctxt);", "datasink_t datasink_xbstream = {\n\t&xbstream_init,\n\t&xbstream_open,\n\t&xbstream_write,\n\t&xbstream_close,\n\t&dummy_remove,\n\t&xbstream_deinit\n};", "static\nssize_t\nmy_xbstream_write_callback(xb_wstream_file_t *f __attribute__((unused)),\n\t\t void *userdata, const void *buf, size_t len)\n{\n\tds_stream_ctxt_t\t*stream_ctxt;", "\tstream_ctxt = (ds_stream_ctxt_t *) userdata;", "\txb_ad(stream_ctxt != NULL);\n\txb_ad(stream_ctxt->dest_file != NULL);", "\tif (!ds_write(stream_ctxt->dest_file, buf, len)) {\n\t\treturn len;\n\t}\n\treturn -1;\n}", "static\nds_ctxt_t *\nxbstream_init(const char *root __attribute__((unused)))\n{\n\tds_ctxt_t\t\t*ctxt;\n\tds_stream_ctxt_t\t*stream_ctxt;\n\txb_wstream_t *xbstream;", "\tctxt = (ds_ctxt_t *)my_malloc(sizeof(ds_ctxt_t) + sizeof(ds_stream_ctxt_t),\n\t\t\t MYF(MY_FAE));\n\tstream_ctxt = (ds_stream_ctxt_t *)(ctxt + 1);", "\tif (pthread_mutex_init(&stream_ctxt->mutex, NULL)) {\n\t\tmsg(\"xbstream_init: pthread_mutex_init() failed.\");\n\t\tgoto err;\n\t}", "\txbstream = xb_stream_write_new();\n\tif (xbstream == NULL) {\n\t\tmsg(\"xb_stream_write_new() failed.\");\n\t\tgoto err;\n\t}\n\tstream_ctxt->xbstream = xbstream;\n\tstream_ctxt->dest_file = NULL;", "\tctxt->ptr = stream_ctxt;", "\treturn ctxt;", "err:\n\tmy_free(ctxt);\n\treturn NULL;\n}", "static\nds_file_t *\nxbstream_open(ds_ctxt_t *ctxt, const char *path, MY_STAT *mystat)\n{\n\tds_file_t\t\t*file;\n\tds_stream_file_t\t*stream_file;\n\tds_stream_ctxt_t\t*stream_ctxt;\n\tds_ctxt_t\t\t*dest_ctxt;\n\txb_wstream_t\t\t*xbstream;\n\txb_wstream_file_t\t*xbstream_file;", "\n\txb_ad(ctxt->pipe_ctxt != NULL);\n\tdest_ctxt = ctxt->pipe_ctxt;", "\tstream_ctxt = (ds_stream_ctxt_t *) ctxt->ptr;", "\tpthread_mutex_lock(&stream_ctxt->mutex);\n\tif (stream_ctxt->dest_file == NULL) {\n\t\tstream_ctxt->dest_file = ds_open(dest_ctxt, path, mystat);", "", "\t}\n\tpthread_mutex_unlock(&stream_ctxt->mutex);", "\tif (stream_ctxt->dest_file == NULL) {\n\t\treturn NULL;\n\t}", "\n\tfile = (ds_file_t *) my_malloc(sizeof(ds_file_t) +\n\t\t\t\t sizeof(ds_stream_file_t),\n\t\t\t\t MYF(MY_FAE));", "\tif (!file) {\n\t\tmsg(\"my_malloc() failed.\");\n\t\tgoto err;\n\t}", "\tstream_file = (ds_stream_file_t *) (file + 1);", "\txbstream = stream_ctxt->xbstream;", "\txbstream_file = xb_stream_write_open(xbstream, path, mystat,\n\t\t stream_ctxt,\n\t\t\t\t\t my_xbstream_write_callback);", "\tif (xbstream_file == NULL) {\n\t\tmsg(\"xb_stream_write_open() failed.\");\n\t\tgoto err;\n\t}", "\tstream_file->xbstream_file = xbstream_file;\n\tstream_file->stream_ctxt = stream_ctxt;\n\tfile->ptr = stream_file;\n\tfile->path = stream_ctxt->dest_file->path;", "\treturn file;", "err:\n\tif (stream_ctxt->dest_file) {\n\t\tds_close(stream_ctxt->dest_file);\n\t\tstream_ctxt->dest_file = NULL;\n\t}\n\tmy_free(file);", "\treturn NULL;\n}", "static\nint\nxbstream_write(ds_file_t *file, const uchar *buf, size_t len)\n{\n\tds_stream_file_t\t*stream_file;\n\txb_wstream_file_t\t*xbstream_file;", "\n\tstream_file = (ds_stream_file_t *) file->ptr;", "\txbstream_file = stream_file->xbstream_file;", "\tif (xb_stream_write_data(xbstream_file, buf, len)) {\n\t\tmsg(\"xb_stream_write_data() failed.\");\n\t\treturn 1;\n\t}", "\treturn 0;\n}", "static\nint\nxbstream_close(ds_file_t *file)\n{\n\tds_stream_file_t\t*stream_file;\n\tint\t\t\trc = 0;", "\tstream_file = (ds_stream_file_t *)file->ptr;", "\trc = xb_stream_write_close(stream_file->xbstream_file);", "\tmy_free(file);", "\treturn rc;\n}", "static\nvoid\nxbstream_deinit(ds_ctxt_t *ctxt)\n{\n\tds_stream_ctxt_t\t*stream_ctxt;", "\tstream_ctxt = (ds_stream_ctxt_t *) ctxt->ptr;", "\tif (xb_stream_write_done(stream_ctxt->xbstream)) {\n\t\tmsg(\"xb_stream_done() failed.\");\n\t}", "\tif (stream_ctxt->dest_file) {\n\t\tds_close(stream_ctxt->dest_file);\n\t\tstream_ctxt->dest_file = NULL;\n\t}", "\tpthread_mutex_destroy(&stream_ctxt->mutex);", "\tmy_free(ctxt);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [137], "buggy_code_start_loc": [129], "filenames": ["extra/mariabackup/ds_xbstream.cc"], "fixing_code_end_loc": [142], "fixing_code_start_loc": [128], "message": "MariaDB Server before 10.7 is vulnerable to Denial of Service. In extra/mariabackup/ds_xbstream.cc, when an error occurs (stream_ctxt->dest_file == NULL) while executing the method xbstream_open, the held lock is not released correctly, which allows local users to trigger a denial of service due to the deadlock.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mariadb:mariadb:*:*:*:*:*:*:*:*", "matchCriteriaId": "0A447A17-E295-4F60-AC74-E04F843E9FE8", "versionEndExcluding": "10.2.41", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:mariadb:mariadb:*:*:*:*:*:*:*:*", "matchCriteriaId": "705DFD55-1C4B-41E3-BD84-EE76F9B497E2", "versionEndExcluding": "10.3.32", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "10.3.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:mariadb:mariadb:*:*:*:*:*:*:*:*", "matchCriteriaId": "A8F611A5-866A-4E49-9689-0A47B05FA738", "versionEndExcluding": "10.4.22", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "10.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:mariadb:mariadb:*:*:*:*:*:*:*:*", "matchCriteriaId": "0A15558C-2B98-4AA5-9775-A1A4374D7BD6", "versionEndExcluding": "10.5.13", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "10.5.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:mariadb:mariadb:*:*:*:*:*:*:*:*", "matchCriteriaId": "73DE2000-2CBA-4811-AD1F-F6EB3B9E4556", "versionEndExcluding": "10.6.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "10.6.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "MariaDB Server before 10.7 is vulnerable to Denial of Service. In extra/mariabackup/ds_xbstream.cc, when an error occurs (stream_ctxt->dest_file == NULL) while executing the method xbstream_open, the held lock is not released correctly, which allows local users to trigger a denial of service due to the deadlock."}, {"lang": "es", "value": "MariaDB Server versiones anteriores a 10.7, es vulnerable a una denegaci\u00f3n de servicio. En el archivo xtra/mariabackup/ds_xbstream.cc, cuando es producido un error (stream_ctxt-)dest_file == NULL) mientras es ejecutado el m\u00e9todo xbstream_open, el bloqueo mantenido no es liberado correctamente, lo que permite a usuarios locales desencadenar una denegaci\u00f3n de servicio debido al bloqueo"}], "evaluatorComment": null, "id": "CVE-2022-31621", "lastModified": "2022-11-05T01:55:18.800", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 2.1, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-05-25T21:15:08.573", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/MariaDB/server/commit/b1351c15946349f9daa7e5297fb2ac6f3139e4a8"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Permissions Required", "Third Party Advisory"], "url": "https://jira.mariadb.org/browse/MDEV-26574?filter=-2"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.netapp.com/advisory/ntap-20220707-0006/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-667"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/MariaDB/server/commit/b1351c15946349f9daa7e5297fb2ac6f3139e4a8"}, "type": "CWE-667"}
200
Determine whether the {function_name} code is vulnerable or not.
[ "# Changes in HTMLDOC v1.9.12", "- Fixed a crash bug with \"data:\" URIs and EPUB output (Issue #410)", "- Fixed JPEG error handling (Issue #415)", "- Fixed crash bugs with bogus table attributes (Issue #416, Issue #417)\n- Fixed a crash bug with malformed URIs (Issue #418)\n- Fixed a crash bug with malformed GIF files (Issue #423)\n- Fixed some issues reported by Coverity.", "\n# Changes in HTMLDOC v1.9.11", "- Added high-resolution desktop icons for Linux.\n- Updated the internal HTTP library to fix truncation of redirection URLs\n (Issue #396)\n- Fixed a regression in the handling of character entities for UTF-8 input\n (Issue #401)\n- The `--numbered` option did not work when the table-of-contents was disabled\n (Issue #405)", "\n# Changes in HTMLDOC v1.9.10", "- Updated local zlib to v1.2.11.\n- Updated local libpng to v1.6.37.\n- Fixed packaging issues on macOS and Windows (Issue #377, Issue #386)\n- Now ignore sRGB profile errors in PNG files (Issue #390)\n- The GUI would crash when saving (Issue #391)\n- Page comments are now allowed in `pre` text (Issue #394)", "\n# Changes in HTMLDOC v1.9.9", "- Fixed a redirection issue - some sites (incorrectly) provide an incomplete\n Location: URL in the HTTP response.\n- Fixed https: support on newer versions of Windows (Issue #378)\n- Fixed a problem with remote URLs containing spaces (Issue #379)\n- Fixed a UTF-8 processing bug for Markdown files (Issue #383)\n- Added support for `<FONT FACE=\"monospace\">` (Issue #385)", "\n# Changes in HTMLDOC v1.9.8", "- Added support for a `HTMLDOC.filename` META keyword that controls the filename\n reported in CGI mode; the default remains \"htmldoc.pdf\" (Issue #367)\n- Fixed a paragraph formatting issue with large inline images (Issue #369)\n- Fixed a buffer underflow issue (Issue #370)\n- Fixed PDF page numbers (Issue #371)\n- Added support for a new `L` header/footer format (`$LETTERHEAD`), which\n inserts a letterhead image at its full size (Issue #372, Issue #373,\n Issue #375)\n- Updated the build documentation (Issue #374)", "\n# Changes in HTMLDOC v1.9.7", "- Refactored the PRE rendering code to work around compiler optimization bugs\n (Issue #349)\n- Added support for links with targets (Issue #351)\n- Fixed a table rowspan + valign bug (Issue #360)", "\n# Changes in HTMLDOC v1.9.6", "- Added support for data URIs (Issue #340)\n- HTMLDOC no longer includes a PDF table of contents when converting a single\n web page (Issue #344)\n- Updated the markdown support with external links, additional inline markup,\n and hard line breaks.\n- Links in markdown text no longer render with a leading space as part of the\n link (Issue #346)\n- Fixed a buffer underflow bug discovered by AddressSanitizer.\n- Fixed a bug in UTF-8 support (Issue #348)\n- PDF output now includes the base language of the input document(s)\n (Issue #350)\n- Optimized the loading of font widths (Issue #354)\n- Optimized PDF page resources (Issue #356)\n- Optimized the base memory used for font widths (Issue #357)\n- Added proper `&shy;` support (Issue #361)\n- Title files can now be markdown.", "\n# Changes in HTMLDOC v1.9.5", "- The GUI did not support EPUB output.\n- Empty markdown table cells were not rendered in PDF or PostScript output.\n- The automatically-generated title page now supports both \"docnumber\" and\n \"version\" metadata.\n- Added support for dc:subject and dc:language metadata in EPUB output from the\n HTML keywords and lang values.\n- Added support for the subject and language metadata in markdown input.\n- Fixed a buffer underflow bug (Issue #338)\n- `htmldoc --help` now reports whether HTTPS URLs are supported (Issue #339)\n- Fixed an issue with HTML title pages and EPUB output.", "\n# Changes in HTMLDOC v1.9.4", "- Inline fixed-width text is no longer reduced in size automatically\n (Issue #309)\n- Optimized initialization of font width data (Issue #334)", "\n# Changes in HTMLDOC v1.9.3", "- Fixed formatting bugs with aligned images (Issue #322, Issue #324)\n- Fixed support for three digit \"#RGB\" color values (Issue #323)\n- Fixed character set support for markdown metadata.\n- Updated libpng to v1.6.34 (Issue #326)\n- The makefiles did not use the CPPFLAGS value (Issue #328)", "\n# Changes in HTMLDOC v1.9.2", "- Added Markdown table support.\n- Fixed parsing of TBODY, TFOOT, and THEAD elements in HTML files.", "\n# Changes in HTMLDOC v1.9.1", "- Fixed monospace font size issue (Issue #309)\n- Added support for reproducible builds (Issue #310)\n- Added limited support for the HTML 4.0 SPAN element (Issue #311)\n- Added (extremely limited) UTF-8 support for input files (Issue #314)\n- Fixed buffer underflow for (invalid) short HTML comments (Issue #316)\n- Now indent PRE text, by popular request.\n- EPUB output now makes sure that `<element property>` is written as\n `<element property=\"property\">`.\n- Now support both NAME and ID for table-of-contents targets.", "\n# Changes in HTMLDOC v1.9", "- Added support for repeating a single header row for tables that span multiple\n pages (Issue #16)\n- Added support for embedding the current filename/URL in the header or footer\n (Issue #50)\n- Added EPUB support (Issue #301)\n- Added Markdown support (Issue #302)\n- Fixed a regression in header/footer image scaling (Issue #303)\n- Documentation updates (Issue #305)\n- Compiler fixes (Issue #304, Issue #306)\n- Fixed a bug when running HTMLDOC as a macOS application.\n- Updated the bundled libpng to v1.6.29.", "\n# Changes in HTMLDOC v1.8.30", "- Updated documentation to reflect new project page on Github.\n- Dropped old CDE and IRIX desktop integration files.\n- Cleaned up the GUI and adopted new default text editors for Linux and macOS.\n- PAGE BREAK comments at the end of a file in web page mode would lose the\n first page (Issue #251)\n- Fixed the scaling of header/footer images to limit them to the height of the\n header or footer (Issue #273)\n- Fixed an issue with the top-level makefile not exiting with an error as\n needed (Issue #282)\n- Fixed a URL referencing bug when the same hostname but a different port was\n used (Issue #290)\n- Fixed build issue on macOS (Issue #291)\n- Fixed handling of indexed+alpha PNG images (Issue #295)", "\n# Changes in HTMLDOC v1.8.29", "- Updated local PNG library to version 1.6.20.\n- Updated local JPEG library to version 9b.\n- Dropped support for OpenSSL.\n- Added configure script support for libjpeg-turbo.\n- Updated HTTP code to latest CUPS/ippsample sources.\n- Duplex PDF output incorrectly forced an even number of pages\n- The table of contents showed the wrong page numbers after headings containing\n the \"_HD_OMIT_TOC\" attribute.\n- Fixed reported build issues\n- The configure script's --enable-local* options did not work.", "\n# Changes in HTMLDOC v1.8.28", "- Updated local zlib to version 1.2.8.\n- Updated local PNG library to version 1.6.8.\n- Updated local JPEG library to version 9.\n- Updated default PDF version to 1.4.\n- SECURITY: Fixed three buffer overflow issues when reading AFM files and\n parsing page sizes.\n- Fixed incompatibility with Fortify's version of strcpy, which does not work\n properly with variable-length arrays\n- Fixed compilation against PNG library 1.5 or later\n- Fixed documentation errors\n- Marked Zapf-Dingbats as a standard font\n- Fixed GPL license text in GUI\n- Fixed a table formatting problem when a column has multiple colspan values\n- Fixed parsing of HTML comments\n- Fixed potential out-of-bounds read in table-of-contents rendering code\n- Fixed handling of image URLs with ampersands in them\n- Fixed top/bottom margins for logo and header/footer images\n- Fixed image alignment bug\n- Fixed X11 build problem", "\n# Changes in HTMLDOC v1.8.27", "- Fixed a crash bug that appeared when more than 10 blank pages were present in\n a document\n- Color changes were not reflected in PRE text\n- Remote URLs did not always work on older operating systems\n- Image filenames using % escapes were not decoded properly.\n- Rows using BGCOLOR that spanned across multiple pages did not render properly\n- Rows no longer start on a new page due to a cell with both HEIGHT and ROWSPAN\n specified\n- CMYK JPEG images caused HTMLDOC to crash\n- Table cell width calculations didn't always account for the proper minimum\n width\n- Images were not copied when generating indexed HTML output to a directory\n- Changing the bottom margin resulted in text that was formatted below the\n bottom margin.\n- The Monospace-Oblique font was not embedded properly in PDF files.", "\n# Changes in HTMLDOC v1.8.26", "- Outline and keyword strings in PDF files are now stored as Unicode\n- The Flate compression code could get in an infinite loop if it ran out of\n memory\n- Book files saved from the GUI did not handle filenames with spaces\n- Fixed and re-enabled the ASCII85Device filter support in PostScript Level 2/3\n output\n- Character entities in the first word of a file were not rendered properly\n- Fixed-size table columns were incorrectly resized when a table width was also\n specified and there was extra space to distribute\n- Text could \"walk\" up or down when in-line images were used\n- Row backgrounds incorrectly replaced cell backgrounds when the first cell in a\n row used ROWSPAN\n- HTMLDOC did not correctly parse FONT FACE attributes\n- Images in Level 2/3 PostScript output did not work on some printers\n- The GUI did not use the first page header", "\n# Changes in HTMLDOC v1.8.25", "- Added \"--overflow\" and \"--no-overflow\" command-line options to show or hide\n the content-too-large errors; the default is \"--no-overflow\".\n- Added \"--header1\" command-line option and \"HEADER1\" page comments to set the\n page header for the first page of each chapter.\n- Added \"timing\" and \"remotebytes\" debug data generation.\n- Added DejaVu font collection to better support Cyrillic and Greek text; the\n new fonts are available under the generic names \"monospace\", \"sans\", and\n \"serif\".\n- Added \"--referer\" command-line option and corresponding CGI-mode support to\n pass Referer: information in HTTP requests\n- On Windows, HTMLDOC now logs CGI mode errors to a file called \"htmldoc.log\" in\n the Windows temporary directory.\n- HTMLDOC no longer uses Base-85 encoding for image data when producing Level 2\n and 3 PostScript output. It appears that many printers and PostScript\n interpreters cannot properly decode this data when the original image data is\n not a multiple of 8 bits.\n- HTMLDOC now renders STRONG elements in boldface instead of bold-italic to\n match the W3C recommendations.\n- HTMLDOC now automatically inserts a TR element before a TD or TH element as\n needed to improve web site compatibility; this also triggers a HTML error in\n --strict mode.\n- \"$HFIMAGEn\" didn't work in a header/footer string.\n- HTMLDOC could crash when rendering a table.\n- Book files were not used in CGI mode\n- Cookies were not sent in HTTP requests\n- Table cells were not aligned properly when the ROWSPAN attribute was set to 1\n- HTMLDOC crashed when rendering unresolved hyperlinks in aligned images\n- Documented the HTMLDOC_NOCGI environment variable\n- HTMLDOC sometimes crashed when rendering tables with background colors\n- HTMLDOC would crash when writing encrypted strings longer than 1024 bytes\n- HTMLDOC didn't set the data directory when running in CGI mode on Windows.\n- HTMLDOC could crash when loading the Symbol.afm file\n- HTMLDOC did not always honor HEIGHT attributes in table rows.\n- Tables with a mix of colspan and rowspan sometimes caused cells to be moved\n vertically outside the cell." ]
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [5, 1322], "buggy_code_start_loc": [4, 1321], "filenames": ["CHANGES.md", "htmldoc/ps-pdf.cxx"], "fixing_code_end_loc": [6, 1322], "fixing_code_start_loc": [4, 1321], "message": "A flaw was found in htmldoc before v1.9.12. Heap buffer overflow in pspdf_prepare_outpages(), in ps-pdf.cxx may lead to execute arbitrary code and denial of service.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:htmldoc_project:htmldoc:*:*:*:*:*:*:*:*", "matchCriteriaId": "8D1CE1F4-17A1-430E-9C8B-0CE88A07514B", "versionEndExcluding": "1.9.12", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:htmldoc_project:htmldoc:1.9.12:*:*:*:*:*:*:*", "matchCriteriaId": "645554AD-DA7C-4B11-864A-89F423B08291", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A flaw was found in htmldoc before v1.9.12. Heap buffer overflow in pspdf_prepare_outpages(), in ps-pdf.cxx may lead to execute arbitrary code and denial of service."}, {"lang": "es", "value": "Se ha encontrado un fallo en htmldoc versiones anteriores av1.9.12. Un desbordamiento del b\u00fafer de la pila en la funci\u00f3n pspdf_prepare_outpages(), en el archivo ps-pdf.cxx puede conllevar a una ejecuci\u00f3n de c\u00f3digo arbitrario y a una denegaci\u00f3n de servicio"}], "evaluatorComment": null, "id": "CVE-2021-23165", "lastModified": "2022-03-22T17:01:58.600", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 10.0, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-03-16T15:15:10.157", "references": [{"source": "secalert@redhat.com", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1967014"}, {"source": "secalert@redhat.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/michaelrsweet/htmldoc/commit/6e8a95561988500b5b5ae4861b3b0cbf4fba517f"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://github.com/michaelrsweet/htmldoc/commit/6e8a95561988500b5b5ae4861b3b0cbf4fba517f.patch"}, {"source": "secalert@redhat.com", "tags": ["Exploit", "Issue Tracking", "Third Party Advisory"], "url": "https://github.com/michaelrsweet/htmldoc/issues/413"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-787"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-122"}], "source": "secalert@redhat.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/michaelrsweet/htmldoc/commit/6e8a95561988500b5b5ae4861b3b0cbf4fba517f"}, "type": "CWE-787"}
201
Determine whether the {function_name} code is vulnerable or not.
[ "# Changes in HTMLDOC v1.9.12", "- Fixed a crash bug with \"data:\" URIs and EPUB output (Issue #410)", "- Fixed a number-up crash bug (Issue #413)\n- Fixed JPEG error handling (Issue #414, Issue #415)", "- Fixed crash bugs with bogus table attributes (Issue #416, Issue #417)\n- Fixed a crash bug with malformed URIs (Issue #418)\n- Fixed a crash bug with malformed GIF files (Issue #423)\n- Fixed some issues reported by Coverity.", "\n# Changes in HTMLDOC v1.9.11", "- Added high-resolution desktop icons for Linux.\n- Updated the internal HTTP library to fix truncation of redirection URLs\n (Issue #396)\n- Fixed a regression in the handling of character entities for UTF-8 input\n (Issue #401)\n- The `--numbered` option did not work when the table-of-contents was disabled\n (Issue #405)", "\n# Changes in HTMLDOC v1.9.10", "- Updated local zlib to v1.2.11.\n- Updated local libpng to v1.6.37.\n- Fixed packaging issues on macOS and Windows (Issue #377, Issue #386)\n- Now ignore sRGB profile errors in PNG files (Issue #390)\n- The GUI would crash when saving (Issue #391)\n- Page comments are now allowed in `pre` text (Issue #394)", "\n# Changes in HTMLDOC v1.9.9", "- Fixed a redirection issue - some sites (incorrectly) provide an incomplete\n Location: URL in the HTTP response.\n- Fixed https: support on newer versions of Windows (Issue #378)\n- Fixed a problem with remote URLs containing spaces (Issue #379)\n- Fixed a UTF-8 processing bug for Markdown files (Issue #383)\n- Added support for `<FONT FACE=\"monospace\">` (Issue #385)", "\n# Changes in HTMLDOC v1.9.8", "- Added support for a `HTMLDOC.filename` META keyword that controls the filename\n reported in CGI mode; the default remains \"htmldoc.pdf\" (Issue #367)\n- Fixed a paragraph formatting issue with large inline images (Issue #369)\n- Fixed a buffer underflow issue (Issue #370)\n- Fixed PDF page numbers (Issue #371)\n- Added support for a new `L` header/footer format (`$LETTERHEAD`), which\n inserts a letterhead image at its full size (Issue #372, Issue #373,\n Issue #375)\n- Updated the build documentation (Issue #374)", "\n# Changes in HTMLDOC v1.9.7", "- Refactored the PRE rendering code to work around compiler optimization bugs\n (Issue #349)\n- Added support for links with targets (Issue #351)\n- Fixed a table rowspan + valign bug (Issue #360)", "\n# Changes in HTMLDOC v1.9.6", "- Added support for data URIs (Issue #340)\n- HTMLDOC no longer includes a PDF table of contents when converting a single\n web page (Issue #344)\n- Updated the markdown support with external links, additional inline markup,\n and hard line breaks.\n- Links in markdown text no longer render with a leading space as part of the\n link (Issue #346)\n- Fixed a buffer underflow bug discovered by AddressSanitizer.\n- Fixed a bug in UTF-8 support (Issue #348)\n- PDF output now includes the base language of the input document(s)\n (Issue #350)\n- Optimized the loading of font widths (Issue #354)\n- Optimized PDF page resources (Issue #356)\n- Optimized the base memory used for font widths (Issue #357)\n- Added proper `&shy;` support (Issue #361)\n- Title files can now be markdown.", "\n# Changes in HTMLDOC v1.9.5", "- The GUI did not support EPUB output.\n- Empty markdown table cells were not rendered in PDF or PostScript output.\n- The automatically-generated title page now supports both \"docnumber\" and\n \"version\" metadata.\n- Added support for dc:subject and dc:language metadata in EPUB output from the\n HTML keywords and lang values.\n- Added support for the subject and language metadata in markdown input.\n- Fixed a buffer underflow bug (Issue #338)\n- `htmldoc --help` now reports whether HTTPS URLs are supported (Issue #339)\n- Fixed an issue with HTML title pages and EPUB output.", "\n# Changes in HTMLDOC v1.9.4", "- Inline fixed-width text is no longer reduced in size automatically\n (Issue #309)\n- Optimized initialization of font width data (Issue #334)", "\n# Changes in HTMLDOC v1.9.3", "- Fixed formatting bugs with aligned images (Issue #322, Issue #324)\n- Fixed support for three digit \"#RGB\" color values (Issue #323)\n- Fixed character set support for markdown metadata.\n- Updated libpng to v1.6.34 (Issue #326)\n- The makefiles did not use the CPPFLAGS value (Issue #328)", "\n# Changes in HTMLDOC v1.9.2", "- Added Markdown table support.\n- Fixed parsing of TBODY, TFOOT, and THEAD elements in HTML files.", "\n# Changes in HTMLDOC v1.9.1", "- Fixed monospace font size issue (Issue #309)\n- Added support for reproducible builds (Issue #310)\n- Added limited support for the HTML 4.0 SPAN element (Issue #311)\n- Added (extremely limited) UTF-8 support for input files (Issue #314)\n- Fixed buffer underflow for (invalid) short HTML comments (Issue #316)\n- Now indent PRE text, by popular request.\n- EPUB output now makes sure that `<element property>` is written as\n `<element property=\"property\">`.\n- Now support both NAME and ID for table-of-contents targets.", "\n# Changes in HTMLDOC v1.9", "- Added support for repeating a single header row for tables that span multiple\n pages (Issue #16)\n- Added support for embedding the current filename/URL in the header or footer\n (Issue #50)\n- Added EPUB support (Issue #301)\n- Added Markdown support (Issue #302)\n- Fixed a regression in header/footer image scaling (Issue #303)\n- Documentation updates (Issue #305)\n- Compiler fixes (Issue #304, Issue #306)\n- Fixed a bug when running HTMLDOC as a macOS application.\n- Updated the bundled libpng to v1.6.29.", "\n# Changes in HTMLDOC v1.8.30", "- Updated documentation to reflect new project page on Github.\n- Dropped old CDE and IRIX desktop integration files.\n- Cleaned up the GUI and adopted new default text editors for Linux and macOS.\n- PAGE BREAK comments at the end of a file in web page mode would lose the\n first page (Issue #251)\n- Fixed the scaling of header/footer images to limit them to the height of the\n header or footer (Issue #273)\n- Fixed an issue with the top-level makefile not exiting with an error as\n needed (Issue #282)\n- Fixed a URL referencing bug when the same hostname but a different port was\n used (Issue #290)\n- Fixed build issue on macOS (Issue #291)\n- Fixed handling of indexed+alpha PNG images (Issue #295)", "\n# Changes in HTMLDOC v1.8.29", "- Updated local PNG library to version 1.6.20.\n- Updated local JPEG library to version 9b.\n- Dropped support for OpenSSL.\n- Added configure script support for libjpeg-turbo.\n- Updated HTTP code to latest CUPS/ippsample sources.\n- Duplex PDF output incorrectly forced an even number of pages\n- The table of contents showed the wrong page numbers after headings containing\n the \"_HD_OMIT_TOC\" attribute.\n- Fixed reported build issues\n- The configure script's --enable-local* options did not work.", "\n# Changes in HTMLDOC v1.8.28", "- Updated local zlib to version 1.2.8.\n- Updated local PNG library to version 1.6.8.\n- Updated local JPEG library to version 9.\n- Updated default PDF version to 1.4.\n- SECURITY: Fixed three buffer overflow issues when reading AFM files and\n parsing page sizes.\n- Fixed incompatibility with Fortify's version of strcpy, which does not work\n properly with variable-length arrays\n- Fixed compilation against PNG library 1.5 or later\n- Fixed documentation errors\n- Marked Zapf-Dingbats as a standard font\n- Fixed GPL license text in GUI\n- Fixed a table formatting problem when a column has multiple colspan values\n- Fixed parsing of HTML comments\n- Fixed potential out-of-bounds read in table-of-contents rendering code\n- Fixed handling of image URLs with ampersands in them\n- Fixed top/bottom margins for logo and header/footer images\n- Fixed image alignment bug\n- Fixed X11 build problem", "\n# Changes in HTMLDOC v1.8.27", "- Fixed a crash bug that appeared when more than 10 blank pages were present in\n a document\n- Color changes were not reflected in PRE text\n- Remote URLs did not always work on older operating systems\n- Image filenames using % escapes were not decoded properly.\n- Rows using BGCOLOR that spanned across multiple pages did not render properly\n- Rows no longer start on a new page due to a cell with both HEIGHT and ROWSPAN\n specified\n- CMYK JPEG images caused HTMLDOC to crash\n- Table cell width calculations didn't always account for the proper minimum\n width\n- Images were not copied when generating indexed HTML output to a directory\n- Changing the bottom margin resulted in text that was formatted below the\n bottom margin.\n- The Monospace-Oblique font was not embedded properly in PDF files.", "\n# Changes in HTMLDOC v1.8.26", "- Outline and keyword strings in PDF files are now stored as Unicode\n- The Flate compression code could get in an infinite loop if it ran out of\n memory\n- Book files saved from the GUI did not handle filenames with spaces\n- Fixed and re-enabled the ASCII85Device filter support in PostScript Level 2/3\n output\n- Character entities in the first word of a file were not rendered properly\n- Fixed-size table columns were incorrectly resized when a table width was also\n specified and there was extra space to distribute\n- Text could \"walk\" up or down when in-line images were used\n- Row backgrounds incorrectly replaced cell backgrounds when the first cell in a\n row used ROWSPAN\n- HTMLDOC did not correctly parse FONT FACE attributes\n- Images in Level 2/3 PostScript output did not work on some printers\n- The GUI did not use the first page header", "\n# Changes in HTMLDOC v1.8.25", "- Added \"--overflow\" and \"--no-overflow\" command-line options to show or hide\n the content-too-large errors; the default is \"--no-overflow\".\n- Added \"--header1\" command-line option and \"HEADER1\" page comments to set the\n page header for the first page of each chapter.\n- Added \"timing\" and \"remotebytes\" debug data generation.\n- Added DejaVu font collection to better support Cyrillic and Greek text; the\n new fonts are available under the generic names \"monospace\", \"sans\", and\n \"serif\".\n- Added \"--referer\" command-line option and corresponding CGI-mode support to\n pass Referer: information in HTTP requests\n- On Windows, HTMLDOC now logs CGI mode errors to a file called \"htmldoc.log\" in\n the Windows temporary directory.\n- HTMLDOC no longer uses Base-85 encoding for image data when producing Level 2\n and 3 PostScript output. It appears that many printers and PostScript\n interpreters cannot properly decode this data when the original image data is\n not a multiple of 8 bits.\n- HTMLDOC now renders STRONG elements in boldface instead of bold-italic to\n match the W3C recommendations.\n- HTMLDOC now automatically inserts a TR element before a TD or TH element as\n needed to improve web site compatibility; this also triggers a HTML error in\n --strict mode.\n- \"$HFIMAGEn\" didn't work in a header/footer string.\n- HTMLDOC could crash when rendering a table.\n- Book files were not used in CGI mode\n- Cookies were not sent in HTTP requests\n- Table cells were not aligned properly when the ROWSPAN attribute was set to 1\n- HTMLDOC crashed when rendering unresolved hyperlinks in aligned images\n- Documented the HTMLDOC_NOCGI environment variable\n- HTMLDOC sometimes crashed when rendering tables with background colors\n- HTMLDOC would crash when writing encrypted strings longer than 1024 bytes\n- HTMLDOC didn't set the data directory when running in CGI mode on Windows.\n- HTMLDOC could crash when loading the Symbol.afm file\n- HTMLDOC did not always honor HEIGHT attributes in table rows.\n- Tables with a mix of colspan and rowspan sometimes caused cells to be moved\n vertically outside the cell." ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [5, 1322], "buggy_code_start_loc": [4, 1321], "filenames": ["CHANGES.md", "htmldoc/ps-pdf.cxx"], "fixing_code_end_loc": [6, 1322], "fixing_code_start_loc": [4, 1321], "message": "A flaw was found in htmldoc before v1.9.12. Heap buffer overflow in pspdf_prepare_outpages(), in ps-pdf.cxx may lead to execute arbitrary code and denial of service.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:htmldoc_project:htmldoc:*:*:*:*:*:*:*:*", "matchCriteriaId": "8D1CE1F4-17A1-430E-9C8B-0CE88A07514B", "versionEndExcluding": "1.9.12", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:htmldoc_project:htmldoc:1.9.12:*:*:*:*:*:*:*", "matchCriteriaId": "645554AD-DA7C-4B11-864A-89F423B08291", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A flaw was found in htmldoc before v1.9.12. Heap buffer overflow in pspdf_prepare_outpages(), in ps-pdf.cxx may lead to execute arbitrary code and denial of service."}, {"lang": "es", "value": "Se ha encontrado un fallo en htmldoc versiones anteriores av1.9.12. Un desbordamiento del b\u00fafer de la pila en la funci\u00f3n pspdf_prepare_outpages(), en el archivo ps-pdf.cxx puede conllevar a una ejecuci\u00f3n de c\u00f3digo arbitrario y a una denegaci\u00f3n de servicio"}], "evaluatorComment": null, "id": "CVE-2021-23165", "lastModified": "2022-03-22T17:01:58.600", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 10.0, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-03-16T15:15:10.157", "references": [{"source": "secalert@redhat.com", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1967014"}, {"source": "secalert@redhat.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/michaelrsweet/htmldoc/commit/6e8a95561988500b5b5ae4861b3b0cbf4fba517f"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://github.com/michaelrsweet/htmldoc/commit/6e8a95561988500b5b5ae4861b3b0cbf4fba517f.patch"}, {"source": "secalert@redhat.com", "tags": ["Exploit", "Issue Tracking", "Third Party Advisory"], "url": "https://github.com/michaelrsweet/htmldoc/issues/413"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-787"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-122"}], "source": "secalert@redhat.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/michaelrsweet/htmldoc/commit/6e8a95561988500b5b5ae4861b3b0cbf4fba517f"}, "type": "CWE-787"}
201
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * PostScript + PDF output routines for HTMLDOC, a HTML document processing\n * program.\n *\n * Just in case you didn't notice it, this file is too big; it will be\n * broken into more manageable pieces once we make all of the output\n * \"drivers\" into classes...\n *\n * Copyright © 2011-2021 by Michael R Sweet.\n * Copyright © 1997-2010 by Easy Software Products. All rights reserved.\n *\n * This program is free software. Distribution and use rights are outlined in\n * the file \"COPYING\".\n */", "/*\n * Include necessary headers.\n */", "/*\n * The GCC compiler on HP-UX has a nasty habit of incorrectly \"fixing\"\n * the vmtypes.h header file provided with HP-UX. The following\n * conditional magic makes sure that \"page_t\" (which we use in our\n * code) is not defined...\n */", "#ifdef __hpux\n# define page_t\thpux_page_t\n#endif // __hpux", "/*#define DEBUG*/\n#include \"htmldoc.h\"\n#include \"markdown.h\"\n#include \"md5-private.h\"\n#define md5_append _cupsMD5Append\n#define md5_finish _cupsMD5Finish\n#define md5_init _cupsMD5Init\ntypedef unsigned char md5_byte_t;\n#define md5_state_t _cups_md5_state_t\n#include \"rc4.h\"\n#include <stdarg.h>\n#include <ctype.h>\n#include <time.h>\n#include <math.h>", "#ifdef WIN32\n# include <io.h>\n#else\n# include <unistd.h>\n#endif // WIN32", "#include <fcntl.h>", "#include <zlib.h>", "extern \"C\" {\t\t/* Workaround for JPEG header problems... */\n#include <jpeglib.h>\t/* JPEG/JFIF image definitions */\n}", "#ifdef __hpux\n# undef page_t\n#endif // __hpux", "\n/*\n * Output options...\n */", "#define HTMLDOC_ASCII85\n//#define HTMLDOC_INTERPOLATION\n#define HTMLDOC_PRODUCER \"htmldoc \" SVERSION \" Copyright 2011-2019 by Michael R Sweet\"", "\n/*\n * Constants...\n */", "#define RENDER_TEXT\t0\t\t/* Text fragment */\n#define RENDER_IMAGE\t1\t\t/* Image */\n#define RENDER_BOX\t2\t\t/* Box */\n#define RENDER_LINK\t3\t\t/* Hyperlink */\n#define RENDER_BG\t4\t\t/* Background image */", "\n/*\n * Structures...\n */", "typedef struct render_str\t\t/**** Render entity structure ****/\n{\n struct render_str\t*prev;\t\t/* Previous rendering entity */\n struct render_str\t*next;\t\t/* Next rendering entity */\n int\ttype;\t\t\t\t/* Type of entity */\n float\tx,\t\t\t\t/* Position in points */\n\ty,\t\t\t\t/* ... */\n\twidth,\t\t\t\t/* Size in points */\n\theight;\t\t\t\t/* ... */\n union\n {\n struct\n {\n int\ttypeface,\t\t/* Typeface for text */\n\t\tstyle;\t\t\t/* Style of text */\n float\tsize;\t\t\t/* Size of text in points */\n float\tspacing;\t\t/* Inter-character spacing */\n float\trgb[3];\t\t\t/* Color of text */\n uchar\tbuffer[1];\t\t/* String buffer */\n } \ttext;\n image_t\t*image;\t\t\t/* Image pointer */\n float\tbox[3];\t\t\t/* Box color */\n uchar\tlink[1];\t\t/* Link URL */\n }\tdata;\n} render_t;", "typedef struct\t\t\t\t/**** Named link position structure */\n{\n short\t\tpage,\t\t\t/* Page # */\n\t\ttop;\t\t\t/* Top position */\n uchar\t\tname[124];\t\t/* Reference name */\n} link_t;", "typedef struct\t\t\t\t//// Page information\n{\n int\t\twidth,\t\t\t// Width of page in points\n\t\tlength,\t\t\t// Length of page in points\n\t\tleft,\t\t\t// Left margin in points\n\t\tright,\t\t\t// Right margin in points\n\t\ttop,\t\t\t// Top margin in points\n\t\tbottom,\t\t\t// Bottom margin in points\n\t\tduplex,\t\t\t// Duplex this page?\n\t\tlandscape;\t\t// Landscape orientation?\n render_t\t*start,\t\t\t// First render element\n\t\t*end;\t\t\t// Last render element\n uchar\t\t*url, // URL/file\n *chapter,\t\t// Chapter text\n\t\t*heading;\t\t// Heading text\n tree_t\t*headnode;\t\t// Heading node\n uchar\t\t*header[3],\t\t// Headers for regular pages\n\t\t*header1[3],\t\t// Headers for first pages\n\t\t*footer[3];\t\t// Footers for all pages\n char\t\tmedia_color[64],\t// Media color\n\t\tmedia_type[64];\t\t// Media type\n int\t\tmedia_position;\t\t// Media position\n char\t\tpage_text[64];\t\t// Page number for TOC\n image_t\t*background_image;\t// Background image\n float\t\tbackground_color[3];\t// Background color", " // Number-up support\n int\t\tnup;\t\t\t// Number up pages\n int\t\toutpage;\t\t// Output page #\n float\t\toutmatrix[2][3];\t// Transform matrix\n} page_t;", "typedef struct\t\t\t\t//// Output page info\n{\n int\t\tnup;\t\t\t// Number up pages\n int\t\tpages[16];\t\t// Pages on this output page\n int\t\tannot_object;\t\t// Annotation object\n} outpage_t;", "\n/*\n * Local globals...\n */", "static time_t\tdoc_time;\t\t// Current time\nstatic struct tm doc_date;\t\t// Current date", "static uchar *current_url = NULL;\nstatic int\ttitle_page;\nstatic int\tchapter,\n\t\tchapter_outstarts[MAX_CHAPTERS],\n\t\tchapter_outends[MAX_CHAPTERS],\n\t\tchapter_starts[MAX_CHAPTERS],\n\t\tchapter_ends[MAX_CHAPTERS];", "static size_t\tnum_headings = 0,\n\t\talloc_headings = 0;\nstatic int\t*heading_pages = NULL,\n\t\t*heading_tops = NULL;", "static size_t\tnum_pages = 0,\n\t\talloc_pages = 0;\nstatic page_t\t*pages = NULL;\nstatic tree_t\t*current_heading;", "static size_t\tnum_outpages = 0;\nstatic outpage_t *outpages = NULL;", "static size_t\tnum_links = 0,\n\t\talloc_links = 0;\nstatic link_t\t*links = NULL;", "static uchar\tlist_types[16];\nstatic int\tlist_values[16];", "static char\tstdout_filename[256];\nstatic size_t\tnum_objects = 0,\n\t\talloc_objects = 0;\nstatic int\t*objects = NULL,\n\t\troot_object,\n\t\tinfo_object,\n\t\toutline_object,\n\t\tpages_object,\n\t\tnames_object,\n\t\tencrypt_object,\n\t\tfont_objects[TYPE_MAX * STYLE_MAX];", "static uchar\t*doc_title = NULL;\nstatic image_t\t*logo_image = NULL;\nstatic float\tlogo_width,\n\t\tlogo_height;\nstatic image_t\t*lh_image = NULL;\nstatic float\tlh_width,\n\t\tlh_height;", "static image_t\t*hfimage[MAX_HF_IMAGES];\nstatic float\thfimage_width[MAX_HF_IMAGES],\n\t\thfimage_height[MAX_HF_IMAGES];\nstatic float maxhfheight;", "static image_t\t*background_image = NULL;\nstatic float\tbackground_color[3] = { 1.0, 1.0, 1.0 },\n\t\tlink_color[3] = { 0.0, 0.0, 1.0 };", "static int\trender_typeface,\n\t\trender_style;\nstatic float\trender_size,\n\t\trender_rgb[3],\n\t\trender_x,\n\t\trender_y,\n\t\trender_startx,\n\t\trender_spacing;", "static int\t\tcompressor_active = 0;\nstatic z_stream\t\tcompressor;\nstatic uchar\t\tcomp_buffer[8192];\nstatic uchar\t\tencrypt_key[16];\nstatic int\t\tencrypt_len;\nstatic rc4_context_t\tencrypt_state;\nstatic md5_byte_t\tfile_id[16];", "\n/*\n * Local functions...\n */", "extern \"C\" {\ntypedef int\t(*compare_func_t)(const void *, const void *);\n}", "static void\tpspdf_debug_stats();", "static void\tpspdf_transform_coords(page_t *p, float &x, float &y);\nstatic void\tpspdf_transform_page(int outpage, int pos, int page);", "static void\tpspdf_prepare_outpages();\nstatic void\tpspdf_prepare_page(int page);\nstatic void\tpspdf_prepare_heading(int page, int print_page, uchar **format,\n\t\t int y, char *page_text, int page_len);\nstatic void\tps_write_document(uchar *author, uchar *creator,\n\t\t uchar *copyright, uchar *keywords,\n\t\t\t\t uchar *subject, uchar *lang);\nstatic void\tps_write_outpage(FILE *out, int outpage);\nstatic void\tps_write_page(FILE *out, int page);\nstatic void\tps_write_background(FILE *out);\nstatic void\tpdf_write_document(uchar *author, uchar *creator,\n\t\t uchar *copyright, uchar *keywords,\n\t\t\t\t uchar *subject, uchar *lang, tree_t *doc, tree_t *toc);\nstatic void\tpdf_write_outpage(FILE *out, int outpage);\nstatic void\tpdf_write_page(FILE *out, int page);\nstatic void\tpdf_write_resources(FILE *out, int page);\n#ifdef DEBUG_TOC\nstatic void\tpdf_text_contents(FILE *out, tree_t *toc, int indent = 0);\n#endif // DEBUG_TOC\nstatic void\tpdf_write_contents(FILE *out, tree_t *toc, int parent,\n\t\t int prev, int next, int *heading);\nstatic void\tpdf_write_files(FILE *out, tree_t *doc);\nstatic void\tpdf_write_links(FILE *out);\nstatic void\tpdf_write_names(FILE *out);\nstatic int\tpdf_count_headings(tree_t *toc);", "static int\tpdf_start_object(FILE *out, int array = 0);\nstatic void\tpdf_start_stream(FILE *out);\nstatic void\tpdf_end_object(FILE *out);", "static void\tencrypt_init(void);\nstatic void\tflate_open_stream(FILE *out);\nstatic void\tflate_close_stream(FILE *out);\nstatic void\tflate_puts(const char *s, FILE *out);\nstatic void\tflate_printf(FILE *out, const char *format, ...);\nstatic void\tflate_write(FILE *out, uchar *inbuf, int length, int flush=0);", "static void\tparse_contents(tree_t *t, float left, float width, float bottom,\n\t\t float length, float *y, int *page, int *heading,\n\t\t\t tree_t *chap);\nstatic void\tparse_doc(tree_t *t, float *left, float *right, float *bottom,\n\t\t float *top, float *x, float *y, int *page,\n\t\t\t tree_t *cpara, int *needspace);\nstatic void\tparse_heading(tree_t *t, float left, float width, float bottom,\n\t\t float length, float *x, float *y, int *page,\n\t\t\t int needspace);\nstatic void\tparse_paragraph(tree_t *t, float left, float width, float bottom,\n\t\t float length, float *x, float *y, int *page,\n\t\t\t int needspace);\nstatic void\tparse_pre(tree_t *t, float left, float width, float bottom,\n\t\t float length, float *x, float *y, int *page,\n\t\t\t int needspace);\nstatic void\tparse_table(tree_t *t, float left, float width, float bottom,\n\t\t float length, float *x, float *y, int *page,\n\t\t\t int needspace);\nstatic void\tparse_list(tree_t *t, float *left, float *width, float *bottom,\n\t\t float *length, float *x, float *y, int *page,\n\t\t\t int needspace);\nstatic void\tinit_list(tree_t *t);\nstatic void\tparse_comment(tree_t *t, float *left, float *width, float *bottom,\n\t\t float *length, float *x, float *y, int *page,\n\t\t\t tree_t *para, int needspace);", "static void\tcheck_pages(int page);", "static void\tadd_link(uchar *name, int page, int top);\nstatic link_t\t*find_link(uchar *name);\nstatic int\tcompare_links(link_t *n1, link_t *n2);", "static void\tfind_background(tree_t *t);\nstatic void\twrite_background(int page, FILE *out);", "static render_t\t*new_render(int page, int type, double x, double y,\n\t\t double width, double height, void *data,\n\t\t\t render_t *insert = 0);\nstatic float\tget_cell_size(tree_t *t, float left, float right,\n\t\t float *minwidth, float *prefwidth,\n\t\t\t float *minheight);\nstatic float\tget_table_size(tree_t *t, float left, float right,\n\t\t float *minwidth, float *prefwidth,\n\t\t\t float *minheight);\nstatic tree_t\t*flatten_tree(tree_t *t);\nstatic float\tget_width(uchar *s, int typeface, int style, int size);\nstatic void\tupdate_image_size(tree_t *t);\nstatic uchar\t*get_title(tree_t *doc);\nstatic FILE\t*open_file(void);\nstatic void\tset_color(FILE *out, float *rgb);\nstatic void\tset_font(FILE *out, int typeface, int style, float size);\nstatic void\tset_pos(FILE *out, float x, float y);\nstatic void\twrite_prolog(FILE *out, int pages, uchar *author,\n\t\t uchar *creator, uchar *copyright,\n\t\t\t uchar *keywords, uchar *subject);\nstatic void\tps_hex(FILE *out, uchar *data, int length);\n#ifdef HTMLDOC_ASCII85\nstatic void\tps_ascii85(FILE *out, uchar *data, int length, int eod = 0);\n#endif // HTMLDOC_ASCII85\nstatic void\tjpg_init(j_compress_ptr cinfo);\nstatic boolean\tjpg_empty(j_compress_ptr cinfo);\nstatic void\tjpg_term(j_compress_ptr cinfo);\nstatic void\tjpg_setup(FILE *out, image_t *img, j_compress_ptr cinfo);\nstatic int\tcompare_rgb(unsigned *rgb1, unsigned *rgb2);\nstatic void\twrite_image(FILE *out, render_t *r, int write_obj = 0);\nstatic void\twrite_imagemask(FILE *out, render_t *r);\nstatic void\twrite_string(FILE *out, uchar *s, int compress);\nstatic void\twrite_text(FILE *out, render_t *r);\nstatic void\twrite_trailer(FILE *out, int pages, uchar *lang);\nstatic int\twrite_type1(FILE *out, typeface_t typeface,\n\t\t\t style_t style);\nstatic void\twrite_utf16(FILE *out, uchar *s);", "\n/*\n * 'pspdf_export()' - Export PostScript/PDF file(s)...\n */", "int\npspdf_export(tree_t *document,\t/* I - Document to export */\n tree_t *toc)\t/* I - Table of contents for document */\n{\n int\t\ti, j;\t\t/* Looping vars */\n const char\t*title_file;\t/* Location of title image/file */\n uchar\t\t*author,\t/* Author of document */\n\t\t*creator,\t/* HTML file creator (Netscape, etc) */\n\t\t*copyright,\t/* File copyright */\n\t\t*docnumber,\t/* Document number */\n\t\t*keywords,\t/* Search keywords */\n\t\t*subject,\t/* Subject */\n\t\t*lang;\t\t/* Language */\n tree_t\t*t;\t\t/* Title page document tree */\n FILE\t\t*fp;\t\t/* Title page file */\n float\t\tx, y,\t\t/* Current page position */\n\t\tleft, right,\t/* Left and right margins */\n\t\tbottom, top,\t/* Bottom and top margins */\n\t\twidth,\t\t/* Width of , author, etc */\n\t\theight;\t\t/* Height of area */\n int\t\tpage,\t\t/* Current page # */\n\t\tpos,\t\t/* Current header/footer position */\n\t\theading,\t/* Current heading # */\n\t\ttoc_duplex,\t/* Duplex TOC pages? */\n\t\ttoc_landscape,\t/* Do TOC in landscape? */\n\t\ttoc_width,\t/* Width of TOC pages */\n\t\ttoc_length,\t/* Length of TOC pages */\n\t\ttoc_left,\t/* TOC page margins */\n\t\ttoc_right,\n\t\ttoc_bottom,\n\t\ttoc_top;\n image_t\t*timage;\t/* Title image */\n float\t\ttimage_width,\t/* Title image width */\n\t\ttimage_height;\t/* Title image height */\n render_t\t*r;\t\t/* Rendering structure... */\n float\t\trgb[3];\t\t/* Text color */\n int\t\tneedspace;\t/* Need whitespace */", "\n /*\n * Figure out the printable area of the output page...\n */", " if (Landscape)\n {\n PagePrintWidth = PageLength - PageLeft - PageRight;\n PagePrintLength = PageWidth - PageTop - PageBottom;\n }\n else\n {\n PagePrintWidth = PageWidth - PageLeft - PageRight;\n PagePrintLength = PageLength - PageTop - PageBottom;\n }", " toc_width = PageWidth;\n toc_length = PageLength;\n toc_left = PageLeft;\n toc_right = PageRight;\n toc_bottom = PageBottom;\n toc_top = PageTop;\n toc_landscape = Landscape;\n toc_duplex = PageDuplex;", " /*\n * Get the document title, author, etc...\n */", " doc_title = get_title(document);\n author = htmlGetMeta(document, (uchar *)\"author\");\n creator = htmlGetMeta(document, (uchar *)\"generator\");\n copyright = htmlGetMeta(document, (uchar *)\"copyright\");\n docnumber = htmlGetMeta(document, (uchar *)\"docnumber\");\n keywords = htmlGetMeta(document, (uchar *)\"keywords\");\n subject = htmlGetMeta(document, (uchar *)\"subject\");\n lang = htmlGetMeta(document, (uchar *)\"lang\");\n logo_image = image_load(LogoImage, !OutputColor);\n lh_image = image_load(Letterhead, !OutputColor);\n maxhfheight = 0.0f;", " if (docnumber == NULL)\n docnumber = htmlGetMeta(document, (uchar *)\"version\");", " if (lh_image != NULL)\n {\n lh_width = (float)(lh_image->width * PagePrintWidth / _htmlBrowserWidth);\n lh_height = (float)(lh_width * lh_image->height / lh_image->width);", " if (lh_height > maxhfheight)\n maxhfheight = lh_height;\n }\n else\n lh_width = lh_height = 0.0f;", " if (logo_image != NULL)\n {\n logo_width = (float)(logo_image->width * PagePrintWidth / _htmlBrowserWidth);\n logo_height = (float)(logo_width * logo_image->height / logo_image->width);", " if (logo_height > (2.0 * HeadFootSize))\n {\n // Issue #273: too large logo image will overlap the body text, so cap\n // the height of the logo image to the header/footer size...\n //\n // Issue #303: regression prevents using header/footer images for special\n // underlining/etc. effects.\n logo_height = (float)(2.0 * HeadFootSize);\n logo_width = logo_height * logo_image->width / logo_image->height;\n }", " if (logo_height > maxhfheight)\n maxhfheight = logo_height;\n }\n else\n logo_width = logo_height = 0.0f;", " for (int hfi = 0; hfi < MAX_HF_IMAGES; hfi ++)\n {\n hfimage[hfi] = image_load(HFImage[hfi], !OutputColor);", " if (hfimage[hfi])\n {\n hfimage_width[hfi] = (float)(hfimage[hfi]->width * PagePrintWidth / _htmlBrowserWidth);\n hfimage_height[hfi] = (float)(hfimage_width[hfi] * hfimage[hfi]->height / hfimage[hfi]->width);", " if (hfimage_height[hfi] > (2.0 * HeadFootSize))\n {\n // Issue #273: too large logo image will overlap the body text, so cap\n // the height of the logo image to the header/footer size...\n //\n // Issue #303: regression prevents using header/footer images for special\n // underlining/etc. effects.\n hfimage_height[hfi] = (float)(2.0 * HeadFootSize);\n hfimage_width[hfi] = hfimage_height[hfi] * hfimage[hfi]->width / hfimage[hfi]->height;\n }", " if (hfimage_height[hfi] > maxhfheight)\n maxhfheight = hfimage_height[hfi];\n }\n else\n hfimage_width[hfi] = hfimage_height[hfi] = 0.0f;\n }", " find_background(document);\n get_color((uchar *)LinkColor, link_color);", " /*\n * Initialize page rendering variables...\n */", " num_pages = 0;\n alloc_pages = 0;\n pages = NULL;", " memset(list_types, 0267, sizeof(list_types));\n memset(list_values, 0, sizeof(list_values));\n memset(chapter_starts, -1, sizeof(chapter_starts));\n memset(chapter_ends, -1, sizeof(chapter_starts));", " /*\n * Get the current date, using the SOURCE_DATE_EPOCH environment variable, if\n * present, for the number of seconds since the epoch - this enables\n * reproducible builds (Issue #310).\n */", " const char *source_date_epoch = getenv(\"SOURCE_DATE_EPOCH\");\n if (!source_date_epoch || (doc_time = (time_t)strtol(source_date_epoch, NULL, 10)) <= 0)\n doc_time = time(NULL);", " gmtime_r(&doc_time, &doc_date);", " num_headings = 0;\n alloc_headings = 0;\n heading_pages = NULL;\n heading_tops = NULL;\n num_links = 0;\n alloc_links = 0;\n links = NULL;\n num_pages = 0;", " DEBUG_printf((\"pspdf_export: TitlePage = %d, TitleImage = \\\"%s\\\"\\n\",\n TitlePage, TitleImage));", " if (TitlePage)\n {\n const char *title_ext = file_extension(TitleImage);", "#ifdef WIN32\n if (TitleImage[0] &&\n stricmp(title_ext, \"bmp\") != 0 &&\n\tstricmp(title_ext, \"gif\") != 0 &&\n\tstricmp(title_ext, \"jpg\") != 0 &&\n\tstricmp(title_ext, \"png\") != 0)\n#else\n if (TitleImage[0] &&\n strcmp(title_ext, \"bmp\") != 0 &&\n\tstrcmp(title_ext, \"gif\") != 0 &&\n\tstrcmp(title_ext, \"jpg\") != 0 &&\n\tstrcmp(title_ext, \"png\") != 0)\n#endif // WIN32\n {\n DEBUG_printf((\"pspdf_export: Generating a titlepage using \\\"%s\\\"\\n\",\n TitleImage));", " // Find the title file...\n if ((title_file = file_find(Path, TitleImage)) == NULL)\n {\n\tprogress_error(HD_ERROR_FILE_NOT_FOUND,\n\t \"Unable to find title file \\\"%s\\\"!\", TitleImage);\n\treturn (1);\n }", " // Write a title page from HTML source...\n if ((fp = fopen(title_file, \"rb\")) == NULL)\n {\n\tprogress_error(HD_ERROR_FILE_NOT_FOUND,\n\t \"Unable to open title file \\\"%s\\\" - %s!\",\n TitleImage, strerror(errno));\n\treturn (1);\n }", "#ifdef _WIN32\n if (!stricmp(title_ext, \"md\"))\n#else\n if (!strcmp(title_ext, \"md\"))\n#endif // _WIN32\n\tt = mdReadFile(NULL, fp, file_directory(TitleImage));\n else\n\tt = htmlReadFile(NULL, fp, file_directory(TitleImage));", " htmlFixLinks(t, t, (uchar *)file_directory(TitleImage));\n fclose(fp);", " page = 0;\n title_page = 1;\n current_heading = NULL;\n x = 0.0f;\n bottom = 0.0f;\n top = PagePrintLength;\n y = top;\n needspace = 0;\n left = 0.0f;\n right = PagePrintWidth;", " parse_doc(t, &left, &right, &bottom, &top, &x, &y, &page, NULL, &needspace);", " if (PageDuplex && (num_pages & 1))\n\tcheck_pages(num_pages);", " htmlDeleteTree(t);\n }\n else\n {\n /*\n * Create a standard title page...\n */", " if ((timage = image_load(TitleImage, !OutputColor)) != NULL)\n {\n\ttimage_width = (float)(timage->width * PagePrintWidth / _htmlBrowserWidth);\n\ttimage_height = (float)(timage_width * timage->height / timage->width);\n }\n else\n timage_width = timage_height = 0.0f;", " check_pages(0);\n if (PageDuplex)\n check_pages(1);", " height = 0.0;", " if (timage != NULL)\n\theight += timage_height + _htmlSpacings[SIZE_P];\n if (doc_title != NULL)\n\theight += _htmlSpacings[SIZE_H1] + _htmlSpacings[SIZE_P];\n if (author != NULL)\n\theight += _htmlSpacings[SIZE_P];\n if (docnumber != NULL)\n\theight += _htmlSpacings[SIZE_P];\n if (copyright != NULL)\n\theight += _htmlSpacings[SIZE_P];", " y = 0.5f * (PagePrintLength + height);", " if (timage != NULL)\n {\n\tnew_render(0, RENDER_IMAGE, 0.5f * (PagePrintWidth - timage_width),\n y - timage_height, timage_width, timage_height, timage);\n\ty -= timage_height + _htmlSpacings[SIZE_P];\n }", " get_color(_htmlTextColor, rgb);", " if (doc_title != NULL)\n {\n\twidth = get_width(doc_title, _htmlHeadingFont, STYLE_BOLD, SIZE_H1);\n\tr = new_render(0, RENDER_TEXT, (PagePrintWidth - width) * 0.5f,\n \t y - _htmlSpacings[SIZE_H1], width,\n\t\t\t _htmlSizes[SIZE_H1], doc_title);", "\tr->data.text.typeface = _htmlHeadingFont;\n\tr->data.text.style = STYLE_BOLD;\n\tr->data.text.size = (float)_htmlSizes[SIZE_H1];\n\tmemcpy(r->data.text.rgb, rgb, sizeof(rgb));", "\ty -= _htmlSpacings[SIZE_H1];", "\tif (docnumber != NULL)\n\t{\n\t width = get_width(docnumber, _htmlBodyFont, STYLE_NORMAL, SIZE_P);\n\t r = new_render(0, RENDER_TEXT, (PagePrintWidth - width) * 0.5f,\n y - _htmlSpacings[SIZE_P], width,\n\t\t\t _htmlSizes[SIZE_P], docnumber);", "\t r->data.text.typeface = _htmlBodyFont;\n\t r->data.text.style = STYLE_NORMAL;\n\t r->data.text.size = (float)_htmlSizes[SIZE_P];\n memcpy(r->data.text.rgb, rgb, sizeof(rgb));", "\t y -= _htmlSpacings[SIZE_P];\n\t}", "\ty -= _htmlSpacings[SIZE_P];\n }", " if (author != NULL)\n {\n\twidth = get_width(author, _htmlBodyFont, STYLE_NORMAL, SIZE_P);\n\tr = new_render(0, RENDER_TEXT, (PagePrintWidth - width) * 0.5f,\n \t y - _htmlSpacings[SIZE_P], width, _htmlSizes[SIZE_P],\n\t\t\t author);", "\tr->data.text.typeface = _htmlBodyFont;\n\tr->data.text.style = STYLE_NORMAL;\n\tr->data.text.size = (float)_htmlSizes[SIZE_P];\n\tmemcpy(r->data.text.rgb, rgb, sizeof(rgb));", "\ty -= _htmlSpacings[SIZE_P];\n }", " if (copyright != NULL)\n {\n\twidth = get_width(copyright, _htmlBodyFont, STYLE_NORMAL, SIZE_P);\n\tr = new_render(0, RENDER_TEXT, (PagePrintWidth - width) * 0.5f,\n \t y - _htmlSpacings[SIZE_P], width, _htmlSizes[SIZE_P],\n\t\t\t copyright);", "\tr->data.text.typeface = _htmlBodyFont;\n\tr->data.text.style = STYLE_NORMAL;\n\tr->data.text.size = (float)_htmlSizes[SIZE_P];\n\tmemcpy(r->data.text.rgb, rgb, sizeof(rgb));\n }\n }", " for (page = 0; page < (int)num_pages; page ++)\n strlcpy((char *)pages[page].page_text, (page & 1) ? \"eltit\" : \"title\", sizeof(pages[page].page_text));\n }\n else\n page = 0;", " /*\n * Parse the document...\n */", " if (OutputType == OUTPUT_BOOK)\n chapter = 0;\n else\n {\n chapter = 1;\n TocDocCount = 1;\n chapter_starts[1] = num_pages;\n }", " title_page = 0;\n current_heading = NULL;\n x = 0.0f;\n needspace = 0;\n left = 0.0f;\n right = PagePrintWidth;", " // Adjust top margin as needed...\n float adjust, image_adjust, temp_adjust;", " if (maxhfheight > HeadFootSize)\n image_adjust = (float)(maxhfheight + HeadFootSize);\n else\n image_adjust = (float)(2 * HeadFootSize);", " for (adjust = 0.0, pos = 0; pos < 3; pos ++)\n {\n if (Header[pos] &&\n (strstr(Header[pos], \"$IMAGE\") != NULL ||\n\t strstr(Header[pos], \"$HFIMAGE\") != NULL ||\n\t strstr(Header[pos], \"$LETTERHEAD\") != NULL))\n temp_adjust = image_adjust;\n else if (Header1[pos] &&\n\t (strstr(Header1[pos], \"$IMAGE\") != NULL ||\n\t strstr(Header1[pos], \"$HFIMAGE\") != NULL ||\n\t strstr(Header1[pos], \"$LETTERHEAD\") != NULL))\n temp_adjust = image_adjust;\n else if (Header[pos] || Header1[pos])\n temp_adjust = (float)(2 * HeadFootSize);\n else\n temp_adjust = 0.0;", " if (temp_adjust > adjust)\n adjust = temp_adjust;\n }", " top = PagePrintLength - adjust;", " // Adjust bottom margin as needed...\n for (adjust = 0.0, pos = 0; pos < 3; pos ++)\n {\n if (Footer[pos] &&\n (strstr(Footer[pos], \"$IMAGE\") != NULL ||\n\t strstr(Footer[pos], \"$HFIMAGE\") != NULL ||\n\t strstr(Footer[pos], \"$LETTERHEAD\") != NULL))\n temp_adjust = image_adjust;\n else if (Footer[pos])\n temp_adjust = (float)(2 * HeadFootSize);\n else\n temp_adjust = 0.0;", " if (temp_adjust > adjust)\n adjust = temp_adjust;\n }", " bottom = adjust;", " y = top;", " parse_doc(document, &left, &right, &bottom, &top, &x, &y, &page, NULL, &needspace);", " if (PageDuplex && (num_pages & 1))\n {\n if (PSLevel == 0)\n chapter_ends[chapter] = num_pages - 1;", " check_pages(num_pages);", " if (PSLevel > 0)\n chapter_ends[chapter] = num_pages - 1;\n }\n else\n chapter_ends[chapter] = num_pages - 1;", " for (chapter = 1; chapter <= TocDocCount; chapter ++)\n for (page = chapter_starts[chapter]; page <= chapter_ends[chapter]; page ++)\n pspdf_prepare_page(page);", " /*\n * Parse the table-of-contents if necessary...\n */", " if (TocLevels > 0 && num_headings > 0)\n {\n // Restore default page size, etc...\n PageWidth = toc_width;\n PageLength = toc_length;\n PageLeft = toc_left;\n PageRight = toc_right;\n PageBottom = toc_bottom;\n PageTop = toc_top;\n Landscape = toc_landscape;\n PageDuplex = toc_duplex;", " if (Landscape)\n {\n PagePrintWidth = PageLength - PageLeft - PageRight;\n PagePrintLength = PageWidth - PageTop - PageBottom;\n }\n else\n {\n PagePrintWidth = PageWidth - PageLeft - PageRight;\n PagePrintLength = PageLength - PageTop - PageBottom;\n }", " // Adjust top margin as needed...\n for (pos = 0; pos < 3; pos ++)\n if (TocHeader[pos])\n\tbreak;", " if (pos == 3)\n top = PagePrintLength;\n else if (maxhfheight > HeadFootSize)\n top = (float)(PagePrintLength - maxhfheight - HeadFootSize);\n else\n top = (float)(PagePrintLength - 2 * HeadFootSize);", " // Adjust bottom margin as needed...\n for (pos = 0; pos < 3; pos ++)\n if (TocFooter[pos])\n\tbreak;", " if (pos == 3)\n bottom = 0.0f;\n else if (maxhfheight > HeadFootSize)\n bottom = (float)(maxhfheight + HeadFootSize);\n else\n bottom = (float)(2 * HeadFootSize);", " y = 0.0;\n page = num_pages - 1;\n heading = 0;\n chapter_starts[0] = num_pages;\n chapter = 0;", " parse_contents(toc, 0, PagePrintWidth, bottom, top, &y, &page, &heading, 0);\n if (PageDuplex && (num_pages & 1))\n check_pages(num_pages);\n chapter_ends[0] = num_pages - 1;", " for (page = chapter_starts[0]; page <= chapter_ends[0]; page ++)\n pspdf_prepare_page(page);\n }", " if (TocDocCount > MAX_CHAPTERS)\n TocDocCount = MAX_CHAPTERS;", " /*\n * Do we have any pages?\n */", " if (num_pages > 0 && TocDocCount > 0)\n {\n /*\n * Yes, write the document to disk...\n */", " pspdf_prepare_outpages();", " pspdf_debug_stats();", " progress_error(HD_ERROR_NONE, \"PAGES: %d\", (int)num_outpages);", " if (PSLevel > 0)\n ps_write_document(author, creator, copyright, keywords, subject, lang);\n else\n pdf_write_document(author, creator, copyright, keywords, subject, lang,\n document, toc);\n }\n else\n {\n /*\n * No, show an error...\n */", " pspdf_debug_stats();", " progress_error(HD_ERROR_NO_PAGES,\n \"Error: no pages generated! (did you remember to use webpage mode?\");\n }", " /*\n * Free memory...\n */", " if (doc_title != NULL)\n free(doc_title);", " if (alloc_links)\n {\n free(links);", " num_links = 0;\n alloc_links = 0;\n links = NULL;\n }", " for (i = 0; i < (int)num_pages; i ++)\n {\n if ((i == 0 || pages[i].chapter != pages[i - 1].chapter) &&\n pages[i].chapter)\n free(pages[i].chapter);", " if ((i == 0 || pages[i].heading != pages[i - 1].heading) &&\n pages[i].heading)\n free(pages[i].heading);", " if (!pages[i].heading)\n continue;", " for (j = 0; j < 3; j ++)\n {\n if (!pages[i].header[j])\n continue;", " if (i == 0 || pages[i].header[j] != pages[i - 1].header[j])\n free(pages[i].header[j]);\n }", " for (j = 0; j < 3; j ++)\n {\n if (!pages[i].header1[j])\n continue;", " if (i == 0 || pages[i].header1[j] != pages[i - 1].header1[j])\n free(pages[i].header1[j]);\n }", " for (j = 0; j < 3; j ++)\n {\n if (!pages[i].footer[j])\n continue;", " if (i == 0 || pages[i].footer[j] != pages[i - 1].footer[j])\n free(pages[i].footer[j]);\n }\n }", " for (i = 0; i < 3; i ++)\n {\n Header[i] = NULL;\n Header1[i] = NULL;\n Footer[i] = NULL;\n TocHeader[i] = NULL;\n TocFooter[i] = NULL;\n }", " if (alloc_pages)\n {\n free(pages);\n free(outpages);", " num_pages = 0;\n alloc_pages = 0;\n pages = NULL;\n }", " if (alloc_headings)\n {\n free(heading_pages);\n free(heading_tops);", " num_headings = 0;\n alloc_headings = 0;\n heading_pages = NULL;\n heading_tops = NULL;\n }", " return (0);\n}", "", "//\n// 'pspdf_debug_stats()' - Display debug statistics for render memory use.\n//", "static void\npspdf_debug_stats()\n{\n const char\t*debug;\t\t\t// HTMLDOC_DEBUG env var\n int\t\ti;\t\t\t// Looping var\n render_t\t*r;\t\t\t// Render node\n int\t\tbytes;\t\t\t// Number of bytes", "\n if ((debug = getenv(\"HTMLDOC_DEBUG\")) == NULL ||\n (strstr(debug, \"all\") == NULL && strstr(debug, \"memory\") == NULL))\n return;", " bytes = alloc_headings * sizeof(int) * 2;", " bytes += alloc_pages * sizeof(page_t);\n for (i = 0; i < (int)num_pages; i ++)\n {\n for (r = pages[i].start; r != NULL; r = r->next)\n {\n bytes += sizeof(render_t);", " if (r->type == RENDER_TEXT)\n bytes += strlen((char *)r->data.text.buffer);\n }\n }", " bytes += num_outpages * sizeof(outpage_t);\n bytes += alloc_links * sizeof(link_t);\n bytes += alloc_objects * sizeof(int);", " progress_error(HD_ERROR_NONE, \"DEBUG: Render Data = %d kbytes\",\n (bytes + 1023) / 1024);\n}", "\n/*\n * 'pspdf_transform_coords()' - Transform page coordinates.\n */", "static void\npspdf_transform_coords(page_t *p,\t// I - Page\n float &x,\t// IO - X coordinate\n\t\t float &y)\t// IO - Y coordinate\n{\n float tx, ty;\t\t\t\t// Temporary X and Y", "\n tx = x;\n ty = y;\n x = tx * p->outmatrix[0][0] + ty * p->outmatrix[0][1] + p->outmatrix[0][2];\n y = tx * p->outmatrix[1][0] + ty * p->outmatrix[1][1] + p->outmatrix[1][2];\n}", "\n/*\n * 'pspdf_transform_page()' - Transform a page.\n */", "static void\npspdf_transform_page(int outpage,\t// I - Output page\n int pos,\t\t// I - Position on page\n int page)\t\t// I - Input page\n{\n outpage_t\t*op;\t\t\t// Current output page\n page_t\t*bp;\t\t\t// Current base page\n page_t\t*p;\t\t\t// Current input page\n int\t\tx, y;\t\t\t// Position on output page\n double\tw, l,\t\t\t// Width and length of subpage\n\t\ttx, ty;\t\t\t// Translation values for subpage\n double\tpw, pl;\t\t\t// Printable width and length of full page", "\n DEBUG_printf((\"pspdf_transform_page(outpage = %d, pos = %d, page = %d)\\n\",\n outpage, pos, page));", " if (pos > 15)\n progress_error(HD_ERROR_INTERNAL_ERROR, \"Internal error: pos = %d\", pos);", " op = outpages + outpage;\n op->pages[pos] = page;\n bp = pages + op->pages[0];\n p = pages + page;\n p->outpage = outpage;\n pw = bp->width;\n pl = bp->length;", " DEBUG_printf((\" width = %d, length = %d\\n\", p->width, p->length));", " switch (op->nup)\n {\n default :\n case 1 :\n p->outmatrix[0][0] = 1.0f;\n p->outmatrix[1][0] = 0.0f;\n p->outmatrix[0][1] = 0.0f;\n p->outmatrix[1][1] = 1.0f;\n p->outmatrix[0][2] = 0.0f;\n p->outmatrix[1][2] = 0.0f;\n\tbreak;", " case 2 :\n\tx = pos & 1;", " l = pw;\n w = l * p->width / p->length;", " if (w > (pl * 0.5f))\n {\n w = pl * 0.5f;\n l = w * p->length / p->width;\n }", " tx = 0.5 * (pl * 0.5 - w);\n ty = 0.5 * (pw - l);", " p->outmatrix[0][0] = 0.0f;\n p->outmatrix[1][0] = (float)(w / p->width);\n p->outmatrix[0][1] = (float)(-w / p->width);\n p->outmatrix[1][1] = 0.0f;\n p->outmatrix[0][2] = (float)(ty + pl * w / p->width);\n p->outmatrix[1][2] = (float)(tx + x * pl / 2);\n\tbreak;", " case 4 :\n x = pos & 1;\n\ty = 1 - pos / 2;", " w = pw * 0.5;\n\tl = w * p->length / p->width;", "\tif (l > (pl * 0.5))\n\t{\n\t l = pl * 0.5;\n\t w = l * p->width / p->length;\n\t}", " tx = 0.5 * (pw * 0.5 - w);\n ty = 0.5 * (pl * 0.5 - l);", " p->outmatrix[0][0] = (float)(w / p->width);\n p->outmatrix[1][0] = 0.0f;\n p->outmatrix[0][1] = 0.0f;\n p->outmatrix[1][1] = (float)(w / p->width);\n p->outmatrix[0][2] = (float)(tx + x * pw / 2);\n p->outmatrix[1][2] = (float)(ty + y * pl / 2);\n\tbreak;", " case 6 :\n x = pos % 3;\n\ty = pos / 3;", " l = pw * 0.5;\n w = l * p->width / p->length;", " if (w > (pl * 0.333f))\n {\n w = pl * 0.333f;\n l = w * p->length / p->width;\n }", " tx = 0.5 * (pl * 0.333 - w);\n ty = 0.5 * (pw * 0.5 - l);", " p->outmatrix[0][0] = 0.0f;\n p->outmatrix[1][0] = (float)(w / p->width);\n p->outmatrix[0][1] = (float)(-w / p->width);\n p->outmatrix[1][1] = 0.0f;\n p->outmatrix[0][2] = (float)(ty + y * pw / 2 + pl * w / p->width);\n p->outmatrix[1][2] = (float)(tx + x * pl / 3);\n\tbreak;", " case 9 :\n x = pos % 3;\n\ty = 2 - pos / 3;", " w = pw * 0.333;\n\tl = w * p->length / p->width;", "\tif (l > (pl * 0.333))\n\t{\n\t l = pl * 0.333;\n\t w = l * p->width / p->length;\n\t}", " tx = 0.5 * (pw * 0.333 - w);\n ty = 0.5 * (pl * 0.333 - l);", " p->outmatrix[0][0] = (float)(w / p->width);\n p->outmatrix[1][0] = 0.0f;\n p->outmatrix[0][1] = 0.0f;\n p->outmatrix[1][1] = (float)(w / p->width);\n p->outmatrix[0][2] = (float)(tx + x * pw / 3);\n p->outmatrix[1][2] = (float)(ty + y * pl / 3);\n\tbreak;", " case 16 :\n x = pos & 3;\n\ty = 3 - pos / 4;", " w = pw * 0.25;\n\tl = w * p->length / p->width;", "\tif (l > (pl * 0.25))\n\t{\n\t l = pl * 0.25;\n\t w = l * p->width / p->length;\n\t}", " tx = 0.5 * (pw * 0.25 - w);\n ty = 0.5 * (pl * 0.25 - l);", " p->outmatrix[0][0] = (float)(w / p->width);\n p->outmatrix[1][0] = 0.0f;\n p->outmatrix[0][1] = 0.0f;\n p->outmatrix[1][1] = (float)(w / p->width);\n p->outmatrix[0][2] = (float)(tx + x * pw / 4);\n p->outmatrix[1][2] = (float)(ty + y * pl / 4);\n\tbreak;\n }\n}", "\n/*\n * 'pspdf_prepare_outpages()' - Prepare output pages...\n */", "static void\npspdf_prepare_outpages()\n{\n int\t\tc, i, j;\t/* Looping vars */\n int\t\tnup;\t\t/* Current number-up value */\n page_t\t*page;\t\t/* Current page */\n outpage_t\t*outpage;\t/* Current output page */", "\n // Allocate an output page array...\n outpages = (outpage_t *)malloc(sizeof(outpage_t) * num_pages);", " memset(outpages, -1, sizeof(outpage_t) * num_pages);", " num_outpages = 0;\n outpage = outpages;", " // Handle the title page, as needed...\n if (TitlePage)\n {\n for (i = 0, j = 0, nup = -1, page = pages;\n i < chapter_starts[1];\n\t i ++, page ++)\n {\n if (nup != page->nup)\n {\n if (j)\n\t{\n\t // Break the current output page...\n\t outpage ++;\n\t num_outpages ++;\n\t}", "\tnup = page->nup;\n\tj = 0;\n }", " if (!j)\n\toutpage->nup = nup;", " pspdf_transform_page(num_outpages, j, i);\n j ++;", " if (j >= nup)\n {\n j = 0;\n\toutpage ++;\n\tnum_outpages ++;\n }\n }", " if (j)\n {\n // Break the current output page...\n outpage ++;\n num_outpages ++;\n }\n }", " // Loop through each chapter, adding pages as needed...\n if (OutputType == OUTPUT_BOOK && TocLevels > 0)\n c = 0;\n else\n c = 1;", " for (; c <= TocDocCount; c ++)\n {\n if (chapter_starts[c] < 0)\n continue;", " chapter_outstarts[c] = num_outpages;", " for (i = chapter_starts[c], j = 0, nup = -1, page = pages + i;", " i <= chapter_ends[c];", "\t i ++, page ++)\n {\n if (nup != page->nup)\n {\n if (j)\n\t{\n\t // Break the current output page...\n\t outpage ++;\n\t num_outpages ++;\n\t}", "\tnup = page->nup;\n\tj = 0;\n }", " if (!j)\n\toutpage->nup = nup;", " pspdf_transform_page(num_outpages, j, i);\n j ++;", " if (j >= nup)\n {\n j = 0;\n\toutpage ++;\n\tnum_outpages ++;\n }\n }", " if (j)\n {\n // Break the current output page...\n outpage ++;\n num_outpages ++;\n }", " chapter_outends[c] = num_outpages;\n }", "#ifdef DEBUG\n for (c = 0; c <= TocDocCount; c ++)\n printf(\"chapter_outstarts[%d] = %d, chapter_outends[%d] = %d\\n\",\n c, chapter_outstarts[c], c, chapter_outends[c]);", " printf(\"num_outpages = %d\\n\", (int)num_outpages);\n for (i = 0, outpage = outpages; i < (int)num_outpages; i ++, outpage ++)\n {\n printf(\"outpage[%d]:\\tnup=%d, pages=[\", i, outpage->nup);\n for (j = 0; j < outpage->nup; j ++)\n printf(\" %d\", outpage->pages[j]);\n puts(\" ]\");\n page = pages + outpage->pages[0];\n printf(\"\\t\\twidth = %d, length = %d\\n\", page->width, page->length);\n }", " for (c = 0; c <= TocDocCount; c ++)\n printf(\"chapter_starts[%d] = %d, chapter_ends[%d] = %d\\n\",\n c, chapter_starts[c], c, chapter_ends[c]);", " for (i = 0; i < (int)num_pages; i ++)\n printf(\"pages[%d]->outpage = %d\\n\", i, pages[i].outpage);", " for (i = 0; i < (int)num_headings; i ++)\n printf(\"heading_pages[%d] = %d\\n\", i, heading_pages[i]);", " for (i = 0; i < (int)num_links; i ++)\n printf(\"links[%d].name = \\\"%s\\\", page = %d\\n\", i,\n links[i].name, links[i].page);\n#endif // DEBUG\n}", "\n/*\n * 'pspdf_prepare_page()' - Add headers/footers to page before writing...\n */", "static void\npspdf_prepare_page(int page)\t\t/* I - Page number */\n{\n int\tprint_page;\t\t\t/* Printed page # */\n char\tpage_text[64];\t\t\t/* Page number text */\n int\ttop;\t\t\t\t/* Top of page */", "\n DEBUG_printf((\"pspdf_prepare_page(%d)\\n\", page));\n if (page < 0 || page >= num_pages)\n return;", " /*\n * Make a page number; use roman numerals for the table of contents\n * and arabic numbers for all others...\n */", " if (chapter == 0 && OutputType == OUTPUT_BOOK)\n {\n print_page = page - chapter_starts[0] + 1;\n strlcpy(page_text, format_number(print_page, 'i'), sizeof(page_text));\n }\n else if (chapter < 0)\n {\n print_page = 0;\n // Safe because page_text is more than 6 chars\n strlcpy(page_text, (page & 1) ? (char *)\"eltit\" : (char *)\"title\", sizeof(page_text));\n }\n else\n {\n print_page = page - chapter_starts[1] + 1;\n strlcpy(page_text, format_number(print_page, '1'), sizeof(page_text));\n }", " DEBUG_printf((\"BEFORE page %d page_text is \\\"%s\\\"...\\n\", page, page_text));", " DEBUG_printf((\" header[0] = \\\"%s\\\"\\n\", pages[page].header[0]));\n DEBUG_printf((\" header[1] = \\\"%s\\\"\\n\", pages[page].header[1]));\n DEBUG_printf((\" header[2] = \\\"%s\\\"\\n\", pages[page].header[2]));", " /*\n * Add page headings...\n */", " if (pages[page].landscape)\n {\n PagePrintWidth = pages[page].length - pages[page].right - pages[page].left;\n PagePrintLength = pages[page].width - pages[page].top - pages[page].bottom;\n }\n else\n {\n PagePrintWidth = pages[page].width - pages[page].right - pages[page].left;\n PagePrintLength = pages[page].length - pages[page].top - pages[page].bottom;\n }", " top = (int)(PagePrintLength - HeadFootSize);", " if (chapter == 0)\n {\n /*\n * Add table-of-contents header & footer...\n */", " pspdf_prepare_heading(page, print_page, pages[page].header, top,\n page_text, sizeof(page_text));\n pspdf_prepare_heading(page, print_page, pages[page].footer, 0,\n page_text, sizeof(page_text));\n }\n else if (chapter > 0 && !title_page)\n {\n /*\n * Add chapter header & footer...\n */", " if (page > chapter_starts[chapter] || OutputType != OUTPUT_BOOK)\n pspdf_prepare_heading(page, print_page, pages[page].header, top,\n page_text, sizeof(page_text));\n else\n pspdf_prepare_heading(page, print_page, pages[page].header1, top,\n page_text, sizeof(page_text));\n pspdf_prepare_heading(page, print_page, pages[page].footer, 0,\n page_text, sizeof(page_text));\n }", " /*\n * Copy the page number for the TOC...\n */", " strlcpy(pages[page].page_text, page_text, sizeof(pages[page].page_text));", " DEBUG_printf((\"AFTER page %d page_text is \\\"%s\\\"...\\n\", page, page_text));\n}", "\n/*\n * 'pspdf_prepare_heading()' - Add headers/footers to page before writing...\n */", "static void\npspdf_prepare_heading(int page,\t// I - Page number\n int print_page,\t// I - Printed page number\n\t\t uchar **format,\t// I - Page headings\n\t\t int y,\t\t// I - Baseline of heading\n\t\t char *page_text,\t// O - Page number text\n\t\t int page_len)\t// I - Size of page text\n{\n int\t\tpos,\t\t\t// Position in heading\n\t\tdir;\t\t\t// Direction of page\n char\t\t*number;\t\t// Page number\n char\t\tbuffer[1024],\t\t// String buffer\n\t\t*bufptr,\t\t// Pointer into buffer\n\t\t*formatptr;\t\t// Pointer into format string\n int\t\tformatlen;\t\t// Length of format command string\n render_t\t*temp;\t\t\t// Render structure for titles, etc.", "\n DEBUG_printf((\"pspdf_prepare_heading(%d, %d, [\\\"%s\\\",\\\"%s\\\",\\\"%s\\\"], %d, %p, %d)\\n\",\n page, print_page, format[0], format[1], format[2], y,\n\t\t(void *)page_text, page_len));", " /*\n * Add page headings...\n */", " if (PageDuplex && (page & 1))\n {\n dir = -1;\n format += 2;\n }\n else\n dir = 1;", " for (pos = 0; pos < 3; pos ++, format += dir)\n {\n /*\n * Add the appropriate object...\n */", " if (!*format)\n continue;", " temp = NULL;", " if (strncasecmp((char *)*format, \"$LOGOIMAGE\", 10) == 0 && logo_image)\n {\n // Insert the logo image...\n if (y < (PagePrintLength / 2))\n\ttemp = new_render(page, RENDER_IMAGE, 0, y, logo_width,\n\t logo_height, logo_image);\n else // Offset from top\n\ttemp = new_render(page, RENDER_IMAGE, 0,\n\t y + HeadFootSize - logo_height,\n\t logo_width, logo_height, logo_image);\n }\n else if (strncasecmp((char *)*format, \"$LETTERHEAD\", 11) == 0 && lh_image)\n {\n // Insert the logo image as a letterhead...\n if (y < (PagePrintLength / 2))\n\ttemp = new_render(page, RENDER_IMAGE, 0, y, lh_width, lh_height, lh_image);\n else // Offset from top\n\ttemp = new_render(page, RENDER_IMAGE, 0, y + HeadFootSize - lh_height, lh_width, lh_height, lh_image);\n }\n else if (strncasecmp((char *)*format, \"$HFIMAGE\", 8) == 0)\n {\n int\thfi;\t\t\t// Header/footer image index\n char\t*hfp;\t\t\t// Pointer into $HFIMAGE", "\n hfi = strtol((char*)((*format) + 8), &hfp, 10);", " if (hfi < 0 || hfi >= MAX_HF_IMAGES || !(isspace(*hfp) || !*hfp))\n progress_error(HD_ERROR_BAD_HF_STRING,\n\t \"Bad $HFIMAGE... substitution on page %d.\", page + 1);\n else\n {\n if (y < (PagePrintLength / 2))\n temp = new_render(page, RENDER_IMAGE, 0, y, hfimage_width[hfi],\n hfimage_height[hfi], hfimage[hfi]);\n else\n temp = new_render(page, RENDER_IMAGE, 0,\n y + HeadFootSize - hfimage_height[hfi],\n hfimage_width[hfi], hfimage_height[hfi],\n\t\t\t hfimage[hfi]);\n }\n }\n else\n {\n // Otherwise format the text...\n buffer[sizeof(buffer) - 1] = '\\0';", " for (bufptr = buffer, formatptr = (char *)*format; *formatptr;)\n {\n if (*formatptr == '$')\n\t{\n\t if (formatptr[1] == '$')\n\t {\n\t if (bufptr < (buffer + sizeof(buffer) - 1))\n\t *bufptr++ = '$';", "\t formatptr += 2;\n\t continue;\n\t }\n\t else if (!formatptr[1])\n\t break;", " formatptr ++;\n\t for (formatlen = 1; isalpha(formatptr[formatlen]); formatlen ++);", "\t if (formatlen == 4 && strncasecmp(formatptr, \"PAGE\", 4) == 0)\n\t {\n\t if (formatptr[4] == '(' && formatptr[5] && formatptr[6] == ')')\n {\n\t number = format_number(print_page, formatptr[5]);\n\t formatptr += 7;\n\t }\n\t else\n\t {\n\t number = format_number(print_page, '1');\n\t formatptr += 4;\n\t }", " strlcpy(bufptr, number, sizeof(buffer) - (size_t)(bufptr - buffer));\n\t bufptr += strlen(bufptr);\n\t }\n\t else if (formatlen == 5 && strncasecmp(formatptr, \"PAGES\", 5) == 0)\n\t {\n\t if (formatptr[5] == '(' && formatptr[6] && formatptr[7] == ')')\n {\n\t number = format_number(chapter_ends[TocDocCount] -\n\t chapter_starts[1] + 1, formatptr[6]);\n\t formatptr += 8;\n\t }\n\t else\n\t {\n\t number = format_number(chapter_ends[TocDocCount] -\n\t chapter_starts[1] + 1, '1');\n\t formatptr += 5;\n\t }", " strlcpy(bufptr, number, sizeof(buffer) - (size_t)(bufptr - buffer));\n\t bufptr += strlen(bufptr);\n\t }\n\t else if (formatlen == 11 && strncasecmp(formatptr, \"CHAPTERPAGE\", 11) == 0)\n\t {\n\t int chapter_page;", "\t chapter_page = print_page - chapter_starts[::chapter] +\n\t chapter_starts[1];", "\t if (formatptr[11] == '(' && formatptr[12] && formatptr[13] == ')')\n {\n\t number = format_number(chapter_page, formatptr[12]);\n\t formatptr += 14;\n\t }\n\t else\n\t {\n\t number = format_number(chapter_page, '1');\n\t formatptr += 11;\n\t }", " strlcpy(bufptr, number, sizeof(buffer) - (size_t)(bufptr - buffer));\n\t bufptr += strlen(bufptr);\n\t }\n\t else if (formatlen == 12 && strncasecmp(formatptr, \"CHAPTERPAGES\", 12) == 0)\n\t {\n\t if (formatptr[12] == '(' && formatptr[13] && formatptr[14] == ')')\n {\n\t number = format_number(chapter_ends[::chapter] -\n\t chapter_starts[::chapter] + 1,\n\t\t\t\t formatptr[13]);\n\t formatptr += 15;\n\t }\n\t else\n\t {\n\t number = format_number(chapter_ends[::chapter] -\n\t chapter_starts[::chapter] + 1, '1');\n\t formatptr += 12;\n\t }", " strlcpy(bufptr, number, sizeof(buffer) - (size_t)(bufptr - buffer));\n\t bufptr += strlen(bufptr);\n\t }\n\t else if (formatlen == 5 && strncasecmp(formatptr, \"TITLE\", 5) == 0)\n\t {\n formatptr += 5;\n\t if (doc_title)\n\t {\n strlcpy(bufptr, (char *)doc_title, sizeof(buffer) - (size_t)(bufptr - buffer));\n\t bufptr += strlen(bufptr);\n\t }\n\t }\n\t else if (formatlen == 7 && strncasecmp(formatptr, \"CHAPTER\", 7) == 0)\n\t {\n formatptr += 7;\n\t if (pages[page].chapter)\n\t {\n strlcpy(bufptr, (char *)(pages[page].chapter), sizeof(buffer) - (size_t)(bufptr - buffer));\n\t bufptr += strlen(bufptr);\n\t }\n\t }\n\t else if (formatlen == 7 && strncasecmp(formatptr, \"HEADING\", 7) == 0)\n\t {\n formatptr += 7;\n\t if (pages[page].heading)\n\t {\n strlcpy(bufptr, (char *)(pages[page].heading), sizeof(buffer) - (size_t)(bufptr - buffer));\n\t bufptr += strlen(bufptr);\n\t }\n\t }\n\t else if (formatlen == 4 && strncasecmp(formatptr, \"TIME\", 4) == 0)\n\t {\n formatptr += 4;\n strftime(bufptr, sizeof(buffer) - 1 - (size_t)(bufptr - buffer), \"%X\", &doc_date);\n\t bufptr += strlen(bufptr);\n\t }\n\t else if (formatlen == 4 && strncasecmp(formatptr, \"DATE\", 4) == 0)\n\t {\n formatptr += 4;\n strftime(bufptr, sizeof(buffer) - 1 - (size_t)(bufptr - buffer), \"%x\", &doc_date);\n\t bufptr += strlen(bufptr);\n\t }\n\t else if (formatlen == 3 && strncasecmp(formatptr, \"URL\", 3) == 0)\n\t {\n uchar *url = pages[page].url ? pages[page].url : (uchar *)\"Unknown\";", " formatptr += 3;\n strlcpy(bufptr, (char *)url, sizeof(buffer) - (size_t)(bufptr - buffer));\n\t bufptr += strlen(bufptr);\n\t }\n\t else\n\t {\n progress_error(HD_ERROR_BAD_HF_STRING, \"Bad header/footer $ command on page %d.\", page + 1);", " strlcpy(bufptr, formatptr - 1, sizeof(buffer) - (size_t)(bufptr - buffer));\n\t bufptr += strlen(bufptr);\n\t formatptr += formatlen;\n\t }\n\t}\n\telse if (bufptr < (buffer + sizeof(buffer) - 1))\n\t *bufptr++ = *formatptr++;\n\telse\n\t break;\n }", " *bufptr = '\\0';", " temp = new_render(page, RENDER_TEXT, 0, y,\n \tget_width((uchar *)buffer, HeadFootType,\n\t\t\t HeadFootStyle, SIZE_P) * HeadFootSize /\n\t\t\t _htmlSizes[SIZE_P],\n\t \tHeadFootSize, (uchar *)buffer);", " if (strstr((char *)*format, \"$PAGE\") ||\n strstr((char *)*format, \"$CHAPTERPAGE\"))\n strlcpy(page_text, buffer, (size_t)page_len);\n }", " if (temp == NULL)\n continue;", " /*\n * Justify the object...\n */", " switch (pos)\n {\n case 0 : /* Left justified */\n break;\n case 1 : /* Centered */\n temp->x = (float)((PagePrintWidth - temp->width) * 0.5);\n break;\n case 2 : /* Right justified */\n temp->x = PagePrintWidth - temp->width;\n break;\n }", " /*\n * Set the text font and color...\n */", " if (temp->type == RENDER_TEXT)\n {\n temp->data.text.typeface = HeadFootType;\n temp->data.text.style = HeadFootStyle;\n temp->data.text.size = (float)HeadFootSize;", " get_color(_htmlTextColor, temp->data.text.rgb);\n }\n }\n}", "\n/*\n * 'ps_write_document()' - Write all render entities to PostScript file(s).\n */", "static void\nps_write_document(uchar *author,\t/* I - Author of document */\n \t uchar *creator,\t/* I - Application that generated the HTML file */\n \t uchar *copyright,\t/* I - Copyright (if any) on the document */\n uchar *keywords,\t/* I - Search keywords */\n\t\t uchar *subject,\t/* I - Subject */\n\t\t uchar *lang)\t\t/* I - Language */\n{\n FILE\t\t*out;\t\t\t/* Output file */\n int\t\tpage;\t\t\t/* Current page # */\n int\t\tfirst;\t\t\t/* First chapter */", "\n /*\n * Write the title page(s)...\n */", " chapter = -1;\n out = NULL;", " if (!OutputFiles)\n {\n out = open_file();", " if (out == NULL)\n {\n progress_error(HD_ERROR_WRITE_ERROR,\n \"Unable to open output file - %s\\n\", strerror(errno));\n return;\n }", " write_prolog(out, num_outpages, author, creator, copyright, keywords, subject);\n }", " if (OutputType == OUTPUT_BOOK && TocLevels > 0)\n first = 0;\n else\n first = 1;", " if (TitlePage)\n {\n if (OutputFiles)\n {\n out = open_file();\n write_prolog(out, chapter_outstarts[first], author, creator, copyright,\n keywords, subject);\n }", " for (page = 0; page < chapter_outstarts[first]; page ++)\n ps_write_outpage(out, page);", " if (OutputFiles)\n {\n write_trailer(out, 0, lang);", " progress_error(HD_ERROR_NONE, \"BYTES: %ld\", ftell(out));", " fclose(out);\n }\n }", " for (chapter = first; chapter <= TocDocCount; chapter ++)\n {\n if (chapter_starts[chapter] < 0)\n continue;", " if (OutputFiles)\n {\n out = open_file();\n if (out == NULL)\n {\n progress_error(HD_ERROR_WRITE_ERROR,\n\t \"Unable to create output file - %s\\n\", strerror(errno));\n return;\n }", " write_prolog(out, chapter_outends[chapter] - chapter_outstarts[chapter],\n author, creator, copyright, keywords, subject);\n }", " for (page = chapter_outstarts[chapter];\n page < chapter_outends[chapter];\n page ++)\n ps_write_outpage(out, page);", " /*\n * Close the output file as necessary...\n */", " if (OutputFiles)\n {\n write_trailer(out, 0, lang);", " progress_error(HD_ERROR_NONE, \"BYTES: %ld\", ftell(out));", " fclose(out);\n }\n }", " /*\n * Close the output file as necessary...\n */", " if (!OutputFiles)\n {\n write_trailer(out, 0, lang);", " progress_error(HD_ERROR_NONE, \"BYTES: %ld\", ftell(out));", " if (out != stdout)\n fclose(out);\n }", " if (Verbosity)\n progress_hide();\n}", "\n/*\n * 'ps_write_outpage()' - Write an output page.\n */", "static void\nps_write_outpage(FILE *out,\t/* I - Output file */\n int outpage)\t/* I - Output page number */\n{\n int\t\tfile_page;\t/* Current page # in document */\n page_t\t*p;\t\t/* Current page */\n outpage_t\t*op;\t\t/* Current output page */\n int\t\ti;\t\t/* Looping var */", "\n if (outpage < 0 || outpage >= (int)num_outpages)\n return;", " op = outpages + outpage;\n p = pages + op->pages[0];", " DEBUG_printf((\"ps_write_outpage(%p, %d)\\n\", (void *)out, outpage));", " /*\n * Let the user know which page we are writing...\n */", " if (Verbosity)\n {\n progress_show(\"Writing page %s...\", p->page_text);\n progress_update(100 * outpage / (int)num_outpages);\n }", " /*\n * Figure out the page number in the file...\n */", " if (OutputFiles && chapter >= 0)\n file_page = outpage - chapter_outstarts[chapter] + 1;\n else if (chapter < 0)\n file_page = outpage + 1;\n else if (chapter == 0)\n {\n if (TitlePage)\n file_page = outpage + 1;\n else\n file_page = outpage - chapter_outstarts[0] + 1;\n }\n else\n {\n if (TitlePage)\n file_page = outpage + 1;\n else\n file_page = outpage - chapter_outstarts[1] + 1;\n }", " /*\n * Output the page prolog...\n */", " fprintf(out, \"%%%%Page: (%s) %d\\n\", p->page_text, file_page);\n if (op->nup == 1)\n {\n if (p->duplex && !(file_page & 1))\n fprintf(out, \"%%%%PageBoundingBox: %d %d %d %d\\n\",\n p->right, p->bottom, p->width - p->left, p->length - p->top);\n else\n fprintf(out, \"%%%%PageBoundingBox: %d %d %d %d\\n\",\n p->left, p->bottom, p->width - p->right, p->length - p->top);\n }\n else\n fprintf(out, \"%%%%PageBoundingBox: 0 0 %d %d\\n\", p->width, p->length);", " if (PSLevel > 1 && PSCommands)\n {\n fputs(\"%%BeginPageSetup\\n\", out);", " if (p->width == 612 && p->length == 792)\n fputs(\"%%BeginFeature: *PageSize Letter\\n\", out);\n else if (p->width == 612 && p->length == 1008)\n fputs(\"%%BeginFeature: *PageSize Legal\\n\", out);\n else if (p->width == 792 && p->length == 1224)\n fputs(\"%%BeginFeature: *PageSize Tabloid\\n\", out);\n else if (p->width == 842 && p->length == 1190)\n fputs(\"%%BeginFeature: *PageSize A3\\n\", out);\n else if (p->width == 595 && p->length == 842)\n fputs(\"%%BeginFeature: *PageSize A4\\n\", out);\n else\n fprintf(out, \"%%%%BeginFeature: *PageSize w%dh%d\\n\", p->width,\n\t p->length);", " fprintf(out, \"%d %d SetPageSize\\n\", p->width, p->length);\n fputs(\"%%EndFeature\\n\", out);", " if (p->duplex)\n {\n if (p->landscape)\n {\n\tfputs(\"%%BeginFeature: *Duplex DuplexTumble\\n\", out);\n\tfputs(\"true true SetDuplexMode\\n\", out);\n fputs(\"%%EndFeature\\n\", out);\n }\n else\n {\n\tfputs(\"%%BeginFeature: *Duplex DuplexNoTumble\\n\", out);\n\tfputs(\"true false SetDuplexMode\\n\", out);\n fputs(\"%%EndFeature\\n\", out);\n }\n }\n else\n {\n fputs(\"%%BeginFeature: *Duplex None\\n\", out);\n fputs(\"false false SetDuplexMode\\n\", out);\n fputs(\"%%EndFeature\\n\", out);\n }", " if (p->media_color[0])\n {\n fprintf(out, \"%%%%BeginFeature: *MediaColor %s\\n\", p->media_color);\n fprintf(out, \"(%s) SetMediaColor\\n\", p->media_color);\n fputs(\"%%EndFeature\\n\", out);\n }", " if (p->media_position)\n {\n fprintf(out, \"%%%%BeginFeature: *InputSlot Tray%d\\n\",\n p->media_position);\n fprintf(out, \"%d SetMediaPosition\\n\", p->media_position);\n fputs(\"%%EndFeature\\n\", out);\n }", " if (p->media_type[0])\n {\n fprintf(out, \"%%%%BeginFeature: *MediaType %s\\n\", p->media_type);\n fprintf(out, \"(%s) SetMediaType\\n\", p->media_type);\n fputs(\"%%EndFeature\\n\", out);\n }", " fputs(\"%%EndPageSetup\\n\", out);\n }", " /*\n * Render all of the pages...\n */", " switch (op->nup)\n {\n case 1 :\n ps_write_page(out, op->pages[0]);\n\tbreak;", " default :\n for (i = 0; i < op->nup; i ++)\n\t{\n\t if (op->pages[i] < 0)\n\t break;", " p = pages + op->pages[i];", " fprintf(out, \"GS[%.3f %.3f %.3f %.3f %.3f %.3f]CM\\n\",\n\t p->outmatrix[0][0], p->outmatrix[1][0],\n\t p->outmatrix[0][1], p->outmatrix[1][1],\n\t p->outmatrix[0][2], p->outmatrix[1][2]);\n ps_write_page(out, op->pages[i]);\n\t fputs(\"GR\\n\", out);\n\t}\n\tbreak;\n }", " /*\n * Output the page trailer...\n */", " fputs(\"SP\\n\", out);\n fflush(out);\n}", "\n/*\n * 'ps_write_page()' - Write all render entities on a page to a PostScript file.\n */", "static void\nps_write_page(FILE *out,\t/* I - Output file */\n int page)\t/* I - Page number */\n{\n render_t\t*r,\t\t/* Render pointer */\n\t\t*next;\t\t/* Next render */\n page_t\t*p;\t\t/* Current page */\n const char\t*debug;\t\t/* HTMLDOC_DEBUG environment variable */", "\n if (page < 0 || page >= (int)alloc_pages)\n return;", " p = pages + page;", " DEBUG_printf((\"ps_write_page(%p, %d)\\n\", (void *)out, page));", " /*\n * Clear the render cache...\n */", " render_typeface = -1;\n render_style = -1;\n render_size = -1;\n render_rgb[0] = -1.0f;\n render_rgb[1] = -1.0f;\n render_rgb[2] = -1.0f;\n render_x = -1.0f;\n render_y = -1.0f;\n render_spacing = -1.0f;", " /*\n * Setup the page...\n */", " fputs(\"GS\\n\", out);", " if (p->landscape)\n {\n if (p->duplex && (page & 1))\n fprintf(out, \"0 %d T -90 RO\\n\", p->length);\n else\n fprintf(out, \"%d 0 T 90 RO\\n\", p->width);\n }", " write_background(page, out);", " if (p->duplex && (page & 1))\n fprintf(out, \"%d %d T\\n\", p->right, p->bottom);\n else\n fprintf(out, \"%d %d T\\n\", p->left, p->bottom);", " /*\n * Render all graphics elements...\n */", " for (r = p->start; r != NULL; r = r->next)\n switch (r->type)\n {\n case RENDER_BOX :\n\t set_color(out, r->data.box);\n\t set_pos(out, r->x, r->y);\n\t if (r->height > 0.0f)\n fprintf(out, \" %.1f %.1f F\\n\", r->width, r->height);\n\t else\n fprintf(out, \" %.1f L\\n\", r->width);", "\t render_x = -1.0f;\n\t break;", " case RENDER_IMAGE :\n if (r->width > 0.01f && r->height > 0.01f)\n write_image(out, r);\n break;\n }", " /*\n * Render all text elements, freeing used memory as we go...\n */", " for (r = p->start, next = NULL; r != NULL; r = next)\n {\n if (r->type == RENDER_TEXT)\n write_text(out, r);", " next = r->next;\n free(r);\n }", " p->start = NULL;", " if ((debug = getenv(\"HTMLDOC_DEBUG\")) != NULL && strstr(debug, \"margin\"))\n {\n // Show printable area...\n fprintf(out, \"1 0 1 C 0 0 %d %d B\\n\", p->width - p->right - p->left,\n \t p->length - p->top - p->bottom);\n }", " /*\n * Output the page trailer...\n */", " fputs(\"GR\\n\", out);\n}", "\n/*\n * 'ps_write_background()' - Write a background image...\n */", "static void\nps_write_background(FILE *out)\t\t/* I - Output file */\n{\n int\ty,\t\t\t\t/* Current line */\n\tpwidth;\t\t\t\t/* Pixel width */", "\n if (!background_image->pixels)\n image_load(background_image->filename, !OutputColor, 1);", " pwidth = background_image->width * background_image->depth;", " fputs(\"/BG[\", out);\n for (y = 0; y < background_image->height; y ++)\n {\n putc('<', out);\n ps_hex(out, background_image->pixels + y * pwidth, pwidth);\n putc('>', out);\n }\n fputs(\"]def\", out);", " image_unload(background_image);\n}", "\n/*\n * 'pdf_write_document()' - Write all render entities to a PDF file.\n */", "static void\npdf_write_document(uchar *author,\t// I - Author of document\n \t uchar *creator,\t// I - Application that generated the HTML file\n \t uchar *copyright,\t// I - Copyright (if any) on the document\n uchar *keywords,\t// I - Search keywords\n\t\t uchar *subject,\t// I - Subject\n\t\t uchar *lang,\t// I - Language\n\t\t tree_t *doc,\t\t// I - Document\n tree_t *toc)\t\t// I - Table of contents tree\n{\n int\t\ti;\t\t\t// Looping variable\n FILE\t\t*out;\t\t\t// Output file\n int\t\toutpage,\t\t// Current page #\n\t\theading;\t\t// Current heading #\n int\t\tbytes;\t\t\t// Number of bytes\n char\t\tbuffer[8192];\t\t// Copy buffer\n int\t\tnum_images;\t\t// Number of images in document\n image_t\t**images;\t\t// Pointers to images\n render_t\ttemp;\t\t\t// Dummy rendering data...", "\n // Open the output file...\n out = open_file();\n if (out == NULL)\n {\n progress_error(HD_ERROR_WRITE_ERROR,\n \"Unable to write document file - %s\\n\", strerror(errno));\n return;\n }", " // Clear the objects array...\n num_objects = 0;\n alloc_objects = 0;\n objects = NULL;", " // Write the prolog...\n write_prolog(out, num_outpages, author, creator, copyright, keywords, subject);", " // Write images as needed...\n num_images = image_getlist(&images);", " for (i = 0; i < num_images; i ++)\n {\n int\thfi;\t\t\t\t// Header/footer image index", "\n for (hfi = 0; hfi < MAX_HF_IMAGES; hfi ++)\n if (images[i] == hfimage[hfi])\n break;", " if (images[i]->use > 1 || images[i]->mask ||\n (images[i]->width * images[i]->height * images[i]->depth) > 65536 ||\n\timages[i] == background_image ||\n\timages[i] == logo_image ||\n\thfi < MAX_HF_IMAGES)\n {\n progress_show(\"Writing image %d (%s)...\", i + 1, images[i]->filename);\n progress_update(100 * i / num_images);", " temp.data.image = images[i];\n write_image(out, &temp, 1);\n }\n }", " // Write links and target names...\n pdf_write_links(out);\n if (PDFVersion >= 12)\n pdf_write_names(out);", " // Verify that everything is working so far...\n pdf_start_object(out);", " if (pages_object != (int)num_objects)\n progress_error(HD_ERROR_INTERNAL_ERROR,\n \"Internal error: pages_object != num_objects\");", " fputs(\"/Type/Pages\", out);\n fprintf(out, \"/Count %d\", (int)num_outpages);\n fputs(\"/Kids[\", out);", " for (outpage = 0; outpage < (int)num_outpages; outpage ++)\n fprintf(out, \"%d 0 R\\n\", pages_object + outpage * 2 + 1);", " fputs(\"]\", out);\n pdf_end_object(out);", " for (outpage = 0; outpage < (int)num_outpages; outpage ++)\n pdf_write_outpage(out, outpage);", " if (OutputType == OUTPUT_BOOK && TocLevels > 0)\n {\n /*\n * Write the outline tree using the table-of-contents...\n */", " heading = 0;\n#ifdef DEBUG_TOC\n pdf_text_contents(out, toc);\n#endif // DEBUG_TOC\n pdf_write_contents(out, toc, 0, 0, 0, &heading);\n }\n else\n {\n /*\n * Write the outline tree using the HTML files.\n */", " pdf_write_files(out, doc);\n }", " /*\n * Write the trailer and close the output file...\n */", " write_trailer(out, 0, lang);", " progress_error(HD_ERROR_NONE, \"BYTES: %ld\", ftell(out));", " if (CGIMode)\n {\n const char\t*meta_filename = (const char *)htmlGetMeta(doc, (uchar *)\"HTMLDOC.filename\");\n const char\t*filename;", " if (meta_filename)\n {\n if ((filename = strrchr(meta_filename, '/')) != NULL)\n filename ++;\n else\n filename = meta_filename;\n }\n else\n filename = \"htmldoc.pdf\";", " // In CGI mode, we only produce PDF output to stdout...\n printf(\"Content-Type: application/pdf\\r\\n\"\n\t \"Content-Length: %ld\\r\\n\"\n\t \"Content-Disposition: inline; filename=\\\"%s\\\"\\r\\n\"\n\t \"Accept-Ranges: none\\r\\n\"\n\t \"X-Creator: HTMLDOC \" SVERSION \"\\r\\n\"\n\t \"\\r\\n\", ftell(out), filename);\n }", " fclose(out);", " //\n // If we are sending the output to stdout, copy the temp file now...\n //", " if (!OutputPath[0])\n {\n#ifdef WIN32\n // Make sure we are in binary mode... stupid Microsoft!\n setmode(1, O_BINARY);\n#elif defined(__EMX__)\n // OS/2 has a setmode for FILE's...\n fflush(stdout);\n _fsetmode(stdout, \"b\");\n#endif // WIN32 || __EMX__", " // Open the temporary file and copy it to stdout...\n out = fopen(stdout_filename, \"rb\");", " while ((bytes = fread(buffer, 1, sizeof(buffer), out)) > 0)\n fwrite(buffer, 1, (size_t)bytes, stdout);", " // Close the temporary file (it is removed when the program exits...)\n fclose(out);\n }", " // Clear the objects array...\n if (alloc_objects)\n {\n free(objects);", " num_objects = 0;\n alloc_objects = 0;\n objects = NULL;\n }", " if (Verbosity)\n progress_hide();\n}", "\n/*\n * 'pdf_write_resources()' - Write the resources dictionary for a page.\n */", "static void\npdf_write_resources(FILE *out,\t\t/* I - Output file */\n int outpage)\t/* I - Output page for resources */\n{\n int\t\ti;\t\t\t/* Looping var */\n outpage_t\t*op;\t\t\t/* Current output page */\n page_t\t*p;\t\t\t/* Current page */\n render_t\t*r;\t\t\t/* Render pointer */\n int\t\tfonts_used[TYPE_MAX * STYLE_MAX];\n\t\t\t\t\t/* Non-zero if the page uses a font */\n int\t\timages_used;\t\t/* Non-zero if the page uses an image */\n int\t\ttext_used;\t\t/* Non-zero if the page uses text */\n static const char *effects[] =\t/* Effects and their commands */\n\t\t{\n\t\t \"\",\n\t\t \"/S/Box/M/I\",\n\t\t \"/S/Box/M/O\",\n\t\t \"/S/Dissolve\",\n\t\t \"/S/Glitter/Di 270\",\n\t\t \"/S/Glitter/Di 315\",\n\t\t \"/S/Glitter/Di 0\",\n\t\t \"/S/Blinds/Dm/H\",\n\t\t \"/S/Split/Dm/H/M/I\",\n\t\t \"/S/Split/Dm/H/M/O\",\n\t\t \"/S/Blinds/Dm/V\",\n\t\t \"/S/Split/Dm/V/M/I\",\n\t\t \"/S/Split/Dm/V/M/O\",\n\t\t \"/S/Wipe/Di 270\",\n\t\t \"/S/Wipe/Di 180\",\n\t\t \"/S/Wipe/Di 0\",\n\t\t \"/S/Wipe/Di 90\"\n\t\t};", "\n memset(fonts_used, 0, sizeof(fonts_used));\n images_used = background_image != NULL;\n text_used = 0;", " op = outpages + outpage;\n for (i = 0; i < op->nup; i ++)\n {\n if (op->pages[i] < 0)\n break;", " p = pages + op->pages[i];", " for (r = p->start; r != NULL; r = r->next)\n if (r->type == RENDER_IMAGE)\n\timages_used = 1;\n else if (r->type == RENDER_TEXT)\n {\n\ttext_used = 1;\n\tfonts_used[r->data.text.typeface * 4 + r->data.text.style] = 1;\n }\n }", " fputs(\"/Resources<<\", out);", " if (!images_used)\n fputs(\"/ProcSet[/PDF/Text]\", out);\n else if (PDFVersion >= 12)\n {\n if (OutputColor)\n fputs(\"/ProcSet[/PDF/Text/ImageB/ImageC/ImageI]\", out);\n else\n fputs(\"/ProcSet[/PDF/Text/ImageB/ImageI]\", out);\n }\n else\n {\n if (OutputColor)\n fputs(\"/ProcSet[/PDF/Text/ImageB/ImageC]\", out);\n else\n fputs(\"/ProcSet[/PDF/Text/ImageB]\", out);\n }", " if (text_used)\n {\n fputs(\"/Font<<\", out);\n for (i = 0; i < (TYPE_MAX * STYLE_MAX); i ++)\n if (fonts_used[i])\n\tfprintf(out, \"/F%x %d 0 R\", i, font_objects[i]);\n fputs(\">>\", out);\n }", " fputs(\"/XObject<<\", out);", " for (i = 0; i < op->nup; i ++)\n {\n if (op->pages[i] < 0)\n break;", " p = pages + op->pages[i];", " for (r = p->start; r != NULL; r = r->next)\n if (r->type == RENDER_IMAGE && r->data.image->obj)\n\tfprintf(out, \"/I%d %d 0 R\", r->data.image->obj, r->data.image->obj);\n }", " if (background_image)\n fprintf(out, \"/I%d %d 0 R\", background_image->obj,\n background_image->obj);", " fputs(\">>>>\", out);", " if (PDFEffect)\n fprintf(out, \"/Dur %.0f/Trans<</Type/Trans/D %.1f%s>>\", PDFPageDuration,\n PDFEffectDuration, effects[PDFEffect]);\n}", "\n/*\n * 'pdf_write_outpage()' - Write an output page.\n */", "static void\npdf_write_outpage(FILE *out,\t/* I - Output file */\n int outpage)\t/* I - Output page number */\n{\n int\t\ti;\t\t/* Looping var */\n page_t\t*p;\t\t/* Current page */\n outpage_t\t*op;\t\t/* Output page */", "\n DEBUG_printf((\"pdf_write_outpage(out = %p, outpage = %d)\\n\", (void *)out, outpage));", " if (outpage < 0 || outpage >= (int)num_outpages)\n return;", " op = outpages + outpage;\n p = pages + op->pages[0];", " DEBUG_printf((\"op->pages[0] = %d (%dx%d)\\n\", op->pages[0], p->width,\n p->length));", " /*\n * Let the user know which page we are writing...\n */", " if (Verbosity)\n {\n progress_show(\"Writing page %s...\", p->page_text);\n progress_update(100 * outpage / (int)num_outpages);\n }", " /*\n * Output the page prolog...\n */", " pdf_start_object(out);", " fputs(\"/Type/Page\", out);\n fprintf(out, \"/Parent %d 0 R\", pages_object);\n fprintf(out, \"/Contents %d 0 R\", (int)num_objects + 1);\n if (p->landscape)\n fprintf(out, \"/MediaBox[0 0 %d %d]\", p->length, p->width);\n else\n fprintf(out, \"/MediaBox[0 0 %d %d]\", p->width, p->length);", " pdf_write_resources(out, outpage);", " /*\n * Actions (links)...\n */", " if (op->annot_object > 0)\n fprintf(out, \"/Annots %d 0 R\", op->annot_object);", " pdf_end_object(out);", " pdf_start_object(out);", " if (Compression)\n fputs(\"/Filter/FlateDecode\", out);", " pdf_start_stream(out);", " flate_open_stream(out);", " /*\n * Render all of the pages...\n */", " switch (op->nup)\n {\n case 1 :\n pdf_write_page(out, op->pages[0]);\n\tbreak;", " default :\n for (i = 0; i < op->nup; i ++)\n\t{\n\t if (op->pages[i] < 0)\n\t break;", " p = pages + op->pages[i];", " flate_printf(out, \"q %.3f %.3f %.3f %.3f %.3f %.3f cm\\n\",\n\t p->outmatrix[0][0], p->outmatrix[1][0],\n\t p->outmatrix[0][1], p->outmatrix[1][1],\n\t p->outmatrix[0][2], p->outmatrix[1][2]);\n pdf_write_page(out, op->pages[i]);\n\t flate_puts(\"Q\\n\", out);\n\t}\n\tbreak;\n }", " /*\n * Close out the page...\n */", " flate_close_stream(out);", " pdf_end_object(out);\n}", "\n/*\n * 'pdf_write_page()' - Write a page to a PDF file.\n */", "static void\npdf_write_page(FILE *out,\t/* I - Output file */\n int page)\t/* I - Page number */\n{\n render_t\t*r,\t\t/* Render pointer */\n\t\t*next;\t\t/* Next render */\n float\t\tbox[3];\t\t/* RGB color for boxes */\n page_t\t*p;\t\t/* Current page */\n const char\t*debug;\t\t/* HTMLDOC_DEBUG environment variable */", "\n if (page < 0 || page >= (int)alloc_pages)\n return;", " p = pages + page;", " /*\n * Clear the render cache...\n */", " render_rgb[0] = -1.0f;\n render_rgb[1] = -1.0f;\n render_rgb[2] = -1.0f;\n render_x = -1.0f;\n render_y = -1.0f;", " /*\n * Output the page header...\n */", " flate_puts(\"q\\n\", out);\n write_background(page, out);", " if (p->duplex && (page & 1))\n flate_printf(out, \"1 0 0 1 %d %d cm\\n\", p->right,\n p->bottom);\n else\n flate_printf(out, \"1 0 0 1 %d %d cm\\n\", p->left,\n p->bottom);", " /*\n * Render all graphics elements...\n */", " box[0] = -1.0f;\n box[1] = -1.0f;\n box[2] = -1.0f;", " for (r = p->start; r != NULL; r = r->next)\n switch (r->type)\n {\n case RENDER_IMAGE :\n if (r->width > 0.01f && r->height > 0.01f)\n write_image(out, r);\n break;", " case RENDER_BOX :\n\t if (r->height == 0.0)\n\t {\n if (box[0] != r->data.box[0] ||\n\t\tbox[1] != r->data.box[1] ||\n\t\tbox[2] != r->data.box[2])\n {\n box[0] = r->data.box[0];\n\t box[1] = r->data.box[1];\n\t box[2] = r->data.box[2];", "\t if (OutputColor)\n \tflate_printf(out, \"%.2f %.2f %.2f RG\\n\", box[0], box[1], box[2]);\n else\n \tflate_printf(out, \"%.2f G\\n\",\n\t\t box[0] * 0.31f + box[1] * 0.61f + box[2] * 0.08f);\n }", " flate_printf(out, \"%.1f %.1f m %.1f %.1f l S\\n\",\n \t r->x, r->y, r->x + r->width, r->y);\n\t }\n\t else\n\t {\n set_color(out, r->data.box);\n flate_printf(out, \"%.1f %.1f %.1f %.1f re f\\n\",\n \t r->x, r->y, r->width, r->height);\n\t }\n\t break;\n }", " /*\n * Render all text elements, freeing used memory as we go...\n */", " flate_puts(\"BT\\n\", out);", " render_typeface = -1;\n render_style = -1;\n render_size = -1;\n render_x = -1.0f;\n render_y = -1.0f;\n render_spacing = -1.0f;", " for (r = p->start, next = NULL; r != NULL; r = next)\n {\n if (r->type == RENDER_TEXT)\n write_text(out, r);", " next = r->next;\n free(r);\n }", " p->start = NULL;", " flate_puts(\"ET\\n\", out);", " if ((debug = getenv(\"HTMLDOC_DEBUG\")) != NULL && strstr(debug, \"margin\"))\n {\n // Show printable area...\n flate_printf(out, \"1 0 1 RG 0 0 %d %d re S\\n\", p->width - p->right - p->left,\n \t p->length - p->top - p->bottom);\n }", " /*\n * Output the page trailer...\n */", " flate_puts(\"Q\\n\", out);\n}", "\n#ifdef DEBUG_TOC\nstatic void\npdf_text_contents(FILE *out, tree_t *toc, int indent)\n{\n static const char *spaces = \" \"\n \" \";", " if (indent > 16)\n indent = 16;", " while (toc)\n {\n fprintf(out, \"%% %s<%s>\", spaces + 64 - 4 * indent,\n _htmlMarkups[toc->markup]);", " switch (toc->markup)\n {\n case MARKUP_A :\n tree_t *temp;", " for (temp = toc->child; temp; temp = temp->next)\n\t fputs((char *)temp->data, out);\n break;", " default :\n fputs(\"\\n\", out);\n\t pdf_text_contents(out, toc->child, indent + 1);\n\t fprintf(out, \"%% %s\", spaces + 64 - 4 * indent);\n break;\n }", " fprintf(out, \"</%s>\\n\", _htmlMarkups[toc->markup]);", " toc = toc->next;\n }\n}\n#endif // DEBUG_TOC", "\n/*\n * 'pdf_write_contents()' - Write the table of contents as outline records to\n * a PDF file.\n */", "static void\npdf_write_contents(FILE *out,\t\t\t/* I - Output file */\n tree_t *toc,\t\t\t/* I - Table of contents tree */\n int parent,\t\t/* I - Parent outline object */\n int prev,\t\t\t/* I - Previous outline object */\n int next,\t\t\t/* I - Next outline object */\n int *heading)\t\t/* IO - Current heading # */\n{\n int\t\ti,\t\t\t\t/* Looping var */\n\t\tthisobj,\t\t\t/* This object */\n\t\tentry,\t\t\t\t/* TOC entry object */\n\t\tcount;\t\t\t\t/* Number of entries at this level */\n uchar\t\t*text;\t\t\t\t/* Entry text */\n tree_t\t*temp;\t\t\t\t/* Looping var */\n int\t\t*entry_counts,\t\t\t/* Number of sub-entries for this entry */\n\t\t*entry_objects;\t\t\t/* Objects for each entry */\n tree_t\t**entries;\t\t\t/* Pointers to each entry */\n float\t\tx, y;\t\t\t\t/* Position of link */", "\n /*\n * Make an object for this entry...\n */", " if (toc == NULL)\n {\n /*\n * This is for the Table of Contents page...\n */", " thisobj = pdf_start_object(out);", " fprintf(out, \"/Parent %d 0 R\", parent);", " fputs(\"/Title\", out);\n write_utf16(out, (uchar *)TocTitle);", " x = 0.0f;\n y = PagePrintLength + PageBottom;\n pspdf_transform_coords(pages + chapter_starts[0], x, y);", " fprintf(out, \"/Dest[%d 0 R/XYZ %.0f %.0f 0]\",\n pages_object + 2 * chapter_outstarts[0] + 1, x, y);", " if (prev > 0)\n fprintf(out, \"/Prev %d 0 R\", prev);", " if (next > 0)\n fprintf(out, \"/Next %d 0 R\", next);", " pdf_end_object(out);\n return;\n }", " /*\n * Allocate the arrays... Add 1 to hold the TOC at the top level...\n */", " if ((entry_counts = (int *)calloc(sizeof(int), num_headings + 1)) == NULL)\n {\n progress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory for %d headings - %s\",\n (int)num_headings, strerror(errno));\n return;\n }", " if ((entry_objects = (int *)calloc(sizeof(int), num_headings + 1)) == NULL)\n {\n progress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory for %d headings - %s\",\n (int)num_headings, strerror(errno));\n free(entry_counts);\n return;\n }", " if ((entries = (tree_t **)calloc(sizeof(tree_t *), num_headings + 1)) == NULL)\n {\n progress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory for %d headings - %s\",\n (int)num_headings, strerror(errno));\n free(entry_objects);\n free(entry_counts);\n return;\n }", " if (parent == 0 && TocLevels > 0)\n {\n /*\n * Add the table of contents to the top-level contents...\n */", " entries[0] = NULL;\n entry_objects[0] = num_objects + 2;\n entry = num_objects + 3;\n count = 1;\n }\n else\n {\n entry = num_objects + 2;\n count = 0;\n }", " /*\n * Find and count the children (entries)...\n */", " if (toc->markup == MARKUP_B && toc->next && toc->next->markup == MARKUP_UL)\n temp = toc->next->child;\n else if (toc->markup == MARKUP_LI && toc->last_child &&\n toc->last_child->markup == MARKUP_UL)\n temp = toc->last_child->child;\n else\n temp = toc->child;", " for (; temp && count <= (int)num_headings; temp = temp->next)\n {\n if (temp->markup == MARKUP_B)\n {\n entries[count] = temp;\n entry_objects[count] = entry;", " if (temp->next && temp->next->markup == MARKUP_UL)\n entry_counts[count] = pdf_count_headings(temp->next->child);\n else\n entry_counts[count] = 0;", " entry += entry_counts[count] + 1;\n count ++;\n }\n else if (temp->markup == MARKUP_LI)\n {\n entries[count] = temp;\n entry_objects[count] = entry;", " if (temp->last_child && temp->last_child->markup == MARKUP_UL)\n entry_counts[count] = pdf_count_headings(temp->last_child);\n else\n entry_counts[count] = 0;", " entry += entry_counts[count] + 1;\n count ++;\n }\n }", " /*\n * Output the top-level object...\n */", " thisobj = pdf_start_object(out);", " if (parent == 0)\n outline_object = thisobj;\n else\n fprintf(out, \"/Parent %d 0 R\", parent);", " if (count > 0)\n {\n fprintf(out, \"/Count %d\", parent == 0 ? count : -count);\n fprintf(out, \"/First %d 0 R\", entry_objects[0]);\n fprintf(out, \"/Last %d 0 R\", entry_objects[count - 1]);\n }", " if (parent > 0 && toc->child && toc->child->markup == MARKUP_A)\n {\n if ((text = htmlGetText(toc->child->child)) != NULL)\n {\n fputs(\"/Title\", out);\n write_utf16(out, text);\n free(text);\n }", " i = heading_pages[*heading];\n x = 0.0f;\n y = heading_tops[*heading] + pages[i].bottom;\n pspdf_transform_coords(pages + i, x, y);", " fprintf(out, \"/Dest[%d 0 R/XYZ %.0f %.0f 0]\",\n pages_object + 2 * pages[i].outpage + 1, x, y);", " (*heading) ++;\n }", " if (prev > 0)\n fprintf(out, \"/Prev %d 0 R\", prev);", " if (next > 0)\n fprintf(out, \"/Next %d 0 R\", next);", " pdf_end_object(out);", " for (i = 0; i < count ; i ++)\n pdf_write_contents(out, entries[i], thisobj, i > 0 ? entry_objects[i - 1] : 0,\n i < (count - 1) ? entry_objects[i + 1] : 0,\n heading);", " free(entry_objects);\n free(entry_counts);\n free(entries);\n}", "\n//\n// 'pdf_write_files()' - Write an outline of HTML files.\n//", "static void\npdf_write_files(FILE *out,\t\t// I - Output file\n tree_t *doc)\t\t// I - Document tree\n{\n int\t\ti,\t\t\t// Looping var\n\t\tnum_files,\t\t// Number of FILE elements\n\t\talloc_text;\t\t// Allocated text?\n uchar\t\t*text;\t\t\t// Entry text\n tree_t\t*temp;\t\t\t// Current node\n link_t\t*link;\t\t\t// Link to file...\n float\t\tx, y;\t\t\t// Position of link", "\n // Figure out the number of (top-level) files in the document...\n for (num_files = 0, temp = doc; temp; temp = temp->next)\n if (temp->markup == MARKUP_FILE)\n num_files ++;", " if (num_files < 2)\n {\n // No files to outline...\n outline_object = 0;", " return;\n }", " // Write the outline dictionary...\n outline_object = pdf_start_object(out);", " fprintf(out, \"/Count %d\", num_files);\n fprintf(out, \"/First %d 0 R\", outline_object + 1);\n fprintf(out, \"/Last %d 0 R\", outline_object + num_files);", " pdf_end_object(out);", " // Now write the outline items...\n for (i = 0, temp = doc; temp; temp = temp->next)\n if (temp->markup == MARKUP_FILE)\n {\n alloc_text = 0;", " if ((text = get_title(temp->child)) != NULL)\n alloc_text = 1;\n else if ((text = htmlGetVariable(temp, (uchar *)\"_HD_FILENAME\")) == NULL)\n text = (uchar *)\"Unknown\";", " pdf_start_object(out);", " fprintf(out, \"/Parent %d 0 R\", outline_object);", " fputs(\"/Title\", out);\n write_utf16(out, text);\n if (alloc_text)\n free(text);", " if ((link = find_link(htmlGetVariable(temp, (uchar *)\"_HD_FILENAME\"))) != NULL)\n {\n\tx = 0.0f;\n\ty = link->top + pages[link->page].bottom;\n\tpspdf_transform_coords(pages + link->page, x, y);", "\tfprintf(out, \"/Dest[%d 0 R/XYZ %.0f %.0f 0]\",\n \tpages_object + 2 * pages[link->page].outpage + 1, x, y);\n }", " if (i > 0)\n fprintf(out, \"/Prev %d 0 R\", outline_object + i);", " if (i < (num_files - 1))\n fprintf(out, \"/Next %d 0 R\", outline_object + i + 2);", " pdf_end_object(out);", " i ++;\n }\n}", "\n/*\n * 'pdf_count_headings()' - Count the number of headings under this TOC\n * entry.\n */", "static int\t\t\t/* O - Number of headings found */\npdf_count_headings(tree_t *toc)\t/* I - TOC entry */\n{\n int\theadings;\t\t/* Number of headings */", "\n for (headings = 0; toc != NULL; toc = toc->next)\n {\n if (toc->markup == MARKUP_A)\n headings ++;\n if (toc->child != NULL)\n headings += pdf_count_headings(toc->child);\n }", " return (headings);\n}", "\n/*\n * PDF object state variables...\n */", "static int\tpdf_stream_length = 0;\nstatic int\tpdf_stream_start = 0;\nstatic int\tpdf_object_type = 0;", "\n/*\n * 'pdf_start_object()' - Start a new PDF object...\n */", "static int\t\t\t// O - Object number\npdf_start_object(FILE *out,\t// I - File to write to\n int array)\t// I - 1 = array, 0 = dictionary\n{\n int\t*temp;\t\t\t// Temporary integer pointer", "\n num_objects ++;", " // Allocate memory as necessary...\n if (num_objects >= alloc_objects)\n {\n alloc_objects += ALLOC_OBJECTS;", " if (alloc_objects == ALLOC_OBJECTS)\n temp = (int *)malloc(sizeof(int) * alloc_objects);\n else\n temp = (int *)realloc(objects, sizeof(int) * alloc_objects);", " if (temp == NULL)\n {\n progress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory for %d objects - %s\",\n (int)alloc_objects, strerror(errno));\n alloc_objects -= ALLOC_OBJECTS;\n return (0);\n }", " objects = temp;\n }", " objects[num_objects] = ftell(out);\n fprintf(out, \"%d 0 obj\", (int)num_objects);", " pdf_object_type = array;", " fputs(pdf_object_type ? \"[\" : \"<<\", out);", " return (num_objects);\n}", "\n/*\n * 'pdf_start_stream()' - Start a new PDF stream...\n */", "static void\npdf_start_stream(FILE *out)\t// I - File to write to\n{\n // Write the \"/Length \" string, get the position, and then write 10\n // zeroes to cover the maximum size of a stream.", " fputs(\"/Length \", out);\n pdf_stream_length = ftell(out);\n fputs(\"0000000000>>stream\\n\", out);\n pdf_stream_start = ftell(out);\n}", "\n/*\n * 'pdf_end_object()' - End a PDF object...\n */", "static void\npdf_end_object(FILE *out)\t// I - File to write to\n{\n int\tlength;\t\t\t// Total length of stream", "\n if (pdf_stream_start)\n {\n // For streams, go back and update the length field in the\n // object dictionary...\n length = ftell(out) - pdf_stream_start;", " fseek(out, pdf_stream_length, SEEK_SET);\n fprintf(out, \"%-10d\", length);\n fseek(out, 0, SEEK_END);", " pdf_stream_start = 0;", " fputs(\"endstream\\n\", out);\n }\n else\n fputs(pdf_object_type ? \"]\" : \">>\", out);", " fputs(\"endobj\\n\", out);\n}", "\n/*\n * 'pdf_write_links()' - Write annotation link objects for each page in the\n * document.\n */", "static void\npdf_write_links(FILE *out)\t\t/* I - Output file */\n{\n int\t\ti,\t\t\t/* Looping var */\n\t\toutpage,\t\t/* Current page */\n\t\tlobj,\t\t\t/* Current link */\n\t\tnum_lobjs,\t\t/* Number of links on this page */\n\t\talloc_lobjs,\t\t/* Number of links to allocate */\n\t\t*lobjs;\t\t\t/* Link objects */\n float\t\tx, y;\t\t\t/* Position of last link */\n render_t\t*r,\t\t\t/* Current render primitive */\n\t\t*rlast,\t\t\t/* Last render link primitive */\n\t\t*rprev;\t\t\t/* Previous render primitive */\n link_t\t*link;\t\t\t/* Local link */\n page_t\t*p;\t\t\t/* Current page */\n outpage_t\t*op;\t\t\t/* Current output page */", "\n /*\n * First combine adjacent, identical links...\n */", " for (outpage = 0, op = outpages; outpage < (int)num_outpages; outpage ++, op ++)\n {\n for (i = 0; i < op->nup; i ++)\n {\n if (op->pages[i] < 0)\n break;", " p = pages + op->pages[i];", " for (r = p->start, x = 0.0f, y = 0.0f, rlast = NULL, rprev = NULL;\n r != NULL;\n\t rprev = r, r = r->next)\n\tif (r->type == RENDER_LINK)\n\t{\n if (fabs(r->x - x) < 0.1f && fabs(r->y - y) < 0.1f &&\n\t rlast != NULL && strcmp((const char *)rlast->data.link,\n\t (const char *)r->data.link) == 0)\n\t {\n\t // Combine this primitive with the previous one in rlast...\n\t rlast->width = r->x + r->width - rlast->x;\n\t x = rlast->x + rlast->width;", "\t // Delete this render primitive...\n\t rprev->next = r->next;\n\t free(r);\n\t r = rprev;\n\t }\n\t else\n\t {\n\t // Can't combine; just save this info for later use...\n\t rlast = r;\n\t x = r->x + r->width;\n\t y = r->y;\n\t }\n\t}\n }\n }", " /*\n * Setup the initial pages_object number...\n */", " pages_object = num_objects + 1;", " /*\n * Add space for named links in PDF 1.2 output...\n */", " if (PDFVersion >= 12)\n pages_object += num_links + 3;", " /*\n * Stop here if we won't be generating links in the output...\n */", " if (!Links)\n return;", " /*\n * Figure out how many link objects we'll have...\n */", " for (outpage = 0, op = outpages, alloc_lobjs = 0;\n outpage < (int)num_pages;\n outpage ++, op ++)\n {\n num_lobjs = 0;", " for (i = 0; i < op->nup; i ++)\n {\n if (op->pages[i] < 0)\n break;", " p = pages + op->pages[i];", " for (r = p->start; r != NULL; r = r->next)\n\tif (r->type == RENDER_LINK)\n\t{\n if (find_link(r->data.link) != NULL)\n num_lobjs ++;\n else\n num_lobjs += 2;\n\t}\n }", " if (num_lobjs > 0)\n pages_object += num_lobjs + 1;", " if (num_lobjs > alloc_lobjs)\n alloc_lobjs = num_lobjs;\n }", " if (alloc_lobjs == 0)\n return;", " /*\n * Allocate memory for the links...\n */", " if ((lobjs = (int *)malloc(sizeof(int) * (size_t)alloc_lobjs)) == NULL)\n {\n progress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory for %d link objects - %s\",\n alloc_lobjs, strerror(errno));\n return;\n }", " /*\n * Then generate annotation objects for all the links...\n */", " for (outpage = 0, op = outpages; outpage < (int)num_pages; outpage ++, op ++)\n {\n num_lobjs = 0;", " for (i = 0; i < op->nup; i ++)\n {\n if (op->pages[i] < 0)\n break;", " p = pages + op->pages[i];", " for (r = p->start; r != NULL; r = r->next)\n\tif (r->type == RENDER_LINK)\n\t{\n if ((link = find_link(r->data.link)) != NULL)\n\t {\n\t /*\n * Local link...\n */\n\t float x1, y1, x2, y2;", " lobjs[num_lobjs ++] = pdf_start_object(out);", " fputs(\"/Subtype/Link\", out);", " if (PageDuplex && (op->pages[i] & 1))\n\t {\n x1 = r->x + p->right;\n\t y1 = r->y + p->bottom - 2;\n x2 = r->x + r->width + p->right;\n\t y2 = r->y + r->height + p->bottom;\n\t }\n else\n\t {\n x1 = r->x + p->left;\n\t y1 = r->y + p->bottom - 2;\n x2 = r->x + r->width + p->left;\n\t y2 = r->y + r->height + p->bottom;\n\t }", " pspdf_transform_coords(p, x1, y1);\n pspdf_transform_coords(p, x2, y2);\n fprintf(out, \"/Rect[%.1f %.1f %.1f %.1f]\", x1, y1, x2, y2);", " fputs(\"/Border[0 0 0]\", out);", " x1 = 0.0f;\n\t y1 = link->top + pages[link->page].bottom;\n pspdf_transform_coords(pages + link->page, x1, y1);\n\t fprintf(out, \"/Dest[%d 0 R/XYZ %.0f %.0f 0]\",\n \t pages_object + 2 * pages[link->page].outpage + 1,\n \t x1, y1);\n\t pdf_end_object(out);\n\t }\n\t else\n\t {\n\t /*\n * Remote link...\n */", " pdf_start_object(out);", "\t if (PDFVersion >= 12 &&\n \tfile_method((char *)r->data.link) == NULL)\n\t {\n#ifdef WIN32\n if (strcasecmp(file_extension((char *)r->data.link), \"pdf\") == 0)\n#else\n if (strcmp(file_extension((char *)r->data.link), \"pdf\") == 0)\n#endif /* WIN32 */\n {\n\t /*\n\t\t* Link to external PDF file...\n\t\t*/", " const char *target = file_target((char *)r->data.link);", " \tfputs(\"/S/GoToR\", out);\n \tif (target)\n \t{\n \t char\turl[1024], *urlptr;", "\t\t fputs(\"/D\", out);\n\t\t write_string(out, (uchar *)target, 0);", " strlcpy(url, (char *)r->data.link, sizeof(url));\n if ((urlptr = strrchr(url, '#')) != NULL)\n *urlptr = '\\0';", "\t\t fputs(\"/F\", out);\n\t\t write_string(out, (uchar *)url, 0);\n \t}\n \telse\n \t{\n\t\t fputs(\"/D[0/XYZ null null 0]/F\", out);\n\t\t write_string(out, r->data.link, 0);\n\t\t}\n }\n\t else\n {\n\t /*\n\t\t* Link to external filename...\n\t\t*/", " \tfputs(\"/S/Launch\", out);\n \tfputs(\"/F\", out);\n\t\twrite_string(out, r->data.link, 0);", "\t\tif (StrictHTML)\n\t\t progress_error(HD_ERROR_UNRESOLVED_LINK,\n\t\t \"Unable to resolve link to \\\"%s\\\"!\",\n\t\t r->data.link);\n }\n\t }\n\t else\n\t {\n\t /*\n\t * Link to web file...\n\t */", " fputs(\"/S/URI\", out);\n fputs(\"/URI\", out);\n\t write_string(out, r->data.link, 0);\n\t }", " pdf_end_object(out);", " lobjs[num_lobjs ++] = pdf_start_object(out);", " fputs(\"/Subtype/Link\", out);\n if (PageDuplex && (outpage & 1))\n fprintf(out, \"/Rect[%.1f %.1f %.1f %.1f]\",\n r->x + PageRight, r->y + PageBottom,\n r->x + r->width + PageRight, r->y + r->height + PageBottom);\n else\n fprintf(out, \"/Rect[%.1f %.1f %.1f %.1f]\",\n r->x + PageLeft, r->y + PageBottom - 2,\n r->x + r->width + PageLeft, r->y + r->height + PageBottom);\n fputs(\"/Border[0 0 0]\", out);\n\t fprintf(out, \"/A %d 0 R\", (int)num_objects - 1);\n pdf_end_object(out);\n\t }\n\t}\n }", " if (num_lobjs > 0)\n {\n outpages[outpage].annot_object = pdf_start_object(out, 1);", " for (lobj = 0; lobj < num_lobjs; lobj ++)\n fprintf(out, \"%d 0 R%s\", lobjs[lobj],\n\t lobj < (num_lobjs - 1) ? \"\\n\" : \"\");", " pdf_end_object(out);\n }\n }", " free(lobjs);\n}", "\n/*\n * 'pdf_write_names()' - Write named destinations for each link.\n */", "static void\npdf_write_names(FILE *out)\t\t/* I - Output file */\n{\n int\t\ti;\t\t\t/* Looping var */\n uchar\t\t*s;\t\t\t/* Current character in name */\n link_t\t*link;\t\t\t/* Local link */", "\n /*\n * Convert all link names to lowercase...\n */", " for (i = num_links, link = links; i > 0; i --, link ++)\n for (s = link->name; *s != '\\0'; s ++)\n *s = (uchar)tolower(*s);", " /*\n * Write the root name tree entry...\n */", " names_object = pdf_start_object(out);\n fprintf(out, \"/Dests %d 0 R\", (int)num_objects + 1);\n pdf_end_object(out);", " /*\n * Write the name tree child list...\n */", " pdf_start_object(out);\n fprintf(out, \"/Kids[%d 0 R]\", (int)num_objects + 1);\n pdf_end_object(out);", " /*\n * Write the leaf node for the name tree...\n */", " pdf_start_object(out);", " fputs(\"/Limits[\", out);\n write_string(out, links[0].name, 0);\n write_string(out, links[num_links - 1].name, 0);\n fputs(\"]\", out);", " fputs(\"/Names[\", out);\n for (i = 1, link = links; i <= (int)num_links; i ++, link ++)\n {\n write_string(out, link->name, 0);\n fprintf(out, \"%d 0 R\", (int)num_objects + i);\n }\n fputs(\"]\", out);", " pdf_end_object(out);", " for (i = num_links, link = links; i > 0; i --, link ++)\n {\n pdf_start_object(out);\n float x, y;", " x = 0.0f;\n y = link->top + pages[link->page].bottom;\n pspdf_transform_coords(pages + link->page, x, y);\n fprintf(out, \"/D[%d 0 R/XYZ %.0f %.0f 0]\",\n pages_object + 2 * pages[link->page].outpage + 1, x, y);\n pdf_end_object(out);\n }\n}", "\n/*\n * 'render_contents()' - Render a single heading.\n */", "static void\nrender_contents(tree_t *t,\t\t/* I - Tree to parse */\n float left,\t\t/* I - Left margin */\n float right,\t\t/* I - Printable width */\n float bottom,\t\t/* I - Bottom margin */\n float top,\t\t/* I - Printable top */\n float *y,\t\t/* IO - Y position */\n int *page,\t\t/* IO - Page # */\n\t int heading,\t\t/* I - Heading # */\n\t tree_t *chap)\t\t/* I - Chapter heading */\n{\n float\t\tx,\n\t\twidth,\n\t\tnumberwidth,\n\t\theight,\n\t\trgb[3];\n int\t\thpage;\n uchar\t\tnumber[1024],\n\t\t*nptr,\n\t\t*link;\n tree_t\t*flat,\n\t\t*temp,\n\t\t*next;\n render_t\t*r;\n float\t\tdot_width;", "\n DEBUG_printf((\"render_contents(t=%p, left=%.1f, right=%.1f, bottom=%.1f, top=%.1f, y=%.1f, page=%d, heading=%d, chap=%p)\\n\",\n (void *)t, left, right, bottom, top, *y, *page, heading, (void *)chap));", " if (!t)\n return;", " dot_width = _htmlSizes[SIZE_P] * _htmlWidths[t->typeface][t->style]['.'] * 0.001f;", " /*\n * Put the text...\n */", " flat = flatten_tree(t->child->child);", " for (height = 0.0, temp = flat; temp != NULL; temp = temp->next)\n if (temp->height > height)\n height = temp->height;", " height *= _htmlSpacings[SIZE_P] / _htmlSizes[SIZE_P];", " if (t->indent)\n x = left + 18.0f + 18.0f * t->indent;\n else\n x = left;", " *y -= height;", " /*\n * Get the width of the page number, leave room for three dots...\n */", " if (heading >= 0 && heading < (int)num_headings)\n {\n hpage = heading_pages[heading];\n numberwidth = (float)(get_width((uchar *)pages[hpage].page_text, t->typeface, t->style, t->size) + 3.0f * dot_width);\n }\n else\n {\n hpage = 0;\n numberwidth = 0.0f;\n }", " for (temp = flat; temp != NULL; temp = next)\n {\n rgb[0] = temp->red / 255.0f;\n rgb[1] = temp->green / 255.0f;\n rgb[2] = temp->blue / 255.0f;", " if ((x + temp->width) >= (right - numberwidth))\n {\n /*\n * Too wide to fit, continue on the next line\n */", " *y -= _htmlSpacings[SIZE_P];\n x = left + 36.0f * t->indent;\n }", " if (*y < bottom)\n {\n (*page) ++;\n if (Verbosity)\n\tprogress_show(\"Formatting page %d\", *page);", " width = get_width((uchar *)TocTitle, _htmlHeadingFont, STYLE_BOLD, SIZE_H1);\n *y = (float)(top - _htmlSpacings[SIZE_H1]);\n x = (float)(left + 0.5f * (right - left - width));\n r = new_render(*page, RENDER_TEXT, x, *y, 0, 0, TocTitle);\n r->data.text.typeface = _htmlHeadingFont;\n r->data.text.style = STYLE_BOLD;\n r->data.text.size = (float)_htmlSizes[SIZE_H1];\n get_color(_htmlTextColor, r->data.text.rgb);", " *y -= _htmlSpacings[SIZE_H1];", " if (t->indent)\n\tx = left + 18.0f + 18.0f * t->indent;\n else\n\tx = left;", " if (chap != t)\n {\n *y += height;\n render_contents(chap, left, right, bottom, top, y, page, -1, 0);\n\t*y -= _htmlSpacings[SIZE_P];\n }\n }", " if (temp->link != NULL)\n {\n link = htmlGetVariable(temp->link, (uchar *)\"HREF\");", " /*\n * Add a page link...\n */", " new_render(*page, RENDER_LINK, x, *y, temp->width, temp->height, link);", " if (PSLevel == 0 && Links)\n {\n memcpy(rgb, link_color, sizeof(rgb));", "\ttemp->red = (uchar)(link_color[0] * 255.0);\n\ttemp->green = (uchar)(link_color[1] * 255.0);\n\ttemp->blue = (uchar)(link_color[2] * 255.0);", " if (LinkStyle)\n\t new_render(*page, RENDER_BOX, x, *y - 1, temp->width, 0,\n\t link_color);\n }\n }", " if ((link = htmlGetVariable(temp, (uchar *)\"ID\")) != NULL)\n {\n /*\n * Add a target link...\n */", " add_link(link, *page, (int)(*y + height));\n }", " switch (temp->markup)\n {\n case MARKUP_A :\n if ((link = htmlGetVariable(temp, (uchar *)\"NAME\")) != NULL)\n {\n /*\n * Add a target link...\n */", " add_link(link, *page, (int)(*y + height));\n }\n break;", " case MARKUP_NONE :\n if (temp->data == NULL)\n break;", "\t if (temp->underline)\n\t new_render(*page, RENDER_BOX, x, *y - 1, temp->width, 0, rgb);", "\t if (temp->strikethrough)\n\t new_render(*page, RENDER_BOX, x, *y + temp->height * 0.25f,\n\t\t temp->width, 0, rgb);", " r = new_render(*page, RENDER_TEXT, x, *y, 0, 0, temp->data);\n r->data.text.typeface = temp->typeface;\n r->data.text.style = temp->style;\n r->data.text.size = (float)_htmlSizes[temp->size];\n memcpy(r->data.text.rgb, rgb, sizeof(rgb));", " if (temp->superscript)\n r->y += height - temp->height;\n else if (temp->subscript)\n r->y -= height * _htmlSizes[0] / _htmlSpacings[0] -\n\t\t temp->height;\n\t break;", " case MARKUP_IMG :\n\t update_image_size(temp);\n\t new_render(*page, RENDER_IMAGE, x, *y, temp->width, temp->height,\n\t\t image_find((char *)htmlGetVariable(temp, (uchar *)\"REALSRC\")));\n\t break;", " default :\n\t break;\n }", " x += temp->width;\n next = temp->next;\n free(temp);\n }", " if (numberwidth > 0.0f)\n {\n /*\n * Draw dots leading up to the page number...\n */", " width = (float)(numberwidth - 3.0 * dot_width + x);", " for (nptr = number;\n nptr < (number + sizeof(number) - 1) && width < right;\n\t width += dot_width)\n *nptr++ = '.';", " if (nptr > number)\n nptr --;", " strlcpy((char *)nptr, pages[hpage].page_text, sizeof(number) - (size_t)(nptr - number));", " r = new_render(*page, RENDER_TEXT, right - width + x, *y, 0, 0, number);\n r->data.text.typeface = t->typeface;\n r->data.text.style = t->style;\n r->data.text.size = (float)_htmlSizes[t->size];\n memcpy(r->data.text.rgb, rgb, sizeof(rgb));\n }\n}", "\n/*\n * 'count_headings()' - Count the number of headings in the TOC.\n */", "static int\ncount_headings(tree_t *t)\t\t// I - Tree to count\n{\n int\tcount;\t\t\t\t// Number of headings...", "\n count = 0;", " while (t != NULL)\n {\n switch (t->markup)\n {\n case MARKUP_B :\n case MARKUP_LI :\n count ++;\n\t if (t->last_child && t->last_child->markup == MARKUP_UL)\n\t count += count_headings(t->last_child);\n\t break;", " default :\n count += count_headings(t->child);\n break;\n }", " t = t->next;\n }", " return (count);\n}", "\n/*\n * 'parse_contents()' - Parse the table of contents and produce a\n * rendering list...\n */", "static void\nparse_contents(tree_t *t,\t\t/* I - Tree to parse */\n float left,\t\t/* I - Left margin */\n float right,\t\t/* I - Printable width */\n float bottom,\t\t/* I - Bottom margin */\n float top,\t\t/* I - Printable top */\n float *y,\t\t/* IO - Y position */\n int *page,\t\t/* IO - Page # */\n int *heading,\t\t/* IO - Heading # */\n\t tree_t *chap)\t\t/* I - Chapter heading */\n{\n DEBUG_printf((\"parse_contents(t=%p, left=%.1f, right=%.1f, bottom=%.1f, top=%.1f, y=%.1f, page=%d, heading=%d, chap=%p)\\n\",\n (void *)t, left, right, bottom, top, *y, *page, *heading, (void *)chap));", " while (t != NULL)\n {\n switch (t->markup)\n {\n case MARKUP_B :\t/* Top-level TOC */\n if (t->prev != NULL)\t/* Advance one line prior to top-levels... */\n *y -= _htmlSpacings[SIZE_P];", " if (*y < (bottom + _htmlSpacings[SIZE_P] * 3))\n\t *y = 0; // Force page break", " chap = t;", " case MARKUP_LI :\t/* Lower-level TOC */\n DEBUG_printf((\"parse_contents: heading=%d, page = %d\\n\", *heading,\n heading_pages[*heading]));", " /*\n * Put the text unless the author has flagged it otherwise...\n */", " if (htmlGetVariable(t, (uchar *)\"_HD_OMIT_TOC\") == NULL)\n\t {\n render_contents(t, left, right, bottom, top, y, page,\n\t *heading, chap);", " /*\n\t * Update current headings for header/footer strings in TOC.\n\t */", "\t check_pages(*page);", "\t if (t->markup == MARKUP_B &&\n\t\tpages[*page].chapter == pages[*page - 1].chapter)\n\t pages[*page].chapter = htmlGetText(t->child->child);", "\t if (pages[*page].heading == pages[*page - 1].heading)\n\t pages[*page].heading = htmlGetText(t->child->child);", " /*\n * Next heading...\n */", " (*heading) ++;", " if (t->last_child->markup == MARKUP_UL)\n parse_contents(t->last_child, left, right, bottom, top, y,\n\t page, heading, chap);\n }\n\t else if (t->next != NULL && t->next->markup == MARKUP_UL)\n\t {\n\t /*\n\t * Skip children of omitted heading...\n\t */", "\t t = t->next;", "\t (*heading) += count_headings(t->child) + 1;\n\t }\n\t else\n\t (*heading) ++;\n break;", " default :\n parse_contents(t->child, left, right, bottom, top, y, page, heading,\n\t chap);\n break;\n }", " t = t->next;\n }\n}", "\n/*\n * 'parse_doc()' - Parse a document tree and produce rendering list output.\n */", "static void\nparse_doc(tree_t *t,\t\t/* I - Tree to parse */\n float *left,\t\t/* I - Left margin */\n float *right,\t/* I - Printable width */\n float *bottom,\t/* I - Bottom margin */\n float *top,\t\t/* I - Printable top */\n float *x,\t\t/* IO - X position */\n float *y,\t\t/* IO - Y position */\n int *page,\t\t/* IO - Page # */\n\t tree_t *cpara,\t/* I - Current paragraph */\n\t int *needspace)\t/* I - Need whitespace before this element */\n{\n int\t\ti;\t\t/* Looping var */\n tree_t\t*para,\t\t/* Phoney paragraph tree entry */\n\t\t*temp;\t\t/* Paragraph entry */\n var_t\t\t*var;\t\t/* Variable entry */\n uchar\t\t*name;\t\t/* ID name */\n uchar\t\t*style;\t\t/* STYLE attribute */\n float\t\twidth,\t\t/* Width of horizontal rule */\n\t\theight,\t\t/* Height of rule */\n\t\trgb[3];\t\t/* RGB color of rule */", "\n DEBUG_printf((\"parse_doc(t=%p, left=%.1f, right=%.1f, bottom=%.1f, top=%.1f, x=%.1f, y=%.1f, page=%d, cpara=%p, needspace=%d\\n\",\n (void *)t, *left, *right, *bottom, *top, *x, *y, *page, (void *)cpara,\n\t *needspace));\n DEBUG_printf((\" title_page = %d, chapter = %d\\n\", title_page, chapter));", " if (cpara == NULL)\n para = htmlNewTree(NULL, MARKUP_P, NULL);\n else\n para = cpara;", " while (t != NULL)\n {\n if (t->markup == MARKUP_FILE)\n current_url = htmlGetVariable(t, (uchar *)\"_HD_URL\");", " if (((t->markup == MARKUP_H1 && OutputType == OUTPUT_BOOK) ||\n (t->markup == MARKUP_FILE && OutputType == OUTPUT_WEBPAGES)) &&\n\t!title_page)\n {\n // New page on H1 in book mode or file in webpage mode...\n if (para->child != NULL && chapter > 0)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;\n }", " if ((chapter > 0 && OutputType == OUTPUT_BOOK) ||\n ((*page > 0 || *y < *top) && OutputType == OUTPUT_WEBPAGES))\n {\n if (*y < *top)\n (*page) ++;", " if (PageDuplex && (*page & 1))\n (*page) ++;", " if (Verbosity)\n progress_show(\"Formatting page %d\", *page);", " chapter_ends[chapter] = *page - 1;\n }", " // Make sure header and footer strings are correct...\n check_pages(*page);", " memcpy(pages[*page].header, Header, sizeof(pages[*page].header));\n memcpy(pages[*page].header1, Header1, sizeof(pages[*page].header1));\n memcpy(pages[*page].footer, Footer, sizeof(pages[*page].footer));", " // Bump the chapter/file count...\n chapter ++;\n if (chapter >= MAX_CHAPTERS)\n {\n\tprogress_error(HD_ERROR_TOO_MANY_CHAPTERS,\n\t \"Too many chapters/files in document (%d > %d)!\",\n\t chapter, MAX_CHAPTERS);\n chapter = MAX_CHAPTERS - 1;\n }\n else\n chapter_starts[chapter] = *page;", " if (chapter > TocDocCount)\n\tTocDocCount = chapter;", " *y = *top;\n *x = *left;\n *needspace = 0;\n }", " if ((name = htmlGetVariable(t, (uchar *)\"ID\")) != NULL)\n {\n /*\n * Add a link target using the ID=name variable...\n */", " add_link(name, *page, (int)*y);\n }\n else if (t->markup == MARKUP_FILE)\n {\n /*\n * Add a file link...\n */", " uchar\tnewname[256],\t/* New filename */\n\t\t*sep;\t\t/* \"?\" separator in links */", "\n // Strip any trailing HTTP GET data stuff...\n strlcpy((char *)newname, (char *)htmlGetVariable(t, (uchar *)\"_HD_FILENAME\"),\n sizeof(newname));", " if ((sep = (uchar *)strchr((char *)newname, '?')) != NULL)\n *sep = '\\0';", " // Add the link\n add_link(newname, *page, (int)*y);\n }", " if (chapter == 0 && !title_page)\n {\n // Need to handle page comments before the first heading...\n if (t->markup == MARKUP_COMMENT)\n parse_comment(t, left, right, bottom, top, x, y, page, para,\n\t *needspace);", " if (t->child != NULL)\n parse_doc(t->child, left, right, bottom, top, x, y, page, para,\n\t needspace);", " t = t->next;\n continue;\n }", " // Check for some basic stylesheet stuff...\n if ((style = htmlGetStyle(t, (uchar *)\"page-break-before:\")) != NULL &&\n\tstrcasecmp((char *)style, \"avoid\") != 0)\n {\n // Advance to the next page...\n (*page) ++;\n *x = *left;\n *y = *top;\n *needspace = 0;", " // See if we need to go to the next left/righthand page...\n if (PageDuplex && ((*page) & 1) &&\n strcasecmp((char *)style, \"right\") == 0)\n\t(*page) ++;\n else if (PageDuplex && !((*page) & 1) &&\n strcasecmp((char *)style, \"left\") == 0)\n\t(*page) ++;", " // Update the progress as necessary...\n if (Verbosity)\n\tprogress_show(\"Formatting page %d\", *page);\n }", " // Process the markup...\n switch (t->markup)\n {\n case MARKUP_IMG :\n update_image_size(t);\n case MARKUP_NONE :\n case MARKUP_BR :\n if (para->child == NULL)\n {\n\t if (t->parent == NULL)\n\t {\n para->halignment = ALIGN_LEFT;\n para->indent = 0;\n\t }\n\t else\n\t {\n para->halignment = t->parent->halignment;\n para->indent = t->parent->indent;\n\t }\n }", "\t // Skip heading whitespace...\n if (para->child == NULL && t->markup == MARKUP_NONE &&\n\t t->data != NULL && strcmp((char *)t->data, \" \") == 0)\n\t break;", " if ((temp = htmlAddTree(para, t->markup, t->data)) != NULL)\n {\n\t temp->link = t->link;\n temp->width = t->width;\n temp->height = t->height;\n temp->typeface = t->typeface;\n temp->style = t->style;\n temp->size = t->size;\n temp->underline = t->underline;\n temp->strikethrough = t->strikethrough;\n temp->superscript = t->superscript;\n temp->subscript = t->subscript;\n temp->halignment = t->halignment;\n temp->valignment = t->valignment;\n temp->red = t->red;\n temp->green = t->green;\n temp->blue = t->blue;\n for (i = 0, var = t->vars; i < t->nvars; i ++, var ++)\n htmlSetVariable(temp, var->name, var->value);\n }\n break;", " case MARKUP_TABLE :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;\n }", " parse_table(t, *left, *right, *bottom, *top, x, y, page, *needspace);\n\t *needspace = 0;\n break;", " case MARKUP_H1 :\n case MARKUP_H2 :\n case MARKUP_H3 :\n case MARKUP_H4 :\n case MARKUP_H5 :\n case MARKUP_H6 :\n case MARKUP_H7 :\n case MARKUP_H8 :\n case MARKUP_H9 :\n case MARKUP_H10 :\n case MARKUP_H11 :\n case MARKUP_H12 :\n case MARKUP_H13 :\n case MARKUP_H14 :\n case MARKUP_H15 :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;", "\t *needspace = 1;\n }", " parse_heading(t, *left, *right, *bottom, *top, x, y, page, *needspace);\n\t *needspace = 1;\n break;", " case MARKUP_BLOCKQUOTE :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;", "\t *needspace = 1;\n }", " *left += 36;\n\t *right -= 36;", " parse_doc(t->child, left, right, bottom, top, x, y, page, NULL,\n\t needspace);", " *left -= 36;\n\t *right += 36;", " *x = *left;\n *needspace = 1;\n break;", " case MARKUP_CENTER :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;", " *needspace = 1;\n }", " parse_doc(t->child, left, right, bottom, top, x, y, page, NULL,\n\t needspace);", " *x = *left;\n *needspace = 1;\n break;", " case MARKUP_P :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;", "\t *needspace = 1;\n }", " parse_doc(t->child, left, right, bottom, top, x, y, page, NULL,\n\t needspace);", " *x = *left;\n *needspace = 1;\n break;", " case MARKUP_DIV :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;\n }", " parse_doc(t->child, left, right, bottom, top, x, y, page, NULL,\n\t needspace);", " if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;\n }\n break;", " case MARKUP_PRE :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;", "\t *needspace = 1;\n }", " *left += 36.0f;\n *x = *left;", " parse_pre(t, *left, *right, *bottom, *top, x, y, page, *needspace);", " *left -= 36.0f;\n *x = *left;\n *needspace = 1;\n break;", " case MARKUP_DIR :\n case MARKUP_MENU :\n case MARKUP_UL :\n case MARKUP_OL :\n init_list(t);\n case MARKUP_DL :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;\n }", " if (t->indent == 1)\n\t *needspace = 1;", "\t *left += 36.0f;\n *x = *left;", " parse_doc(t->child, left, right, bottom, top, x, y, page, para,\n\t needspace);", " *left -= 36.0f;", " if (t->indent == 1)\n\t *needspace = 1;\n break;", " case MARKUP_LI :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;", "\t *needspace = 0;\n }", " parse_list(t, left, right, bottom, top, x, y, page, *needspace);", " *x = *left;\n *needspace = t->next && t->next->markup != MARKUP_LI &&\n\t t->next->markup != MARKUP_UL &&\n\t\t t->next->markup != MARKUP_OL;\n break;", " case MARKUP_DT :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;", "\t *needspace = 0;\n }", "\t *left -= 36.0f;\n *x = *left;", " parse_doc(t->child, left, right, bottom, top, x, y, page,\n\t NULL, needspace);", "\t *left += 36.0f;\n *x = *left;\n *needspace = 0;\n break;", " case MARKUP_DD :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;", "\t *needspace = 0;\n }", " parse_doc(t->child, left, right, bottom, top, x, y, page, NULL,\n\t needspace);", " *x = *left;\n *needspace = 0;\n break;", " case MARKUP_HR :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;\n }", " if (htmlGetVariable(t, (uchar *)\"BREAK\") == NULL)\n\t {\n\t /*\n\t * Generate a horizontal rule...\n\t */", " if ((name = htmlGetVariable(t, (uchar *)\"WIDTH\")) == NULL)\n\t width = *right - *left;\n\t else\n\t {\n\t if (strchr((char *)name, '%') != NULL)\n\t width = atoi((char *)name) * (*right - *left) / 100;\n\t else\n width = (float)(atoi((char *)name) * PagePrintWidth / _htmlBrowserWidth);\n }", " if ((name = htmlGetVariable(t, (uchar *)\"SIZE\")) == NULL)\n\t height = 2;\n\t else\n\t height = (float)(atoi((char *)name) * PagePrintWidth / _htmlBrowserWidth);", " switch (t->halignment)\n\t {\n\t case ALIGN_LEFT :\n\t *x = *left;\n\t\t break;\n\t case ALIGN_CENTER :\n\t *x = *left + (*right - *left - width) * 0.5f;\n\t\t break;\n\t case ALIGN_RIGHT :\n\t *x = *right - width;\n\t\t break;\n\t }", " if (*y < (*bottom + height + _htmlSpacings[SIZE_P]))\n\t {\n\t /*\n\t * Won't fit on this page...\n\t */", " (*page) ++;\n\t if (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n *y = *top;\n }", " (*y) -= height + _htmlSpacings[SIZE_P];\n rgb[0] = t->red / 255.0f;\n rgb[1] = t->green / 255.0f;\n rgb[2] = t->blue / 255.0f;", " new_render(*page, RENDER_BOX, *x, *y + _htmlSpacings[SIZE_P] * 0.5,\n\t width, height, rgb);\n\t }\n\t else\n\t {\n\t /*\n\t * <HR BREAK> generates a page break...\n\t */", " (*page) ++;\n\t if (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n *y = *top;\n\t }", " *x = *left;\n *needspace = 0;\n break;", " case MARKUP_COMMENT :\n // Check comments for commands...\n parse_comment(t, left, right, bottom, top, x, y, page, para,\n\t *needspace);\n break;", " case MARKUP_HEAD : // Ignore document HEAD section\n case MARKUP_TITLE : // Ignore title and meta stuff\n case MARKUP_META :\n case MARKUP_SCRIPT : // Ignore script stuff\n case MARKUP_INPUT : // Ignore form stuff\n case MARKUP_SELECT :\n case MARKUP_OPTION :\n case MARKUP_TEXTAREA :\n break;", " case MARKUP_STYLE :\n break;", " case MARKUP_A :\n if (htmlGetVariable(t, (uchar *)\"NAME\") != NULL)\n\t {\n\t /*\n\t * Add this named destination to the paragraph tree...\n\t */", " if (para->child == NULL)\n {\n para->halignment = t->halignment;\n para->indent = t->indent;\n }", " if ((temp = htmlAddTree(para, t->markup, t->data)) != NULL)\n {\n\t temp->link = t->link;\n temp->width = t->width;\n temp->height = t->height;\n temp->typeface = t->typeface;\n temp->style = t->style;\n temp->size = t->size;\n temp->underline = t->underline;\n temp->strikethrough = t->strikethrough;\n temp->superscript = t->superscript;\n temp->subscript = t->subscript;\n temp->halignment = t->halignment;\n temp->valignment = t->valignment;\n temp->red = t->red;\n temp->green = t->green;\n temp->blue = t->blue;\n for (i = 0, var = t->vars; i < t->nvars; i ++, var ++)\n \thtmlSetVariable(temp, var->name, var->value);\n }\n\t }", " default :\n\t if (t->child != NULL)\n parse_doc(t->child, left, right, bottom, top, x, y, page, para,\n\t needspace);\n break;\n }", "\n // Check for some basic stylesheet stuff...\n if ((style = htmlGetStyle(t, (uchar *)\"page-break-after:\")) != NULL &&\n\tstrcasecmp((char *)style, \"avoid\") != 0)\n {\n // Advance to the next page...\n (*page) ++;\n *x = *left;\n *y = *top;\n *needspace = 0;", " // See if we need to go to the next left/righthand page...\n if (PageDuplex && ((*page) & 1) &&\n strcasecmp((char *)style, \"right\") == 0)\n\t(*page) ++;\n else if (PageDuplex && !((*page) & 1) &&\n strcasecmp((char *)style, \"left\") == 0)\n\t(*page) ++;", " // Update the progress as necessary...\n if (Verbosity)\n\tprogress_show(\"Formatting page %d\", *page);\n }", " // Move to the next node...\n t = t->next;\n }", " if (para->child != NULL && cpara != para)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;\n *needspace = 0;\n }", " if (cpara != para)\n htmlDeleteTree(para);", " DEBUG_printf((\"LEAVING parse_doc(), x = %.1f, y = %.1f, page = %d\\n\",\n *x, *y, *page));\n}", "\n/*\n * 'parse_heading()' - Parse a heading tree and produce rendering list output.\n */", "static void\nparse_heading(tree_t *t,\t/* I - Tree to parse */\n float left,\t/* I - Left margin */\n float right,\t/* I - Printable width */\n float bottom,\t/* I - Bottom margin */\n float top,\t/* I - Printable top */\n float *x,\t/* IO - X position */\n float *y,\t/* IO - Y position */\n int *page,\t/* IO - Page # */\n int needspace)\t/* I - Need whitespace? */\n{\n int\t*temp;\t\t\t// Temporary integer array pointer", "\n DEBUG_printf((\"parse_heading(t=%p, left=%.1f, right=%.1f, bottom=%.1f, top=%.1f, x=%.1f, y=%.1f, page=%d, needspace=%d\\n\",\n (void *)t, left, right, bottom, top, *x, *y, *page, needspace));", " if (((t->markup - MARKUP_H1) < TocLevels || TocLevels == 0) && !title_page)\n current_heading = t->child;", " if (*y < (5 * _htmlSpacings[SIZE_P] + bottom))\n {\n (*page) ++;\n *y = top;\n if (Verbosity)\n progress_show(\"Formatting page %d\", *page);\n }", " check_pages(*page);", " if (t->markup == MARKUP_H1 && !title_page)\n pages[*page].chapter = htmlGetText(current_heading);", " if ((pages[*page].heading == NULL || t->markup == MARKUP_H1 ||\n (*page > 0 && pages[*page].heading == pages[*page - 1].heading)) &&\n !title_page)\n {\n pages[*page].heading = htmlGetText(current_heading);\n pages[*page].headnode = current_heading;\n }", " if ((t->markup - MARKUP_H1) < TocLevels && !title_page)\n {\n DEBUG_printf((\"H%d: heading_pages[%d] = %d\\n\", t->markup - MARKUP_H1 + 1,\n (int)num_headings, *page - 1));", " // See if we need to resize the headings arrays...\n if (num_headings >= alloc_headings)\n {\n alloc_headings += ALLOC_HEADINGS;", " if (num_headings == 0)\n temp = (int *)malloc(sizeof(int) * alloc_headings);\n else\n temp = (int *)realloc(heading_pages, sizeof(int) * alloc_headings);", " if (temp == NULL)\n {\n progress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory for %d headings - %s\",\n\t (int)alloc_headings, strerror(errno));\n\talloc_headings -= ALLOC_HEADINGS;\n\treturn;\n }", " memset(temp + alloc_headings - ALLOC_HEADINGS, 0,\n sizeof(int) * ALLOC_HEADINGS);", " heading_pages = temp;", " if (num_headings == 0)\n temp = (int *)malloc(sizeof(int) * alloc_headings);\n else\n temp = (int *)realloc(heading_tops, sizeof(int) * alloc_headings);", " if (temp == NULL)\n {\n progress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory for %d headings - %s\",\n\t (int)alloc_headings, strerror(errno));\n\talloc_headings -= ALLOC_HEADINGS;\n\treturn;\n }", " memset(temp + alloc_headings - ALLOC_HEADINGS, 0,\n sizeof(int) * ALLOC_HEADINGS);", " heading_tops = temp;\n }", " heading_pages[num_headings] = *page;\n heading_tops[num_headings] = (int)(*y + 4 * _htmlSpacings[SIZE_P]);\n num_headings ++;\n }", " parse_paragraph(t, left, right, bottom, top, x, y, page, needspace);", " if (t->halignment == ALIGN_RIGHT && t->markup == MARKUP_H1 &&\n OutputType == OUTPUT_BOOK && !title_page)\n {\n /*\n * Special case - chapter heading for users manual...\n */", " *y = bottom + 0.5f * (top - bottom);\n }\n}", "#if defined(PARA_DEBUG) && !defined(DEBUG)\n# undef DEBUG_printf\n# undef DEBUG_puts\n# define DEBUG_printf(x) printf x\n# define DEBUG_puts(x) puts(x)\n#endif /* PARA_DEBUG && !defined(DEBUG) */", "\n/*\n * 'parse_paragraph()' - Parse a paragraph tree and produce rendering list\n * output.\n */", "static void\nparse_paragraph(tree_t *t,\t/* I - Tree to parse */\n \tfloat left,\t/* I - Left margin */\n \tfloat right,\t/* I - Printable width */\n \tfloat bottom,\t/* I - Bottom margin */\n \tfloat top,\t/* I - Printable top */\n \tfloat *x,\t/* IO - X position */\n \tfloat *y,\t/* IO - Y position */\n \tint *page,\t/* IO - Page # */\n \tint needspace)/* I - Need whitespace? */\n{\n int\t\twhitespace;\t/* Non-zero if a fragment ends in whitespace */\n tree_t\t*flat,\n\t\t*start,\n\t\t*end,\n\t\t*prev,\n\t\t*temp;\n float\t\twidth,\n\t\theight,\n\t\toffset,\n\t\tspacing,\n\t\tborderspace,\n\t\ttemp_y,\n\t\ttemp_width,\n\t\ttemp_height;\n float\t\tformat_width, image_y, image_left, image_right;\n int\t\timage_page = *page;\n float\t\tchar_spacing;\n int\t\tnum_chars;\n render_t\t*r;\n uchar\t\t*align,\n\t\t*hspace,\n\t\t*vspace,\n\t\t*link,\n\t\t*border;\n float\t\trgb[3];\n uchar\t\tline[10240],\n\t\t*lineptr,\n\t\t*dataptr;\n tree_t\t*linetype;\n float\t\tlinex,\n\t\tlinewidth;\n int\t\tfirstline;", "\n DEBUG_printf((\"parse_paragraph(t=%p, left=%.1f, right=%.1f, bottom=%.1f, top=%.1f, x=%.1f, y=%.1f, page=%d, needspace=%d\\n\",\n (void *)t, left, right, bottom, top, *x, *y, *page, needspace));", " flat = flatten_tree(t->child);\n image_left = left;\n image_right = right;\n image_y = 0;", " if (flat == NULL)\n DEBUG_puts(\"parse_paragraph: flat == NULL!\");", " // Add leading whitespace...\n if (*y < top && needspace)\n *y -= _htmlSpacings[SIZE_P];", " /*\n * First scan for images with left/right alignment tags...\n */", " for (temp = flat, prev = NULL; temp != NULL;)\n {\n if (temp->markup == MARKUP_IMG)\n update_image_size(temp);", " if (temp->markup == MARKUP_IMG &&\n (align = htmlGetVariable(temp, (uchar *)\"ALIGN\")))\n {\n if ((border = htmlGetVariable(temp, (uchar *)\"BORDER\")) != NULL)\n\tborderspace = (float)atof((char *)border);\n else if (temp->link)\n\tborderspace = 1;\n else\n\tborderspace = 0;", " borderspace *= PagePrintWidth / _htmlBrowserWidth;", " if (strcasecmp((char *)align, \"LEFT\") == 0)\n {\n if ((vspace = htmlGetVariable(temp, (uchar *)\"VSPACE\")) != NULL)\n\t *y -= atoi((char *)vspace);", " if (*y < (bottom + temp->height + 2 * borderspace))\n {\n\t (*page) ++;\n\t *y = top;", "\t if (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n }", " if (borderspace > 0.0f)\n\t{\n\t if (temp->link && PSLevel == 0)\n\t memcpy(rgb, link_color, sizeof(rgb));\n\t else\n\t {\n\t rgb[0] = temp->red / 255.0f;\n\t rgb[1] = temp->green / 255.0f;\n\t rgb[2] = temp->blue / 255.0f;\n\t }", "\t // Top\n new_render(*page, RENDER_BOX, image_left, *y - borderspace,\n\t\t temp->width + 2 * borderspace, borderspace, rgb);\n\t // Left\n new_render(*page, RENDER_BOX, image_left,\n\t *y - temp->height - 2 * borderspace,\n borderspace, temp->height + 2 * borderspace, rgb);\n\t // Right\n new_render(*page, RENDER_BOX, image_left + temp->width + borderspace,\n\t *y - temp->height - 2 * borderspace,\n borderspace, temp->height + 2 * borderspace, rgb);\n\t // Bottom\n new_render(*page, RENDER_BOX, image_left,\n\t *y - temp->height - 2 * borderspace,\n temp->width + 2 * borderspace, borderspace, rgb);\n\t}", " *y -= borderspace;", " new_render(*page, RENDER_IMAGE, image_left + borderspace,\n\t *y - temp->height, temp->width, temp->height,\n\t\t image_find((char *)htmlGetVariable(temp, (uchar *)\"REALSRC\")));", " if (temp->link &&\n\t (link = htmlGetVariable(temp->link, (uchar *)\"_HD_FULL_HREF\")) != NULL)\n {\n\t /*\n\t * Add a page link...\n\t */", "\t new_render(*page, RENDER_LINK, image_left + borderspace, *y - temp->height, temp->width, temp->height, link);\n }", " *y -= borderspace;", " if (vspace != NULL)\n\t *y -= atoi((char *)vspace);", " image_left += temp->width + 2 * borderspace;\n\ttemp_y = *y - temp->height;\n\timage_page = *page;", "\tif (temp_y < image_y || image_y == 0)\n\t image_y = temp_y;", " if ((hspace = htmlGetVariable(temp, (uchar *)\"HSPACE\")) != NULL)\n\t image_left += atoi((char *)hspace);", " if (prev != NULL)\n prev->next = temp->next;\n else\n flat = temp->next;", " free(temp);\n temp = prev;\n }\n else if (strcasecmp((char *)align, \"RIGHT\") == 0)\n {\n if ((vspace = htmlGetVariable(temp, (uchar *)\"VSPACE\")) != NULL)\n\t *y -= atoi((char *)vspace);", " if (*y < (bottom + temp->height + 2 * borderspace))\n {\n\t (*page) ++;\n\t *y = top;", "\t if (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n }", " image_right -= temp->width + 2 * borderspace;\n\timage_page = *page;", " if (borderspace > 0.0f)\n\t{\n\t if (temp->link && PSLevel == 0)\n\t memcpy(rgb, link_color, sizeof(rgb));\n\t else\n\t {\n\t rgb[0] = temp->red / 255.0f;\n\t rgb[1] = temp->green / 255.0f;\n\t rgb[2] = temp->blue / 255.0f;\n\t }", "\t // Top\n new_render(*page, RENDER_BOX, image_right, *y - borderspace,\n\t\t temp->width + 2 * borderspace, borderspace, rgb);\n\t // Left\n new_render(*page, RENDER_BOX, image_right,\n\t *y - temp->height - 2 * borderspace,\n borderspace, temp->height + 2 * borderspace, rgb);\n\t // Right\n new_render(*page, RENDER_BOX, image_right + temp->width + borderspace,\n\t *y - temp->height - 2 * borderspace,\n borderspace, temp->height + 2 * borderspace, rgb);\n\t // Bottom\n new_render(*page, RENDER_BOX, image_right, *y - temp->height - 2 * borderspace,\n temp->width + 2 * borderspace, borderspace, rgb);\n\t}", " *y -= borderspace;", " new_render(*page, RENDER_IMAGE, image_right + borderspace,\n\t *y - temp->height, temp->width, temp->height,\n\t\t image_find((char *)htmlGetVariable(temp, (uchar *)\"REALSRC\")));", " if (temp->link &&\n\t (link = htmlGetVariable(temp->link, (uchar *)\"_HD_FULL_HREF\")) != NULL)\n {\n\t /*\n\t * Add a page link...\n\t */", "\t new_render(*page, RENDER_LINK, image_right + borderspace, *y - temp->height, temp->width, temp->height, link);\n }", " *y -= borderspace;", " if (vspace != NULL)\n\t *y -= atoi((char *)vspace);", "\ttemp_y = *y - temp->height;", "\tif (temp_y < image_y || image_y == 0)\n\t image_y = temp_y;", " if ((hspace = htmlGetVariable(temp, (uchar *)\"HSPACE\")) != NULL)\n\t image_right -= atoi((char *)hspace);", " if (prev != NULL)\n prev->next = temp->next;\n else\n flat = temp->next;", " free(temp);\n temp = prev;\n }\n }", " if (temp != NULL)\n {\n prev = temp;\n temp = temp->next;\n }\n else\n temp = flat;\n }", " /*\n * Then format the text and inline images...\n */", " format_width = image_right - image_left;\n firstline = 1;", " DEBUG_printf((\"format_width = %.1f\\n\", format_width));", " // Make stupid compiler warnings go away (if you can't put\n // enough smarts in the compiler, don't add the warning!)\n offset = 0.0f;\n temp_width = 0.0f;\n temp_height = 0.0f;\n lineptr = NULL;\n linex = 0.0f;\n linewidth = 0.0f;", " while (flat != NULL)\n {\n start = flat;\n end = flat;\n width = 0.0;", " while (flat != NULL)\n {\n // Get fragments...\n temp_width = 0.0;\n temp = flat;\n whitespace = 0;", " while (temp != NULL && !whitespace)\n {\n if (temp->markup == MARKUP_NONE && temp->data[0] == ' ')\n\t{\n if (temp == start)\n temp_width -= _htmlWidths[temp->typeface][temp->style][' '] *\n _htmlSizes[temp->size] * 0.001f;\n else if (temp_width > 0.0f)\n\t whitespace = 1;\n\t}\n else\n whitespace = 0;", " if (whitespace)\n\t break;", " if (temp->markup == MARKUP_IMG)\n\t{\n\t if ((border = htmlGetVariable(temp, (uchar *)\"BORDER\")) != NULL)\n\t borderspace = (float)atof((char *)border);\n\t else if (temp->link)\n\t borderspace = 1;\n\t else\n\t borderspace = 0;", " borderspace *= PagePrintWidth / _htmlBrowserWidth;", " temp_width += 2 * borderspace;\n\t}", " prev = temp;\n temp = temp->next;\n temp_width += prev->width;", " if ((temp_width >= format_width && prev->markup == MARKUP_IMG) ||\n\t prev->markup == MARKUP_BR)\n\t{\n\t break;\n\t}\n\telse if (prev->markup == MARKUP_NONE)\n\t{\n\t int\tch = prev->data[strlen((char *)prev->data) - 1];", "\t if (_htmlUTF8)\n\t ch = _htmlUnicode[ch];", " if (ch == 173)\n break;\n\t}\n }", " if ((width + temp_width) <= format_width)\n {\n width += temp_width;\n end = temp;\n flat = temp;", " if (prev->markup == MARKUP_BR)\n break;\n }\n else if (width == 0.0)\n {\n width += temp_width;\n end = temp;\n flat = temp;\n break;\n }\n else\n break;\n }", " if (start == end)\n {\n end = start->next;\n flat = start->next;\n width = start->width;\n }", " for (height = 0.0, num_chars = 0, temp = prev = start;\n temp != end;\n\t temp = temp->next)\n {\n prev = temp;", " if (temp->markup == MARKUP_NONE)\n num_chars += strlen((char *)temp->data);", " if (temp->height > height)\n height = temp->height;\n }", " for (spacing = 0.0, temp = prev = start;\n temp != end;\n\t temp = temp->next)\n {\n prev = temp;", " if (temp->markup != MARKUP_IMG)\n temp_height = (float)(temp->height * _htmlSpacings[0] / _htmlSizes[0]);\n else\n {\n\tif ((border = htmlGetVariable(temp, (uchar *)\"BORDER\")) != NULL)\n\t borderspace = (float)atof((char *)border);\n\telse if (temp->link)\n\t borderspace = 1;\n\telse\n\t borderspace = 0;", " borderspace *= PagePrintWidth / _htmlBrowserWidth;", " temp_height = temp->height + 2 * borderspace;\n }", " if (temp_height > spacing)\n spacing = temp_height;\n }", " if (firstline && end != NULL && *y < (bottom + height + _htmlSpacings[t->size]))\n {\n // Go to next page since only 1 line will fit on this one...\n (*page) ++;\n *y = top;", " if (Verbosity)\n progress_show(\"Formatting page %d\", *page);\n }", " firstline = 0;", " if (height == 0.0f)\n height = spacing;", " for (temp = start; temp != end; temp = temp->next)\n if (temp->markup != MARKUP_A)\n break;", " if (temp != NULL && temp->markup == MARKUP_NONE && temp->data[0] == ' ')\n {\n // Drop leading space...\n for (dataptr = temp->data; *dataptr; dataptr ++)\n *dataptr = dataptr[1];\n *dataptr = '\\0';", " temp_width = _htmlWidths[temp->typeface][temp->style][' '] * _htmlSizes[temp->size] * 0.001f;\n temp->width -= temp_width;\n num_chars --;\n }", " if (end != NULL)\n temp = end->prev;\n else\n temp = NULL;", " DEBUG_printf((\" BEFORE page=%d, y=%.1f, height=%.1f, spacing=%.1f, bottom=%.1f\\n\", *page, *y, height, spacing, bottom));", " if (*y < (spacing + bottom))\n {\n (*page) ++;\n *y = top;", " if (Verbosity)\n progress_show(\"Formatting page %d\", *page);\n }", " *y -= height;", " DEBUG_printf((\" page=%d, y=%.1f, width=%.1f, height=%.1f\\n\", *page, *y, width, height));", " if (Verbosity)\n progress_update(100 - (int)(100 * (*y) / PagePrintLength));", " char_spacing = 0.0f;\n whitespace = 0;\n temp = start;\n linetype = NULL;", " rgb[0] = temp->red / 255.0f;\n rgb[1] = temp->green / 255.0f;\n rgb[2] = temp->blue / 255.0f;", " switch (t->halignment)\n {\n case ALIGN_LEFT :\n linex = image_left;\n\t break;", " case ALIGN_CENTER :\n linex = image_left + 0.5f * (format_width - width);\n\t break;", " case ALIGN_RIGHT :\n linex = image_right - width;\n\t break;", " case ALIGN_JUSTIFY :\n linex = image_left;\n\t if (flat != NULL && flat->prev->markup != MARKUP_BR && num_chars > 1)\n\t char_spacing = (format_width - width) / (num_chars - 1);\n\t break;\n }", " while (temp != end)\n {\n if (temp->link != NULL && PSLevel == 0 && Links &&\n temp->markup == MARKUP_NONE)\n {\n\ttemp->red = (uchar)(link_color[0] * 255.0);\n\ttemp->green = (uchar)(link_color[1] * 255.0);\n\ttemp->blue = (uchar)(link_color[2] * 255.0);\n }", " /*\n * See if we are doing a run of characters in a line and need to\n * output this run...\n */", " if (linetype != NULL &&\n\t (temp->markup != MARKUP_NONE ||\n\t temp->typeface != linetype->typeface ||\n\t temp->style != linetype->style ||\n\t temp->size != linetype->size ||\n\t temp->superscript != linetype->superscript ||\n\t temp->subscript != linetype->subscript ||\n\t temp->red != linetype->red ||\n\t temp->green != linetype->green ||\n\t temp->blue != linetype->blue))\n {\n r = new_render(*page, RENDER_TEXT, linex - linewidth, *y,\n\t linewidth, linetype->height, line);\n\tr->data.text.typeface = linetype->typeface;\n\tr->data.text.style = linetype->style;\n\tr->data.text.size = (float)_htmlSizes[linetype->size];\n\tr->data.text.spacing = char_spacing;\n memcpy(r->data.text.rgb, rgb, sizeof(rgb));", "\tif (linetype->superscript)\n r->y += height - linetype->height;\n else if (linetype->subscript)\n r->y -= height - linetype->height;", " free(linetype);\n linetype = NULL;\n }", " if ((link = htmlGetVariable(temp, (uchar *)\"ID\")) != NULL)\n {\n /*\n\t* Add a target link...\n\t*/", "\tadd_link(link, *page, (int)(*y + height));\n }", " switch (temp->markup)\n {\n case MARKUP_A :\n if ((link = htmlGetVariable(temp, (uchar *)\"NAME\")) != NULL)\n {\n /*\n * Add a target link...\n */", " add_link(link, *page, (int)(*y + height));\n }", "\tdefault :\n\t temp_width = temp->width;\n break;", " case MARKUP_NONE :\n if (temp->data == NULL)\n break;", "\t if (((temp->width - right + left) > 0.001 ||\n\t (temp->height - top + bottom) > 0.001) && OverflowErrors)\n\t progress_error(HD_ERROR_CONTENT_TOO_LARGE,\n\t \"Text on page %d too large - \"\n\t\t\t \"truncation or overlapping may occur!\", *page + 1);", " if (linetype == NULL)\n {\n\t linetype = temp;\n\t lineptr = line;\n\t linewidth = 0.0;", "\t rgb[0] = temp->red / 255.0f;\n\t rgb[1] = temp->green / 255.0f;\n\t rgb[2] = temp->blue / 255.0f;\n\t }", " strlcpy((char *)lineptr, (char *)temp->data, sizeof(line) - (size_t)(lineptr - line));", " temp_width = temp->width + char_spacing * strlen((char *)lineptr);", "\t if (temp->underline || (temp->link && LinkStyle && PSLevel == 0))\n\t new_render(*page, RENDER_BOX, linex, *y - 1, temp_width, 0, rgb);", "\t if (temp->strikethrough)\n\t new_render(*page, RENDER_BOX, linex, *y + temp->height * 0.25f,\n\t temp_width, 0, rgb);", " linewidth += temp_width;\n lineptr += strlen((char *)lineptr);", " if (lineptr > line && lineptr[-1] == ' ')\n whitespace = 1;\n else\n whitespace = 0;\n\t break;", "\tcase MARKUP_IMG :\n\t if (((temp->width - right + left) > 0.001 ||\n\t (temp->height - top + bottom) > 0.001) && OverflowErrors)\n\t {\n\t DEBUG_printf((\"IMAGE: %.3fx%.3f > %.3fx%.3f\\n\",\n\t temp->width, temp->height,\n\t\t\t right - left, top - bottom));", "\t progress_error(HD_ERROR_CONTENT_TOO_LARGE,\n\t \"Image on page %d too large - \"\n\t\t\t \"truncation or overlapping may occur!\", *page + 1);\n }", "\t if ((border = htmlGetVariable(temp, (uchar *)\"BORDER\")) != NULL)\n\t borderspace = (float)atof((char *)border);\n\t else if (temp->link)\n\t borderspace = 1;\n\t else\n\t borderspace = 0;", " borderspace *= PagePrintWidth / _htmlBrowserWidth;", " temp_width += 2 * borderspace;", "\t switch (temp->valignment)\n\t {\n\t case ALIGN_TOP :\n\t\t offset = height - temp->height - 2 * borderspace;\n\t\t break;\n\t case ALIGN_MIDDLE :\n\t\t offset = 0.5f * (height - temp->height) - borderspace;\n\t\t break;\n\t case ALIGN_BOTTOM :\n\t\t offset = 0.0f;\n\t }", " if (borderspace > 0.0f)\n\t {\n\t // Top\n new_render(*page, RENDER_BOX, linex,\n\t *y + offset + temp->height + borderspace,\n\t\t\t temp->width + 2 * borderspace, borderspace, rgb);\n\t // Left\n new_render(*page, RENDER_BOX, linex, *y + offset,\n \t borderspace, temp->height + 2 * borderspace, rgb);\n\t // Right\n new_render(*page, RENDER_BOX, linex + temp->width + borderspace,\n\t *y + offset, borderspace,\n\t\t\t temp->height + 2 * borderspace, rgb);\n\t // Bottom\n new_render(*page, RENDER_BOX, linex, *y + offset,\n \t temp->width + 2 * borderspace, borderspace, rgb);\n\t }", "\t new_render(*page, RENDER_IMAGE, linex + borderspace,\n\t *y + offset + borderspace, temp->width, temp->height,\n\t\t image_find((char *)htmlGetVariable(temp, (uchar *)\"REALSRC\")));\n whitespace = 0;\n\t temp_width = temp->width + 2 * borderspace;\n\t break;\n }", " if (temp->link != NULL &&\n (link = htmlGetVariable(temp->link, (uchar *)\"_HD_FULL_HREF\")) != NULL)\n {\n /*\n\t* Add a page link...\n\t*/", "\tnew_render(*page, RENDER_LINK, linex, *y + offset, temp->width, temp->height, link);\n }", " linex += temp_width;\n prev = temp;\n temp = temp->next;\n if (prev != linetype)\n free(prev);\n }", " /*\n * See if we have a run of characters that hasn't been output...\n */", " if (linetype != NULL)\n {\n r = new_render(*page, RENDER_TEXT, linex - linewidth, *y,\n linewidth, linetype->height, line);\n r->data.text.typeface = linetype->typeface;\n r->data.text.style = linetype->style;\n r->data.text.spacing = char_spacing;\n r->data.text.size = (float)_htmlSizes[linetype->size];\n memcpy(r->data.text.rgb, rgb, sizeof(rgb));", " if (linetype->superscript)\n r->y += height - linetype->height;\n else if (linetype->subscript)\n r->y -= height - linetype->height;", " free(linetype);\n }", " /*\n * Update the margins after we pass below the images...\n */", " *y -= spacing - height;", " DEBUG_printf((\" AFTER y=%.1f, bottom=%.1f\\n\", *y, bottom));", " if (*y < bottom)\n {\n (*page) ++;\n *y = top;", " if (Verbosity)\n progress_show(\"Formatting page %d\", *page);\n }", " if (*y < image_y || *page > image_page)\n {\n image_y = 0.0f;\n image_left = left;\n image_right = right;\n format_width = image_right - image_left;\n }\n }", " *x = left;\n if (*y > image_y && image_y > 0.0f && image_page == *page)\n *y = image_y;", " DEBUG_printf((\"LEAVING parse_paragraph(), x = %.1f, y = %.1f, page = %d, image_y = %.1f\\n\", *x, *y, *page, image_y));\n}", "\n#if defined(PARA_DEBUG) && !defined(DEBUG)\n# undef DEBUG_printf\n# undef DEBUG_puts\n# define DEBUG_printf(x)\n# define DEBUG_puts(x)\n#endif /* PARA_DEBUG && !DEBUG */", "\n/*\n * 'parse_pre()' - Parse preformatted text and produce rendering list output.\n */", "static void\nparse_pre(tree_t *t,\t\t/* I - Tree to parse */\n float left,\t\t/* I - Left margin */\n float right,\t\t/* I - Printable width */\n float bottom,\t/* I - Bottom margin */\n float top,\t\t/* I - Printable top */\n float *x,\t\t/* IO - X position */\n float *y,\t\t/* IO - Y position */\n int *page,\t\t/* IO - Page # */\n int needspace)\t/* I - Need whitespace? */\n{\n tree_t\t*flat, *start, *next;\n uchar\t\t*link,\n\t\tline[10240],\n\t\t*lineptr,\n\t\t*dataptr;\n int\t\tcol;\n float\t\twidth,\n\t\theight,\n\t\trgb[3];\n render_t\t*r;", "\n REF(right);", " DEBUG_printf((\"parse_pre(t=%p, left=%.1f, right=%.1f, x=%.1f, y=%.1f, page=%d\\n\",\n (void *)t, left, right, *x, *y, *page));", " if (t->child == NULL)\n return;", " if (*y < top && needspace)\n *y -= _htmlSpacings[SIZE_P];", " flat = flatten_tree(t->child);", " if (flat == NULL)\n return;", " if (flat->markup == MARKUP_NONE && flat->data != NULL)\n {\n // Skip leading blank line, if present...\n for (dataptr = flat->data; isspace(*dataptr); dataptr ++);", " if (!*dataptr)\n {\n next = flat->next;\n free(flat);\n flat = next;\n }\n }", " while (flat != NULL)\n {\n for (height = 0.0f, start = flat; flat != NULL; flat = flat->next)\n {\n if (flat->height > height)\n height = flat->height;", " if (flat->markup == MARKUP_BR ||\n (flat->markup == MARKUP_NONE && flat->data &&\n\t flat->data[strlen((char *)flat->data) - 1] == '\\n'))\n break;\n }", " if (flat)\n flat = flat->next;", " if (*y < (height + bottom))\n {\n (*page) ++;\n *y = top;", " if (Verbosity)\n\tprogress_show(\"Formatting page %d\", *page);\n }", " *x = left;\n *y -= height;", " if (Verbosity)\n progress_update(100 - (int)(100 * (*y) / PagePrintLength));", " col = 0;\n while (start != flat)\n {\n rgb[0] = start->red / 255.0f;\n rgb[1] = start->green / 255.0f;\n rgb[2] = start->blue / 255.0f;", " if (start->link &&\n\t (link = htmlGetVariable(start->link, (uchar *)\"_HD_FULL_HREF\")) != NULL)\n {\n /*\n\t* Add a page link...\n\t*/", "\tnew_render(*page, RENDER_LINK, *x, *y, start->width, start->height, link);", "\tif (PSLevel == 0 && Links)\n\t{\n memcpy(rgb, link_color, sizeof(rgb));", "\t start->red = (uchar)(link_color[0] * 255.0);\n\t start->green = (uchar)(link_color[1] * 255.0);\n\t start->blue = (uchar)(link_color[2] * 255.0);", " if (LinkStyle)\n\t new_render(*page, RENDER_BOX, *x, *y - 1, start->width, 0,\n\t link_color);\n\t}\n }", " if ((link = htmlGetVariable(start, (uchar *)\"ID\")) != NULL)\n {\n /*\n\t* Add a target link...\n\t*/", "\tadd_link(link, *page, (int)(*y + height));\n }", " switch (start->markup)\n {\n case MARKUP_COMMENT :\n\t parse_comment(start, &left, &right, &bottom, &top, x, y, page, NULL, 0);\n break;", "\tcase MARKUP_A :\n if ((link = htmlGetVariable(start, (uchar *)\"NAME\")) != NULL)\n {\n /*\n * Add a target link...\n */", " add_link(link, *page, (int)(*y + height));\n }\n break;", "\tcase MARKUP_NONE :\n for (lineptr = line, dataptr = start->data;\n\t\t *dataptr != '\\0' && lineptr < (line + sizeof(line) - 1);\n\t\t dataptr ++)\n if (*dataptr == '\\n')\n\t\tbreak;\n else if (*dataptr == '\\t')\n {\n /* This code changed after 15 years to work around new compiler optimization bugs (Issue #349) */\n int num_cols = 8 - (col & 7);", " memcpy(lineptr, \" \", num_cols);\n lineptr += num_cols;\n col += num_cols;\n }\n else if (*dataptr != '\\r')\n {\n \t*lineptr++ = *dataptr;\n \tcol ++;\n }", " *lineptr = '\\0';", " width = get_width(line, start->typeface, start->style, start->size);\n r = new_render(*page, RENDER_TEXT, *x, *y, width, 0, line);\n r->data.text.typeface = start->typeface;\n r->data.text.style = start->style;\n r->data.text.size = (float)_htmlSizes[start->size];\n memcpy(r->data.text.rgb, rgb, sizeof(rgb));", "\t if (start->underline)\n\t new_render(*page, RENDER_BOX, *x, *y - 1, start->width, 0, rgb);", "\t if (start->strikethrough)\n\t new_render(*page, RENDER_BOX, *x, *y + start->height * 0.25f,\n\t \t start->width, 0, rgb);", " *x += start->width;\n break;", "\tcase MARKUP_IMG :\n\t new_render(*page, RENDER_IMAGE, *x, *y, start->width, start->height,\n\t\t image_find((char *)htmlGetVariable(start, (uchar *)\"REALSRC\")));", " *x += start->width;\n col ++;\n\t break;", "\tdefault :\n break;\n }", " next = start->next;\n free(start);\n start = next;", " }", " if ((*x - right) > 0.001 && OverflowErrors)\n progress_error(HD_ERROR_CONTENT_TOO_LARGE,\n\t \"Preformatted text on page %d too long - \"\n\t\t \"truncation or overlapping may occur!\", *page + 1);", " *y -= _htmlSpacings[t->size] - _htmlSizes[t->size];\n }", " *x = left;\n}", "\n//#define TABLE_DEBUG 1\n#ifdef TABLE_DEBUG\n# undef DEBUG_puts\n# define DEBUG_puts(x) puts(x)\n# define DEBUG 1\n# undef DEBUG_printf\n# define DEBUG_printf(x) printf x\n#endif /* TABLE_DEBUG */", "\ntypedef struct\n{\n int debug;\n int num_cols,\n num_rows;\n float border,\n\t\tborder_left,\n border_rgb[3],\n\t\tborder_size,\n cellpadding,\n height;\n int\t\tcol_spans[MAX_COLUMNS],\n\t\trow_spans[MAX_COLUMNS];\n char\t\tcol_fixed[MAX_COLUMNS],\n\t\tcol_percent[MAX_COLUMNS];\n float\t\tcol_lefts[MAX_COLUMNS],\n\t\tcol_rights[MAX_COLUMNS],\n\t\tcol_widths[MAX_COLUMNS],\n\t\tcol_swidths[MAX_COLUMNS],\n\t\tcol_mins[MAX_COLUMNS],\n\t\tcol_smins[MAX_COLUMNS],\n\t\tcol_prefs[MAX_COLUMNS];\n int\t\tcell_page[MAX_COLUMNS],\t// Start page for cell\n\t\tcell_endpage[MAX_COLUMNS];\n\t\t\t\t\t// End page for cell\n float\t\tcell_y[MAX_COLUMNS],\t// Row for each cell\n\t\tcell_endy[MAX_COLUMNS],\t// Row for each cell\n\t\tcell_height[MAX_COLUMNS],\n\t\t\t\t\t// Height of each cell in a row\n\t\tspan_heights[MAX_COLUMNS];\n\t\t\t\t\t// Height of spans\n render_t\t*cell_bg[MAX_COLUMNS];\t// Background rectangles\n render_t\t*cell_start[MAX_COLUMNS];\n\t\t\t\t\t// Start of the content for a cell in the row\n render_t\t*cell_end[MAX_COLUMNS];\t// End of the content for a cell in a row\n} hdtable_t;", "\n/*\n * 'render_table_row()' - Render a table row.\n */", "static void\nrender_table_row(hdtable_t &table,\n tree_t ***cells,\n int row,\n uchar *height_var,\n float left,\t\t// I - Left margin\n float right,\t\t// I - Printable width\n float bottom,\t\t// I - Bottom margin\n float top,\t\t\t// I - Printable top\n float *x,\n float *y,\n int *page)\n{\n int\t\tcol,\n\t\ttcol,\n\t\tcolspan,\n\t\trowspan,\n\t\ttempspace;\n float\t\twidth,\n\t\ttemp_y;\n int\t\ttemp_page;\n uchar\t\t*var;\n int\t\tdo_valign;\t\t// True if we should do vertical alignment of cells\n int row_page;\n float\t\trow_y,\n row_starty,\n row_height,\t\t// Total height of the row\n\t\ttemp_height;\t\t// Temporary holder\n uchar\t\t*bgcolor;\n float\t\tbgrgb[3];", "\n do_valign = 1;\n row_height = 0.0f;\n row_page = *page;\n row_y = *y - table.cellpadding;\n row_starty = row_y;", " DEBUG_printf((\"BEFORE row_y = %.1f, *y = %.1f, row_page = %d\\n\",\n row_y, *y, row_page));", " for (col = 0, rowspan = 9999; col < table.num_cols; col += colspan)\n {\n if (table.row_spans[col] == 0)\n {\n if ((var = htmlGetVariable(cells[row][col], (uchar *)\"ROWSPAN\")) != NULL)\n table.row_spans[col] = atoi((char *)var);", " if (table.row_spans[col] <= 1)\n table.row_spans[col] = 0;", " if (table.row_spans[col] > (table.num_rows - row))\n table.row_spans[col] = table.num_rows - row;", " table.span_heights[col] = 0.0f;\n }", " if (table.row_spans[col] < rowspan)\n rowspan = table.row_spans[col];", " for (colspan = 1; (col + colspan) < table.num_cols; colspan ++)\n if (cells[row][col] != cells[row][col + colspan])\n break;\n }", " if (!rowspan)\n rowspan = 1;", " for (col = 0; col < table.num_cols;)\n {\n for (colspan = 1; (col + colspan) < table.num_cols; colspan ++)\n if (cells[row][col] != cells[row][col + colspan])\n break;\n colspan --;", " DEBUG_printf((\" col = %d, colspan = %d, left = %.1f, right = %.1f, cell = %p\\n\", col, colspan, table.col_lefts[col], table.col_rights[col + colspan], (void *)cells[row][col]));", " *x = table.col_lefts[col];\n temp_y = *y - table.cellpadding;\n temp_page = *page;\n tempspace = 0;", " if (row == 0 || cells[row][col] != cells[row - 1][col])\n {\n check_pages(*page);", " if (cells[row][col] == NULL)\n bgcolor = NULL;\n else if ((bgcolor = htmlGetVariable(cells[row][col], (uchar *)\"BGCOLOR\")) != NULL)\n {\n memcpy(bgrgb, background_color, sizeof(bgrgb));", " get_color(bgcolor, bgrgb, 0);", " width = table.col_rights[col + colspan] - table.col_lefts[col] + 2 * table.cellpadding;\n table.border_left = table.col_lefts[col] - table.cellpadding;", " table.cell_bg[col] = new_render(*page, RENDER_BOX, table.border_left, row_y, width + table.border, 0.0, bgrgb);\n }\n else\n {\n table.cell_bg[col] = NULL;", " new_render(*page, RENDER_TEXT, -1.0f, -1.0f, 0.0, 0.0, (void *)\"\");\n }", " DEBUG_printf((\"cell_bg[%d] = %p, pages[%d].end = %p\\n\", col, (void *)table.cell_bg[col], *page, (void *)pages[*page].end));", " table.cell_start[col] = pages[*page].end;\n table.cell_page[col] = temp_page;\n table.cell_y[col] = temp_y;", " if (table.debug)\n {\n check_pages(*page);", " render_t *r;\n char table_text[255];", " snprintf(table_text, sizeof(table_text), \"cell=%p [%d,%d]\",\n (void *)cells[row][col], row, col);\n r = new_render(temp_page, RENDER_TEXT, *x, temp_y,\n get_width((uchar *)table_text, TYPE_COURIER, STYLE_NORMAL, 1),\n _htmlSizes[1], table_text);", " r->data.text.typeface = TYPE_COURIER;\n r->data.text.style = STYLE_NORMAL;\n r->data.text.size = (float)_htmlSizes[1];\n }", " if (cells[row][col] != NULL && cells[row][col]->child != NULL)\n {\n DEBUG_printf((\" parsing cell %d,%d; width = %.1f\\n\", row, col, table.col_rights[col + colspan] - table.col_lefts[col]));", " bottom += table.cellpadding;\n top -= table.cellpadding;", " parse_doc(cells[row][col]->child, table.col_lefts + col, table.col_rights + col + colspan, &bottom, &top, x, &temp_y, &temp_page, NULL, &tempspace);", " bottom -= table.cellpadding;\n top += table.cellpadding;\n }", " table.cell_endpage[col] = temp_page;\n table.cell_endy[col] = temp_y;\n table.cell_height[col] = *y - table.cellpadding - temp_y;\n table.cell_end[col] = pages[*page].end;", " if (table.cell_start[col] == NULL)\n table.cell_start[col] = pages[*page].start;", " DEBUG_printf((\"row = %d, col = %d, y = %.1f, cell_y = %.1f, cell_height = %.1f\\n\", row, col, *y - table.cellpadding, temp_y, table.cell_height[col]));\n DEBUG_printf((\"cell_start[%d] = %p, cell_end[%d] = %p\\n\", col, (void *)table.cell_start[col], col, (void *)table.cell_end[col]));\n }", " if (table.row_spans[col] == 0 &&\n table.cell_page[col] == table.cell_endpage[col] &&\n table.cell_height[col] > row_height)\n row_height = table.cell_height[col];", " if (table.row_spans[col] <= rowspan)\n {\n if (table.cell_page[col] != table.cell_endpage[col])\n do_valign = 0;", " if (table.cell_endpage[col] > row_page)\n {\n row_page = table.cell_endpage[col];\n row_y = table.cell_endy[col];\n }\n else if (table.cell_endy[col] < row_y && table.cell_endpage[col] == row_page)\n row_y = table.cell_endy[col];\n }", " DEBUG_printf((\"**** col = %d, row = %d, row_y = %.1f, row_page = %d\\n\", col, row, row_y, row_page));", " for (col ++; colspan > 0; colspan --, col ++)\n {\n table.cell_start[col] = NULL;\n table.cell_page[col] = table.cell_page[col - 1];\n table.cell_y[col] = table.cell_y[col - 1];\n table.cell_end[col] = NULL;\n table.cell_endpage[col] = table.cell_endpage[col - 1];\n table.cell_endy[col] = table.cell_endy[col - 1];\n table.cell_height[col] = table.cell_height[col - 1];\n }\n }", " DEBUG_printf((\"row = %d, row_y = %.1f, row_height = %.1f\\n\", row, row_y, row_height));", " for (col = 0; col < table.num_cols; col += colspan)\n {\n for (colspan = 1; (col + colspan) < table.num_cols; colspan ++)\n if (cells[row][col] != cells[row][col + colspan])\n break;", " if (table.row_spans[col])\n table.span_heights[col] += row_height;", " DEBUG_printf((\"col = %d, cell_y = %.1f, cell_page = %d, cell_endpage = %d, row_spans = %d, span_heights = %.1f, cell_height = %.1f\\n\", col, table.cell_y[col], table.cell_page[col], table.cell_endpage[col], table.row_spans[col], table.span_heights[col], table.cell_height[col]));\n }", " for (col = 0; col < table.num_cols; col += colspan)\n {\n for (colspan = 1; (col + colspan) < table.num_cols; colspan ++)\n if (cells[row][col] != cells[row][col + colspan])\n break;", " if (table.row_spans[col] == rowspan &&\n table.cell_page[col] == table.cell_endpage[col] &&\n table.cell_height[col] > table.span_heights[col])\n {\n temp_height = table.cell_height[col] - table.span_heights[col];\n row_height += temp_height;\n DEBUG_printf((\"Adjusting row-span height by %.1f, new row_height = %.1f\\n\", temp_height, row_height));", " for (tcol = 0; tcol < table.num_cols; tcol ++)\n if (table.row_spans[tcol])\n {\n table.span_heights[tcol] += temp_height;\n DEBUG_printf((\"col = %d, span_heights = %.1f\\n\", tcol, table.span_heights[tcol]));\n }\n }\n }", " DEBUG_printf((\"AFTER row = %d, row_page = %d, row_y = %.1f, row_height = %.1f, *y = %.1f, do_valign = %d\\n\", row, row_page, row_y, row_height, *y, do_valign));", " /*\n * Do the vertical alignment\n */", " if (do_valign)\n {\n height_var = NULL;", " if (cells[row][0] != NULL)\n {\n if ((height_var = htmlGetVariable(cells[row][0]->parent, (uchar *)\"HEIGHT\")) == NULL)\n\tfor (col = 0; col < table.num_cols; col ++)\n\t if (htmlGetVariable(cells[row][col], (uchar *)\"ROWSPAN\") == NULL)\n\t if ((height_var = htmlGetVariable(cells[row][col], (uchar *)\"HEIGHT\")) != NULL)\n\t break;\n }", " if (height_var != NULL)\n {\n // Hardcode the row height...\n if (height_var[strlen((char *)height_var) - 1] == '%')\n temp_height = (float)(atof((char *)height_var) * 0.01f * PagePrintLength);\n else\n temp_height = (float)(atof((char *)height_var) * PagePrintWidth / _htmlBrowserWidth);", " if (table.height > 0 && temp_height > table.height)\n temp_height = table.height;", " temp_height -= 2 * table.cellpadding;", " if (temp_height > row_height)\n {\n // Only enforce the height if it is > the actual row height.\n row_height = temp_height;\n row_y = *y - temp_height;\n }\n }", " for (col = 0; col < table.num_cols; col += colspan + 1)\n {\n render_t\t*p;\n float\tdelta_y;", "\n for (colspan = 1; (col + colspan) < table.num_cols; colspan ++)\n if (cells[row][col] != cells[row][col + colspan])\n break;", " colspan --;", " if (table.cell_start[col] == NULL || table.row_spans[col] > rowspan ||\n cells[row][col] == NULL || cells[row][col]->child == NULL)\n continue;", " if (table.row_spans[col] == 1)\n {\n int tcol;\n float span_height = 0.0f;", " for (tcol = 0; tcol < table.num_cols; tcol ++)\n {\n if (table.row_spans[col] == 1 && table.span_heights[col] > span_height)\n span_height = table.span_heights[col];\n }", " switch (cells[row][col]->valignment)\n {\n case ALIGN_MIDDLE :\n// delta_y = (table.span_heights[col] - table.cell_height[col]) * 0.5f;\n delta_y = (span_height - table.cell_height[col]) * 0.5f;\n break;", " case ALIGN_BOTTOM :\n// delta_y = table.span_heights[col] - table.cell_height[col];\n delta_y = span_height - table.cell_height[col];\n break;", " default :\n delta_y = 0.0f;\n break;\n }\n }\n else if (table.row_spans[col])\n {\n delta_y = 0.0f;\n }\n else\n {\n switch (cells[row][col]->valignment)\n {\n case ALIGN_MIDDLE :\n delta_y = (row_height - table.cell_height[col]) * 0.5f;\n break;", " case ALIGN_BOTTOM :\n delta_y = row_height - table.cell_height[col];\n break;", " default :\n delta_y = 0.0f;\n break;\n }\n }", " DEBUG_printf((\"row = %d, col = %d, valign = %d, rowspans = %d, cell_height = %.1f, span_heights = %.1f, delta_y = %.1f\\n\", row, col, cells[row][col]->valignment, table.row_spans[col], table.cell_height[col], table.span_heights[col], delta_y));", " if (delta_y > 0.0f)\n {\n if (table.cell_start[col] == table.cell_end[col])\n p = table.cell_start[col];\n else\n p = table.cell_start[col]->next;", " for (; p != NULL; p = p->next)\n {\n DEBUG_printf((\"aligning %p (%s), y was %.1f, now %.1f\\n\",\n (void *)p, p->data.text.buffer, p->y, p->y - delta_y));", " p->y -= delta_y;\n if (p == table.cell_end[col])\n break;\n }\n }\n#ifdef DEBUG\n else\n {\n if (table.cell_start[col] == table.cell_end[col])\n p = table.cell_start[col];\n else\n p = table.cell_start[col]->next;", " for (; p != NULL; p = p->next)\n {\n printf(\"NOT aligning %p (%s)\\n\", (void *)p, p->data.text.buffer);", " if (p == table.cell_end[col])\n break;\n }\n }\n#endif /* DEBUG */\n }\n }", " // Update all current columns with ROWSPAN <= rowspan to use the same\n // end page and row...\n for (col = 0, temp_page = -1, temp_y = 99999999; col < table.num_cols; col ++)\n if (table.row_spans[col] <= rowspan &&\n cells[row][col] != NULL && cells[row][col]->child != NULL)\n {\n if (table.cell_endpage[col] > temp_page)\n {\n temp_page = table.cell_endpage[col];\n temp_y = table.cell_endy[col];\n }\n else if (table.cell_endpage[col] == temp_page && table.cell_endy[col] < temp_y)\n temp_y = table.cell_endy[col];\n }", " for (col = 0; col < table.num_cols; col ++)\n if (table.row_spans[col] <= rowspan &&\n cells[row][col] != NULL && cells[row][col]->child != NULL)\n {\n table.cell_endpage[col] = temp_page;\n table.cell_endy[col] = temp_y;\n }", " row_y -= table.cellpadding;", " table.border_left = table.col_lefts[0] - table.cellpadding;\n width = table.col_rights[table.num_cols - 1] - table.col_lefts[0] + 2 * table.cellpadding;", " for (bgcolor = NULL, col = 0; col < table.num_cols; col ++)\n if (table.row_spans[col] <= rowspan &&\n cells[row][col] &&\n !htmlGetVariable(cells[row][col], (uchar *)\"ROWSPAN\") &&\n (bgcolor = htmlGetVariable(cells[row][col]->parent,\n (uchar *)\"BGCOLOR\")) != NULL)\n break;", " if (bgcolor)\n {\n memcpy(bgrgb, background_color, sizeof(bgrgb));", " get_color(bgcolor, bgrgb, 0);", " if (row_page > *page)\n {\n // Draw background on multiple pages...", " // Bottom of first page...\n new_render(*page, RENDER_BOX, table.border_left, bottom,\n width, row_starty - bottom + table.cellpadding, bgrgb,\n pages[*page].start);", " // Intervening pages...\n for (temp_page = *page + 1; temp_page < row_page; temp_page ++)\n {\n new_render(temp_page, RENDER_BOX, table.border_left, bottom,\n width, top - bottom, bgrgb, pages[temp_page].start);\n }", " // Top of last page...\n check_pages(*page);", " new_render(row_page, RENDER_BOX, table.border_left, row_y,\n width, top - row_y, bgrgb,\n pages[row_page].start);\n }\n else\n {\n // Draw background in row...\n new_render(row_page, RENDER_BOX, table.border_left, row_y,\n width, row_height + 2 * table.cellpadding, bgrgb,\n pages[row_page].start);\n }\n }", " for (col = 0; col < table.num_cols; col += colspan + 1)\n {\n for (colspan = 0; (col + colspan) < table.num_cols; colspan ++)\n if (cells[row][col] != cells[row][col + colspan])\n break;\n else if (table.row_spans[col + colspan] > 0)\n {\n DEBUG_printf((\"row = %d, col = %d, decrementing row_spans (%d) to %d...\\n\", row,\n col, table.row_spans[col + colspan],\n table.row_spans[col + colspan] - rowspan));\n table.row_spans[col + colspan] -= rowspan;\n }", " colspan --;", " width = table.col_rights[col + colspan] - table.col_lefts[col] +\n 2 * table.cellpadding;", " if (cells[row][col] == NULL || cells[row][col]->child == NULL ||\n table.row_spans[col] > 0)\n continue;", " DEBUG_printf((\"DRAWING BORDER+BACKGROUND: col=%d, row=%d, cell_page=%d, cell_y=%.1f\\n\"\n \" cell_endpage=%d, cell_endy=%.1f\\n\",\n col, row, table.cell_page[col], table.cell_y[col],\n table.cell_endpage[col], table.cell_endy[col]));", " if ((bgcolor = htmlGetVariable(cells[row][col],\n (uchar *)\"BGCOLOR\")) != NULL)\n {\n memcpy(bgrgb, background_color, sizeof(bgrgb));", " get_color(bgcolor, bgrgb, 0);\n }", " table.border_left = table.col_lefts[col] - table.cellpadding;", " if (table.cell_page[col] != table.cell_endpage[col])\n {\n /*\n * Crossing a page boundary...\n */", " if (table.border > 0)\n {\n /*\n * +---+---+---+\n * | | | |\n */", " // Top\n new_render(table.cell_page[col], RENDER_BOX, table.border_left,\n table.cell_y[col] + table.cellpadding,\n width + table.border, table.border, table.border_rgb);\n // Left\n new_render(table.cell_page[col], RENDER_BOX, table.border_left, bottom,\n table.border, table.cell_y[col] - bottom + table.cellpadding + table.border, table.border_rgb);\n // Right\n new_render(table.cell_page[col], RENDER_BOX,\n table.border_left + width, bottom,\n table.border, table.cell_y[col] - bottom + table.cellpadding + table.border, table.border_rgb);\n }", " if (bgcolor != NULL)\n {\n table.cell_bg[col]->y = bottom;\n table.cell_bg[col]->height = table.cell_y[col] - bottom + table.cellpadding + table.border;\n }", " for (temp_page = table.cell_page[col] + 1; temp_page < table.cell_endpage[col]; temp_page ++)\n {\n /*\n * | | | |\n * | | | |\n */", " if (table.border > 0.0f)\n {\n // Left\n new_render(temp_page, RENDER_BOX, table.border_left, bottom,\n table.border, top - bottom, table.border_rgb);\n // Right\n new_render(temp_page, RENDER_BOX,\n table.border_left + width, bottom,\n table.border, top - bottom, table.border_rgb);\n }", " if (bgcolor != NULL)\n new_render(temp_page, RENDER_BOX, table.border_left, bottom,\n width + table.border, top - bottom, bgrgb,\n pages[temp_page].start);\n }", " if (table.border > 0.0f)\n {\n /*\n * | | | |\n * +---+---+---+\n */", " // Left\n new_render(table.cell_endpage[col], RENDER_BOX, table.border_left, row_y,\n table.border, top - row_y, table.border_rgb);\n // Right\n new_render(table.cell_endpage[col], RENDER_BOX,\n table.border_left + width, row_y,\n table.border, top - row_y, table.border_rgb);\n // Bottom\n new_render(table.cell_endpage[col], RENDER_BOX, table.border_left, row_y,\n width + table.border, table.border, table.border_rgb);\n }", " if (bgcolor != NULL)\n {\n check_pages(table.cell_endpage[col]);", " new_render(table.cell_endpage[col], RENDER_BOX, table.border_left, row_y,\n width + table.border, top - row_y, bgrgb,\n pages[table.cell_endpage[col]].start);\n }\n }\n else\n {\n /*\n * +---+---+---+\n * | | | |\n * +---+---+---+\n */", " if (table.border > 0.0f)\n {\n // Top\n new_render(table.cell_page[col], RENDER_BOX, table.border_left,\n table.cell_y[col] + table.cellpadding,\n width + table.border, table.border, table.border_rgb);\n // Left\n new_render(table.cell_page[col], RENDER_BOX, table.border_left, row_y,\n table.border, table.cell_y[col] - row_y + table.cellpadding + table.border, table.border_rgb);\n // Right\n new_render(table.cell_page[col], RENDER_BOX,\n table.border_left + width, row_y,\n table.border, table.cell_y[col] - row_y + table.cellpadding + table.border, table.border_rgb);\n // Bottom\n new_render(table.cell_page[col], RENDER_BOX, table.border_left, row_y,\n width + table.border, table.border, table.border_rgb);\n }", " if (bgcolor != NULL)\n {\n table.cell_bg[col]->y = row_y;\n table.cell_bg[col]->height = table.cell_y[col] - row_y + table.cellpadding + table.border;\n }\n }\n }", " *page = row_page;\n *y = row_y;\n}", "\n/*\n * 'parse_table()' - Parse a table and produce rendering output.\n */", "static void\nparse_table(tree_t *t,\t\t\t// I - Tree to parse\n float left,\t\t// I - Left margin\n float right,\t\t// I - Printable width\n float bottom,\t\t// I - Bottom margin\n float top,\t\t\t// I - Printable top\n float *x,\t\t\t// IO - X position\n float *y,\t\t\t// IO - Y position\n int *page,\t\t// IO - Page #\n int needspace)\t\t// I - Need whitespace?\n{\n int\t\tcol,\n\t\trow,\n header_row = -1,\n\t\ttcol,\n\t\tcolspan,\n\t\trowspan,\n\t\talloc_rows,\n\t\tregular_cols;\n hdtable_t table;\n float\t\tcol_width,\n\t\tcol_min,\n\t\tcol_pref,\n\t\tcol_height,\n\t\tcellspacing,\n\t\twidth,\n\t\tpref_width,\n\t\tspan_width,\n\t\tregular_width,\n\t\tactual_width,\n\t\ttable_width,\n\t\tmin_width,\n\t\ttemp_width,\n header_height = 0.0,\n\t\ttable_y,\n temp_bottom,\n\t\ttemp_top;\n int\t\ttemp_page, table_page;\n uchar\t\t*var,\n\t\t*height_var,\t\t// Row HEIGHT variable\n *header_height_var = NULL;\n tree_t\t*temprow,\n\t\t*tempcol,\n\t\t*tempnext,\n\t\t***cells,\n\t\t*caption;\t\t// Caption for bottom, if any\n float\t\ttemp_height;\t\t// Temporary holder\n uchar\t\t*bgcolor;\n float\t\tbgrgb[3];\n const char\t*htmldoc_debug;\t\t// HTMLDOC_DEBUG env var", "\n DEBUG_puts(\"\\n\\nTABLE\");", " DEBUG_printf((\"parse_table(t=%p, left=%.1f, right=%.1f, x=%.1f, y=%.1f, page=%d\\n\",\n (void *)t, left, right, *x, *y, *page));", " if (t->child == NULL)\n return; /* Empty table... */", " memset(&table, 0, sizeof(table));", " /*\n * Check debug mode...\n */", " if ((htmldoc_debug = getenv(\"HTMLDOC_DEBUG\")) != NULL &&\n (strstr(htmldoc_debug, \"table\") || strstr(htmldoc_debug, \"all\")))\n table.debug = 1;\n else\n table.debug = 0;", " /*\n * Figure out the # of rows, columns, and the desired widths...\n */", " cells = NULL;", " if ((var = htmlGetVariable(t, (uchar *)\"WIDTH\")) != NULL)\n {\n if (var[strlen((char *)var) - 1] == '%')\n table_width = (float)(atof((char *)var) * (right - left) / 100.0f);\n else\n table_width = (float)(atoi((char *)var) * PagePrintWidth / _htmlBrowserWidth);", " if (table_width < 0.0f || table_width > PagePrintWidth)\n table_width = right - left;\n }\n else\n table_width = right - left;", " if ((var = htmlGetVariable(t, (uchar *)\"HEIGHT\")) != NULL)\n {\n if (var[strlen((char *)var) - 1] == '%')\n table.height = (float)(atof((char *)var) * (top - bottom) / 100.0f);\n else\n table.height = (float)(atoi((char *)var) * PagePrintWidth / _htmlBrowserWidth);\n }\n else\n table.height = -1.0f;", " DEBUG_printf((\"table_width = %.1f\\n\", table_width));", " if ((var = htmlGetVariable(t, (uchar *)\"CELLPADDING\")) != NULL)\n {\n if ((table.cellpadding = atoi((char *)var)) < 0.0f)\n table.cellpadding = 0.0f;\n else if (table.cellpadding > 20.0f)\n table.cellpadding = 20.0f;\n }\n else\n table.cellpadding = 1.0f;", " if ((var = htmlGetVariable(t, (uchar *)\"CELLSPACING\")) != NULL)\n {\n if ((cellspacing = atoi((char *)var)) < 0.0f)\n cellspacing = 0.0f;\n else if (cellspacing > 20.0f)\n cellspacing = 20.0f;\n }\n else\n cellspacing = 0.0f;", " if ((var = htmlGetVariable(t, (uchar *)\"BORDER\")) != NULL)\n {\n if ((table.border = (float)atof((char *)var)) <= 0.0 && var[0] != '0')\n table.border = 1.0f;\n else if (table.border > 20.0f)\n table.border = 20.0f;", " table.cellpadding += table.border;\n }\n else\n table.border = 0.0f;", " if (table.debug && table.border == 0.0f)\n table.border = 0.01f;", " table.border_rgb[0] = t->red / 255.0f;\n table.border_rgb[1] = t->green / 255.0f;\n table.border_rgb[2] = t->blue / 255.0f;", " if ((var = htmlGetVariable(t, (uchar *)\"BORDERCOLOR\")) != NULL)\n get_color(var, table.border_rgb, 0);", " if (table.border == 0.0f && table.cellpadding > 0.0f)\n {\n /*\n * Ah, the strange table formatting nightmare that is HTML.\n * Netscape and MSIE assign an invisible border width of 1\n * pixel if no border is specified...\n */", " table.cellpadding += 1.0f;\n }", " table.border_size = table.border - 1.0f;", " cellspacing *= PagePrintWidth / _htmlBrowserWidth;\n table.cellpadding *= PagePrintWidth / _htmlBrowserWidth;\n table.border *= PagePrintWidth / _htmlBrowserWidth;\n table.border_size *= PagePrintWidth / _htmlBrowserWidth;", " DEBUG_printf((\"border = %.1f, cellpadding = %.1f\\n\", table.border, table.cellpadding));", " temp_bottom = bottom - table.cellpadding;\n temp_top = top + table.cellpadding;", " for (temprow = t->child, table.num_cols = 0, table.num_rows = 0, alloc_rows = 0, caption = NULL;\n temprow != NULL;\n temprow = tempnext)\n {\n tempnext = temprow->next;", " if (temprow->markup == MARKUP_CAPTION)\n {\n if ((var = htmlGetVariable(temprow, (uchar *)\"ALIGN\")) == NULL ||\n strcasecmp((char *)var, \"bottom\"))\n {\n /*\n * Show caption at top...\n\t*/", " parse_paragraph(temprow, left, right, bottom, top, x, y, page, needspace);\n needspace = 1;\n }\n else\n {\n /*\n * Flag caption for bottom of table...\n\t*/", " caption = temprow;\n }\n }\n else if (temprow->markup == MARKUP_TR ||\n ((temprow->markup == MARKUP_TBODY || temprow->markup == MARKUP_THEAD ||\n temprow->markup == MARKUP_TFOOT) && temprow->child != NULL))\n {\n if (temprow->markup == MARKUP_THEAD)\n header_row = table.num_rows;", " // Descend into table body as needed...\n if (temprow->markup == MARKUP_TBODY || temprow->markup == MARKUP_THEAD ||\n temprow->markup == MARKUP_TFOOT)\n temprow = temprow->child;", " // Figure out the next row...\n if ((tempnext = temprow->next) == NULL)\n if (temprow->parent->markup == MARKUP_TBODY ||\n temprow->parent->markup == MARKUP_THEAD ||\n temprow->parent->markup == MARKUP_TFOOT)\n tempnext = temprow->parent->next;", " // Allocate memory for the table as needed...\n if (table.num_rows >= alloc_rows)\n {\n alloc_rows += ALLOC_ROWS;", " if (alloc_rows == ALLOC_ROWS)\n\t cells = (tree_t ***)malloc(sizeof(tree_t **) * (size_t)alloc_rows);\n\telse\n\t cells = (tree_t ***)realloc(cells, sizeof(tree_t **) * (size_t)alloc_rows);", " if (cells == (tree_t ***)0)\n\t{\n\t progress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory for table!\");\n\t return;\n\t}\n }", " if ((cells[table.num_rows] = (tree_t **)calloc(sizeof(tree_t *), MAX_COLUMNS)) == NULL)\n {\n\tprogress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory for table!\");\n free(cells);\n\treturn;\n }", "#ifdef DEBUG\n printf(\"BEFORE row %d: num_cols = %d\\n\", table.num_rows, table.num_cols);", " if (table.num_rows)\n for (col = 0; col < table.num_cols; col ++)\n\t printf(\" col %d: row_spans[] = %d\\n\", col, table.row_spans[col]);\n#endif // DEBUG", " // Figure out the starting column...\n if (table.num_rows)\n {\n\tfor (col = 0, rowspan = 9999; col < table.num_cols; col ++)\n\t if (table.row_spans[col] < rowspan)\n\t rowspan = table.row_spans[col];", "\tfor (col = 0; col < table.num_cols; col ++)\n\t table.row_spans[col] -= rowspan;", "\tfor (col = 0; table.row_spans[col] && col < table.num_cols; col ++)\n cells[table.num_rows][col] = cells[table.num_rows - 1][col];\n }\n else\n col = 0;", " for (tempcol = temprow->child;\n tempcol != NULL && col < MAX_COLUMNS;\n tempcol = tempcol->next)\n {\n if (tempcol->markup == MARKUP_TH && table.num_rows == 0)\n header_row = table.num_rows;", " if (tempcol->markup == MARKUP_TD || tempcol->markup == MARKUP_TH)\n {\n\t // Handle colspan and rowspan stuff...\n if ((var = htmlGetVariable(tempcol, (uchar *)\"COLSPAN\")) != NULL)\n {\n if ((colspan = atoi((char *)var)) < 1)\n colspan = 1;\n else if (colspan > (MAX_COLUMNS - col))\n colspan = MAX_COLUMNS - col;\n }\n else\n colspan = 1;", " if ((var = htmlGetVariable(tempcol, (uchar *)\"ROWSPAN\")) != NULL)\n\t {\n table.row_spans[col] = atoi((char *)var);", "\t if (table.row_spans[col] <= 1)\n\t table.row_spans[col] = 0;", "\t for (tcol = 1; tcol < colspan; tcol ++)\n table.row_spans[col + tcol] = table.row_spans[col];\n }", " // Compute the cell size...\n col_width = get_cell_size(tempcol, 0.0f, table_width, &col_min, &col_pref, &col_height);\n if ((var = htmlGetVariable(tempcol, (uchar *)\"WIDTH\")) != NULL)\n\t {\n\t if (var[strlen((char *)var) - 1] == '%')\n\t {\n col_width -= 2.0 * table.cellpadding - cellspacing;", "\t if (colspan <= 1)\n\t table.col_percent[col] = 1;\n\t }\n\t else\n\t {\n col_width -= 2.0 * table.cellpadding;\n\t }", "\t if (col_width <= 0.0f)\n\t col_width = 0.0f;\n\t else if (col_width > PageWidth)\n\t col_width = PageWidth;\n\t }\n\t else\n\t col_width = 0.0f;", " tempcol->height = col_height;", "\t DEBUG_printf((\"%d,%d: colsp=%d, rowsp=%d, width=%.1f, minw=%.1f, prefw=%.1f, minh=%.1f\\n\", col, table.num_rows, colspan, table.row_spans[col], col_width, col_min, col_pref, col_height));", " // Add widths to columns...\n if (colspan > 1)\n {\n\t if (colspan > table.col_spans[col])\n\t table.col_spans[col] = colspan;", "\t if (col_width > table.col_swidths[col])\n\t table.col_swidths[col] = col_width;", "\t if (col_min > table.col_smins[col])\n\t table.col_smins[col] = col_min;", "\t temp_width = col_width / colspan;\n\t for (int i = 0; i < colspan; i ++)\n\t {\n\t if (temp_width > table.col_widths[col + i])\n\t table.col_widths[col + i] = temp_width;\n\t }\n }\n\t else\n\t {\n\t if (col_width > 0.0f)\n\t table.col_fixed[col] = 1;", "\t if (col_width > table.col_widths[col])\n\t table.col_widths[col] = col_width;", "\t if (col_pref > table.col_prefs[col])\n\t table.col_prefs[col] = col_pref;", "\t if (col_min > table.col_mins[col])\n\t table.col_mins[col] = col_min;\n }", "\t while (colspan > 0 && col < MAX_COLUMNS)\n\t {\n cells[table.num_rows][col] = tempcol;\n col ++;\n colspan --;\n }", " while (table.row_spans[col] && col < table.num_cols)\n\t {\n cells[table.num_rows][col] = cells[table.num_rows - 1][col];\n\t col ++;\n\t }\n }\n }", " DEBUG_printf((\"header_row=%d\\n\", header_row));", " if (col > table.num_cols)\n table.num_cols = col;", "#ifdef DEBUG\n printf(\"AFTER row %d: num_cols = %d\\n\", table.num_rows, table.num_cols);", " for (col = 0; col < table.num_cols; col ++)\n printf(\" col %d: row_spans[] = %d\\n\", col, table.row_spans[col]);\n#endif // DEBUG", " table.num_rows ++;", " for (col = 0; col < table.num_cols; col ++)\n if (table.row_spans[col])\n\t table.row_spans[col] --;\n }\n }", " /*\n * OK, some people apparently create HTML tables with no columns or\n * rows... If this happened, return immediately...\n */", " if (table.num_cols == 0)\n return;", " /*\n * Now figure out the width of the table...\n */", " if ((var = htmlGetVariable(t, (uchar *)\"WIDTH\")) != NULL)\n {\n if (var[strlen((char *)var) - 1] == '%')\n width = (float)(atof((char *)var) * (right - left) / 100.0f);\n else\n width = (float)(atoi((char *)var) * PagePrintWidth / _htmlBrowserWidth);\n }\n else\n {\n for (col = 0, width = 0.0; col < table.num_cols; col ++)\n width += table.col_prefs[col];", " width += (2 * table.cellpadding + cellspacing) * table.num_cols - cellspacing;", " if (width > (right - left))\n width = right - left;\n }", " /*\n * Compute the width of each column based on the printable width.\n */", " DEBUG_printf((\"\\nTABLE: %dx%d\\n\\n\", table.num_cols, table.num_rows));", " actual_width = (2 * table.cellpadding + cellspacing) * table.num_cols -\n cellspacing;\n regular_width = (width - actual_width) / table.num_cols;", " DEBUG_printf((\" width = %.1f, actual_width = %.1f, regular_width = %.1f\\n\\n\",\n width, actual_width, regular_width));\n DEBUG_puts(\" Col Width Min Pref Fixed? Percent?\");\n DEBUG_puts(\" --- ------ ------ ------ ------ --------\");", "#ifdef DEBUG\n for (col = 0; col < table.num_cols; col ++)\n printf(\" %-3d %-6.1f %-6.1f %-6.1f %-6s %s\\n\", col, table.col_widths[col], table.col_mins[col], table.col_prefs[col], table.col_fixed[col] ? \"YES\" : \"NO\", table.col_percent[col] ? \"YES\" : \"NO\");", " puts(\"\");\n#endif /* DEBUG */", " /*\n * The first pass just handles columns with a specified width...\n */", " DEBUG_puts(\"PASS 1: fixed width handling\\n\");", " for (col = 0, regular_cols = 0; col < table.num_cols; col ++)\n if (table.col_widths[col] > 0.0f)\n {\n if (table.col_mins[col] > table.col_widths[col])\n {\n DEBUG_printf((\" updating column %d to width=%.1f\\n\", col, table.col_mins[col]));", " table.col_widths[col] = table.col_mins[col];\n }", " actual_width += table.col_widths[col];\n }\n else\n {\n regular_cols ++;", " actual_width += table.col_mins[col];\n }", " DEBUG_printf((\" actual_width = %.1f, regular_cols = %d\\n\\n\", actual_width,regular_cols));", " /*\n * Pass two uses the \"preferred\" width whenever possible, and the\n * minimum otherwise...\n */", " DEBUG_puts(\"PASS 2: preferred width handling\\n\");", " for (col = 0, pref_width = 0.0f; col < table.num_cols; col ++)\n if (table.col_widths[col] == 0.0f)\n pref_width += table.col_prefs[col] - table.col_mins[col];", " DEBUG_printf((\" pref_width = %.1f\\n\", pref_width));", " if (pref_width > 0.0f)\n {\n if ((regular_width = (width - actual_width) / pref_width) < 0.0f)\n regular_width = 0.0f;\n else if (regular_width > 1.0f)\n regular_width = 1.0f;", " DEBUG_printf((\" regular_width = %.1f\\n\", regular_width));", " for (col = 0; col < table.num_cols; col ++)\n if (table.col_widths[col] == 0.0f)\n {\n\tpref_width = (table.col_prefs[col] - table.col_mins[col]) * regular_width;", "\tif ((actual_width + pref_width) > width)\n\t{\n if (col == (table.num_cols - 1) && (width - actual_width) >= table.col_mins[col])\n\t table.col_widths[col] = width - actual_width;\n\t else\n\t table.col_widths[col] = table.col_mins[col];\n\t}\n\telse\n table.col_widths[col] = pref_width + table.col_mins[col];", " DEBUG_printf((\" col_widths[%d] = %.1f\\n\", col, table.col_widths[col]));", "\tactual_width += table.col_widths[col] - table.col_mins[col];\n }\n }\n else\n {\n /*\n * Assign min widths for all cells...\n */", " for (col = 0; col < table.num_cols; col ++)\n if (table.col_widths[col] == 0.0f)\n table.col_widths[col] = table.col_mins[col];\n }", " DEBUG_printf((\" actual_width = %.1f\\n\\n\", actual_width));", " /*\n * Pass three enforces any hard or minimum widths for COLSPAN'd\n * columns...\n */", " DEBUG_puts(\"PASS 3: colspan handling\\n\\n\");", " for (col = 0; col < table.num_cols; col ++)\n {\n DEBUG_printf((\" col %d, colspan %d\\n\", col, table.col_spans[col]));", " if (table.col_spans[col] > 1)\n {\n for (colspan = 0, span_width = 0.0f; colspan < table.col_spans[col]; colspan ++)\n span_width += table.col_widths[col + colspan];", " pref_width = 0.0f;", " if (span_width < table.col_swidths[col])\n pref_width = table.col_swidths[col];\n if (span_width < table.col_smins[col] && pref_width < table.col_smins[col])\n pref_width = table.col_smins[col];", " for (colspan = 0; colspan < table.col_spans[col]; colspan ++)\n if (table.col_fixed[col + colspan])\n\t{\n span_width -= table.col_widths[col + colspan];\n\t pref_width -= table.col_widths[col + colspan];\n\t}", " DEBUG_printf((\" col_swidths=%.1f, col_smins=%.1f, span_width=%.1f, pref_width=%.1f\\n\", table.col_swidths[col], table.col_smins[col], span_width, pref_width));", " if (pref_width > 0.0f && pref_width > span_width)\n {\n if (span_width >= 1.0f)\n\t{\n // Expand cells proportionately...\n\t regular_width = pref_width / span_width;", "\t for (colspan = 0; colspan < table.col_spans[col]; colspan ++)\n\t if (!table.col_fixed[col + colspan])\n\t {\n\t actual_width -= table.col_widths[col + colspan];\n\t table.col_widths[col + colspan] *= regular_width;\n\t actual_width += table.col_widths[col + colspan];", " DEBUG_printf((\" col_widths[%d] = %.1f\\n\", col + colspan, table.col_widths[col + colspan]));\n\t }\n }\n\telse\n\t{\n\t // Divide the space up equally between columns, since the\n\t // colspan area is always by itself... (this hack brought\n\t // to you by Yahoo! and their single cell tables with\n\t // colspan=2 :)", "\t regular_width = pref_width / table.col_spans[col];", "\t for (colspan = 0; colspan < table.col_spans[col]; colspan ++)\n\t {\n\t actual_width += regular_width;\n\t table.col_widths[col + colspan] += regular_width;", " DEBUG_printf((\" col_widths[%d] = %.1f\\n\", col, table.col_widths[col]));\n\t }\n\t}\n }\n }\n }", " DEBUG_printf((\" actual_width = %.1f\\n\\n\", actual_width));", " /*\n * Pass four divides up the remaining space amongst the columns...\n */", " DEBUG_puts(\"PASS 4: divide remaining space, if any...\\n\");", " if (width > actual_width)\n {\n for (col = 0, colspan = 0; col < table.num_cols; col ++)\n if (!table.col_fixed[col] || table.col_percent[col])\n colspan ++;", " if (colspan > 0)\n {\n regular_width = (width - actual_width) / table.num_cols;", " for (col = 0; col < table.num_cols; col ++)\n if (!table.col_fixed[col])\n\t{\n\t table.col_widths[col] += regular_width;\n\t DEBUG_printf((\" col_widths[%d] = %.1f\\n\", col, table.col_widths[col]));\n\t}\n }\n }\n else\n width = actual_width;", " DEBUG_puts(\"\");", " /*\n * The final pass is only run if the width > table_width...\n */", " DEBUG_puts(\"PASS 5: Squeeze table as needed...\");", " if (width > table_width)\n {\n /*\n * Squeeze the table to fit the requested width or the printable width\n * as determined at the beginning...\n */", " for (col = 0, min_width = -cellspacing; col < table.num_cols; col ++)\n min_width += table.col_mins[col] + 2 * table.cellpadding + cellspacing;", " DEBUG_printf((\" table_width = %.1f, width = %.1f, min_width = %.1f\\n\", table_width, width, min_width));", " temp_width = table_width - min_width;\n if (temp_width < 0.0f)\n temp_width = 0.0f;", " width -= min_width;\n if (width < 1.0f)\n width = 1.0f;", " for (col = 0; col < table.num_cols; col ++)\n {\n table.col_widths[col] = table.col_mins[col] + temp_width * (table.col_widths[col] - table.col_mins[col]) / width;", " DEBUG_printf((\" col_widths[%d] = %.1f\\n\", col, table.col_widths[col]));\n }", " for (col = 0, width = -cellspacing; col < table.num_cols; col ++)\n width += table.col_widths[col] + 2 * table.cellpadding + cellspacing;", " DEBUG_printf((\" new width = %.1f, max width = %.1f\\n\", width, right - left));\n }", " if ((width - right + left) > 0.001f && OverflowErrors)\n progress_error(HD_ERROR_CONTENT_TOO_LARGE, \"Table on page %d too wide - truncation or overlapping may occur!\", *page + 1);", " DEBUG_puts(\"\");", " DEBUG_printf((\"Final table width = %.1f, alignment = %d\\n\", width, t->halignment));", " switch (t->halignment)\n {\n case ALIGN_LEFT :\n *x = left + table.cellpadding;\n break;\n case ALIGN_CENTER :\n *x = left + 0.5f * (right - left - width) + table.cellpadding;\n break;\n case ALIGN_RIGHT :\n *x = right - width + table.cellpadding;\n break;\n }", " for (col = 0; col < table.num_cols; col ++)\n {\n table.col_lefts[col] = *x;\n table.col_rights[col] = *x + table.col_widths[col];\n *x = table.col_rights[col] + 2 * table.cellpadding + cellspacing;", " DEBUG_printf((\"left[%d] = %.1f, right[%d] = %.1f\\n\", col, table.col_lefts[col], col, table.col_rights[col]));\n }", " /*\n * Now render the whole table...\n */", " if (*y < top && needspace)\n *y -= _htmlSpacings[SIZE_P];", " if (table.debug)\n {\n check_pages(*page);", " render_t *r;\n char table_text[255];", " snprintf(table_text, sizeof(table_text), \"t=%p\", (void *)t);\n r = new_render(*page, RENDER_TEXT, left, *y,\n get_width((uchar *)table_text, TYPE_COURIER, STYLE_NORMAL, 3),\n\t\t _htmlSizes[3], table_text);", " r->data.text.typeface = TYPE_COURIER;\n r->data.text.style = STYLE_NORMAL;\n r->data.text.size = (float)_htmlSizes[3];\n }", " table_page = *page;\n table_y = *y;", " for (row = 0; row < table.num_rows; row ++)\n {\n height_var = NULL;", " if (cells[row][0] != NULL)\n {\n /*\n * Do page comments...\n */", " if (cells[row][0]->parent->prev != NULL &&\n cells[row][0]->parent->prev->markup == MARKUP_COMMENT)\n parse_comment(cells[row][0]->parent->prev, &left, &right, &temp_bottom, &temp_top, x, y, page, NULL, 0);", " /*\n * Get height...\n */", " if ((height_var = htmlGetVariable(cells[row][0]->parent, (uchar *)\"HEIGHT\")) == NULL)\n\tfor (col = 0; col < table.num_cols; col ++)\n\t if (htmlGetVariable(cells[row][col], (uchar *)\"ROWSPAN\") == NULL)\n\t if ((height_var = htmlGetVariable(cells[row][col], (uchar *)\"HEIGHT\")) != NULL)\n\t break;\n }", " if (height_var != NULL && row == header_row)\n header_height_var = height_var;", " if (cells[row][0] != NULL && height_var != NULL)\n {\n // Row height specified; make sure it'll fit...\n if (height_var[strlen((char *)height_var) - 1] == '%')\n\ttemp_height = (float)(atof((char *)height_var) * 0.01f * (PagePrintLength - 2 * table.cellpadding));\n else\n temp_height = (float)(atof((char *)height_var) * PagePrintWidth / _htmlBrowserWidth);", " if (table.height > 0.0f && temp_height > table.height)\n temp_height = table.height;", " temp_height -= 2 * table.cellpadding;\n }\n else\n {\n // Use min height computed from get_cell_size()...\n for (col = 0, temp_height = (float)_htmlSpacings[SIZE_P];\n col < table.num_cols;\n\t col ++)\n if (cells[row][col] != NULL &&\n\t cells[row][col]->height > temp_height &&\n\t !htmlGetVariable(cells[row][col], (uchar *)\"ROWSPAN\"))\n\t temp_height = cells[row][col]->height;", " if (table.height > 0.0)\n {\n\t// Table height specified; make sure it'll fit...\n\tif (temp_height > table.height)\n temp_height = table.height;\n\ttemp_height -= 2 * table.cellpadding;\n }\n else if (temp_height > (PageLength / 8.0) && height_var == NULL)\n\ttemp_height = PageLength / 8.0;\n }", " DEBUG_printf((\"BEFORE row = %d, temp_height = %.1f, *y = %.1f, *page = %d\\n\",\n row, temp_height, *y, *page));", " if (*y < (bottom + 2 * table.cellpadding + temp_height) &&\n temp_height <= (top - bottom - 2 * table.cellpadding))\n {\n DEBUG_puts(\"NEW PAGE\");", " *y = top - header_height;\n (*page) ++;", " if (Verbosity)\n progress_show(\"Formatting page %d\", *page);", " if (row > 0 && header_row >= 0)\n {\n // Render header row...\n render_table_row(table, cells, header_row, header_height_var, left, right, bottom, top, x, y, page);\n }\n }", " float start_y = *y;\n temp_page = *page;\n render_table_row(table, cells, row, height_var, left, right, bottom, top, x, y, page);\n if (header_row >= 0 && row == header_row)\n {\n header_height = *y - start_y;\n top += header_height;\n }\n else if (temp_page != *page && header_row >= 0)\n {\n // Render header row on new page(s)...\n do\n {\n float temp_y = top - header_height;", " temp_page ++;\n render_table_row(table, cells, header_row, header_height_var, left, right, bottom, top, x, &temp_y, &temp_page);\n }\n while (temp_page < *page);\n }", " if (row < (table.num_rows - 1))\n (*y) -= cellspacing;", " DEBUG_printf((\"END row = %d, *y = %.1f, *page = %d\\n\", row, *y, *page));\n }", " top -= header_height;", " /*\n * Handle table background color...\n */", " if ((bgcolor = htmlGetVariable(t, (uchar *)\"BGCOLOR\")) != NULL)\n {\n memcpy(bgrgb, background_color, sizeof(bgrgb));", " get_color(bgcolor, bgrgb, 0);", " table.border_left = table.col_lefts[0] - table.cellpadding;\n width = table.col_rights[table.num_cols - 1] - table.col_lefts[0] + 2 * table.cellpadding;", " if (table_page != *page)\n {\n // Draw background on multiple pages...", " // Bottom of first page...\n new_render(table_page, RENDER_BOX, table.border_left, bottom,\n\t width, table_y - bottom, bgrgb,\n\t\t pages[table_page].start);", " // Intervening pages...\n for (temp_page = table_page + 1; temp_page < *page; temp_page ++)\n {\n new_render(temp_page, RENDER_BOX, table.border_left, bottom,\n width, top - bottom, bgrgb, pages[temp_page].start);\n }", " // Top of last page...\n check_pages(*page);", " new_render(*page, RENDER_BOX, table.border_left, *y,\n\t width, top - *y, bgrgb, pages[*page].start);\n }\n else\n {\n // Draw background in row...\n new_render(table_page, RENDER_BOX, table.border_left, *y,\n\t width, table_y - *y, bgrgb, pages[table_page].start);\n }\n }", " *x = left;", " if (caption)\n {\n /*\n * Show caption at bottom...\n */", " parse_paragraph(caption, left, right, bottom, top, x, y, page, needspace);\n needspace = 1;\n }", " /*\n * Free memory for the table...\n */", " if (table.num_rows > 0)\n {\n for (row = 0; row < table.num_rows; row ++)\n free(cells[row]);", " free(cells);\n }\n}\n#ifdef TABLE_DEBUG\n# undef DEBUG\n# undef DEBUG_puts\n# define DEBUG_puts(x)\n# undef DEBUG_printf\n# define DEBUG_printf(x)\n#endif /* TABLE_DEBUG */", "\n/*\n * 'parse_list()' - Parse a list entry and produce rendering output.\n */", "static void\nparse_list(tree_t *t,\t\t/* I - Tree to parse */\n float *left,\t/* I - Left margin */\n float *right,\t/* I - Printable width */\n float *bottom,\t/* I - Bottom margin */\n float *top,\t\t/* I - Printable top */\n float *x,\t\t/* IO - X position */\n float *y,\t\t/* IO - Y position */\n int *page,\t/* IO - Page # */\n int needspace)\t/* I - Need whitespace? */\n{\n uchar\t\tnumber[255];\t/* List number (for numbered types) */\n uchar\t\t*value;\t\t/* VALUE= variable */\n int\t\ttypeface;\t/* Typeface of list number */\n float\t\twidth;\t\t/* Width of list number */\n render_t\t*r;\t\t/* Render primitive */\n int\t\toldpage;\t/* Old page value */\n float\t\toldy;\t\t/* Old Y value */\n float\t\ttempx;\t\t/* Temporary X value */", "\n DEBUG_printf((\"parse_list(t=%p, left=%.1f, right=%.1f, x=%.1f, y=%.1f, page=%d\\n\",\n (void *)t, *left, *right, *x, *y, *page));", " if (needspace && *y < *top)\n {\n *y -= _htmlSpacings[t->size];\n needspace = 0;\n }", " check_pages(*page);", " oldy = *y;\n oldpage = *page;\n r = pages[*page].end;\n tempx = *x;", " if (t->indent == 0)\n {\n // Adjust left margin when no UL/OL/DL is being used...\n *left += _htmlSizes[t->size];\n tempx += _htmlSizes[t->size];\n }", " parse_doc(t->child, left, right, bottom, top, &tempx, y, page, NULL,\n &needspace);", " // Handle when paragraph wrapped to new page...\n if (*page != oldpage)\n {\n // First see if anything was added to the old page...\n if ((r != NULL && r->next == NULL) || pages[oldpage].end == NULL)\n {\n // No, put the symbol on the next page...\n oldpage = *page;\n oldy = *top;\n }\n }", " if ((value = htmlGetVariable(t, (uchar *)\"VALUE\")) != NULL)\n {\n if (isdigit(value[0]))\n list_values[t->indent] = atoi((char *)value);\n else if (isupper(value[0]))\n list_values[t->indent] = value[0] - 'A' + 1;\n else\n list_values[t->indent] = value[0] - 'a' + 1;\n }", " switch (list_types[t->indent])\n {\n case 'a' :\n case 'A' :\n case '1' :\n case 'i' :\n case 'I' :\n strlcpy((char *)number, format_number(list_values[t->indent], (char)list_types[t->indent]), sizeof(number));\n strlcat((char *)number, \". \", sizeof(number));\n typeface = t->typeface;\n break;", " default :\n snprintf((char *)number, sizeof(number), \"%c \", list_types[t->indent]);\n typeface = TYPE_SYMBOL;\n break;\n }", " width = get_width(number, typeface, t->style, t->size);", " r = new_render(oldpage, RENDER_TEXT, *left - width, oldy - _htmlSizes[t->size],\n width, _htmlSpacings[t->size], number);\n r->data.text.typeface = typeface;\n r->data.text.style = t->style;\n r->data.text.size = (float)_htmlSizes[t->size];\n r->data.text.rgb[0] = t->red / 255.0f;\n r->data.text.rgb[1] = t->green / 255.0f;\n r->data.text.rgb[2] = t->blue / 255.0f;", " list_values[t->indent] ++;", " if (t->indent == 0)\n {\n // Adjust left margin when no UL/OL/DL is being used...\n *left -= _htmlSizes[t->size];\n }\n}", "\n/*\n * 'init_list()' - Initialize the list type and value as necessary.\n */", "static void\ninit_list(tree_t *t)\t\t/* I - List entry */\n{\n uchar\t\t*type,\t\t/* TYPE= variable */\n\t\t*value;\t\t/* VALUE= variable */\n static uchar\t*symbols = (uchar *)\"\\327\\267\\250\\340\";", "\n if ((type = htmlGetVariable(t, (uchar *)\"TYPE\")) != NULL)\n {\n if (strlen((char *)type) == 1)\n list_types[t->indent] = type[0];\n else if (strcasecmp((char *)type, \"disc\") == 0 ||\n strcasecmp((char *)type, \"circle\") == 0)\n list_types[t->indent] = symbols[1];\n else\n list_types[t->indent] = symbols[2];\n }\n else if (t->markup == MARKUP_UL)\n list_types[t->indent] = symbols[t->indent & 3];\n else if (t->markup == MARKUP_OL)\n list_types[t->indent] = '1';", " if ((value = htmlGetVariable(t, (uchar *)\"VALUE\")) == NULL)\n value = htmlGetVariable(t, (uchar *)\"START\");", " if (value != NULL)\n {\n if (isdigit(value[0]))\n list_values[t->indent] = atoi((char *)value);\n else if (isupper(value[0]))\n list_values[t->indent] = value[0] - 'A' + 1;\n else\n list_values[t->indent] = value[0] - 'a' + 1;\n }\n else if (t->markup == MARKUP_OL)\n list_values[t->indent] = 1;\n}", "\n/*\n * 'parse_comment()' - Parse a comment for HTMLDOC comments.\n */", "#ifdef COMMENT_DEBUG\n# undef DEBUG_puts\n# define DEBUG_puts(x) puts(x)\n# define DEBUG\n# undef DEBUG_printf\n# define DEBUG_printf(x) printf x\n#endif /* COMMENT_DEBUG */", "static void\nparse_comment(tree_t *t,\t/* I - Tree to parse */\n float *left,\t/* I - Left margin */\n float *right,\t/* I - Printable width */\n float *bottom,\t/* I - Bottom margin */\n float *top,\t/* I - Printable top */\n float *x,\t/* IO - X position */\n float *y,\t/* IO - Y position */\n int *page,\t/* IO - Page # */\n\t tree_t *para,\t/* I - Current paragraph */\n\t int needspace)\t/* I - Need whitespace? */\n{\n int\t\ti;\t\t/* Looping var */\n const char\t*comment;\t/* Comment text */\n char\t\t*ptr,\t\t/* Pointer into value string */\n\t\tbuffer[1024];\t/* Buffer for strings */\n int\t\tpos,\t\t/* Position (left, center, right) */\n\t\ttof;\t\t/* Top of form */", "\n DEBUG_printf((\"parse_comment(t=%p, left=%.1f, right=%.1f, bottom=%.1f, \"\n \"top=%.1f, x=%.1f, y=%.1f, page=%d, para=%p, needspace=%d\\n\",\n (void *)t, *left, *right, *bottom, *top, *x, *y, *page, (void *)para,\n\t\tneedspace));", " if (t->data == NULL)\n return;", " if (para != NULL && para->child != NULL && para->child->next == NULL &&\n para->child->child == NULL && para->child->markup == MARKUP_NONE &&\n strcmp((const char *)para->child->data, \" \") == 0)\n {\n // Remove paragraph consisting solely of whitespace...\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;\n }", " // Mark if we are at the top of form...\n tof = (*y >= *top);", " DEBUG_printf((\"BEFORE tof=%d, *y=%.1f, *top=%.1f, *page=%d, t->data=\\\"%s\\\"\\n\",\n \ttof, *y, *top, *page, t->data));\n DEBUG_printf((\" PagePrintWidth = %d\\n\", PagePrintWidth));\n DEBUG_printf((\"PagePrintLength = %d\\n\", PagePrintLength));\n DEBUG_printf((\" PageWidth = %d\\n\", PageWidth));\n DEBUG_printf((\" PageLength = %d\\n\", PageLength));\n DEBUG_printf((\" PageLeft = %d\\n\", PageLeft));\n DEBUG_printf((\" PageBottom = %d\\n\", PageBottom));\n DEBUG_printf((\" PageRight = %d\\n\", PageRight));\n DEBUG_printf((\" PageTop = %d\\n\", PageTop));\n DEBUG_printf((\" Landscape = %d\\n\", Landscape));", "\n for (comment = (const char *)t->data; *comment;)\n {\n // Skip leading whitespace...\n while (isspace(*comment))\n comment ++;", " if (!*comment)\n break;", " if (strncasecmp(comment, \"PAGE BREAK\", 10) == 0 &&\n\t(!comment[10] || isspace(comment[10])))\n {\n /*\n * <!-- PAGE BREAK --> generates a page break...\n */", " comment += 10;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;\n }", " (*page) ++;\n if (Verbosity)\n\tprogress_show(\"Formatting page %d\", *page);\n *x = *left;\n *y = *top;", " tof = 1;\n }\n else if (strncasecmp(comment, \"NEW PAGE\", 8) == 0 &&\n\t (!comment[8] || isspace(comment[8])))\n {\n /*\n * <!-- NEW PAGE --> generates a page break...\n */", " comment += 8;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;\n }", " (*page) ++;\n if (Verbosity)\n\tprogress_show(\"Formatting page %d\", *page);\n *x = *left;\n *y = *top;", " tof = 1;\n }\n else if (strncasecmp(comment, \"NEW SHEET\", 9) == 0 &&\n\t (!comment[9] || isspace(comment[9])))\n {\n /*\n * <!-- NEW SHEET --> generate a page break to a new sheet...\n */", " comment += 9;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;\n }", " if (NumberUp == 1)\n {\n // NEW SHEET breaks to the next sheet of paper...\n (*page) ++;", "\tif (PageDuplex && ((*page) & 1))\n\t (*page) ++;\n }\n else\n {\n // NEW SHEET breaks to the next side/sheet...\n (*page) ++;", "\tfor (i = *page - 1; i >= 0; i --)\n\t if (pages[i].nup != NumberUp)\n\t break;", " i ++;\n\tfor (i = *page - i; (i % NumberUp) != 0; i ++, (*page) ++);\n }", " if (Verbosity)\n\tprogress_show(\"Formatting page %d\", *page);", " *x = *left;\n *y = *top;", " tof = 1;\n }\n else if (strncasecmp(comment, \"HALF PAGE\", 9) == 0 &&\n (!comment[9] || isspace(comment[9])))\n {\n /*\n * <!-- HALF PAGE --> Go to the next half page. If in the\n * top half of a page, go to the bottom half. If in the\n * bottom half, go to the next page.\n */\n float halfway;", "\n comment += 9;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;\n }", " halfway = 0.5f * (*top + *bottom);", " if (*y <= halfway)\n {\n\t(*page) ++;\n\tif (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n\t*x = *left;\n\t*y = *top;", " tof = 1;\n }\n else\n {\n\t*x = *left;\n\t*y = halfway;", " tof = 0;\n }\n }\n else if (strncasecmp(comment, \"NEED \", 5) == 0)\n {\n /*\n * <!-- NEED amount --> generate a page break if there isn't\n * enough remaining space...\n */", " comment += 5;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if ((*y - get_measurement(comment, (float)_htmlSpacings[SIZE_P])) < *bottom)\n {\n\t(*page) ++;", "\tif (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n\t*y = *top;\n tof = 1;\n }", " *x = *left;", " // Skip amount...\n while (*comment && !isspace(*comment))\n comment ++;\n }\n else if (strncasecmp(comment, \"MEDIA COLOR \", 12) == 0)\n {\n // Media color for page...\n comment += 12;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (!tof)\n {\n\t(*page) ++;", "\tif (PageDuplex && ((*page) & 1))\n\t (*page) ++;", "\tif (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n\t*y = *top;\n tof = 1;\n }", " *x = *left;", " check_pages(*page);", " // Get color...\n if (*comment == '\\\"')\n {\n\tfor (ptr = pages[*page].media_color, comment ++;\n *comment && *comment != '\\\"';\n\t comment ++)\n if (ptr < (pages[*page].media_color +\n\t sizeof(pages[*page].media_color) - 1))\n\t *ptr++ = *comment;", " if (*comment == '\\\"')\n\t comment ++;\n }\n else\n {\n\tfor (ptr = pages[*page].media_color;\n *comment && !isspace(*comment);\n\t comment ++)\n if (ptr < (pages[*page].media_color +\n\t sizeof(pages[*page].media_color) - 1))\n\t *ptr++ = *comment;\n }", " *ptr = '\\0';\n }\n else if (strncasecmp(comment, \"MEDIA POSITION \", 15) == 0)\n {\n // Media position for page...\n comment += 15;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (!tof)\n {\n\t(*page) ++;", "\tif (PageDuplex && ((*page) & 1))\n\t (*page) ++;", "\tif (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n\t*y = *top;\n tof = 1;\n }", " *x = *left;", " check_pages(*page);", " pages[*page].media_position = atoi(comment);", " // Skip position...\n while (*comment && !isspace(*comment))\n comment ++;\n }\n else if (strncasecmp(comment, \"MEDIA TYPE \", 11) == 0)\n {\n // Media type for page...\n comment += 11;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (!tof)\n {\n\t(*page) ++;", "\tif (PageDuplex && ((*page) & 1))\n\t (*page) ++;", "\tif (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n\t*y = *top;\n tof = 1;\n }", " *x = *left;", " check_pages(*page);", " // Get type...\n if (*comment == '\\\"')\n {\n\tfor (ptr = pages[*page].media_type, comment ++;\n *comment && *comment != '\\\"';\n\t comment ++)\n if (ptr < (pages[*page].media_type +\n\t sizeof(pages[*page].media_type) - 1))\n\t *ptr++ = *comment;", " if (*comment == '\\\"')\n\t comment ++;\n }\n else\n {\n\tfor (ptr = pages[*page].media_type;\n *comment && !isspace(*comment);\n\t comment ++)\n if (ptr < (pages[*page].media_type +\n\t sizeof(pages[*page].media_type) - 1))\n\t *ptr++ = *comment;\n }", " *ptr = '\\0';\n }\n else if (strncasecmp(comment, \"MEDIA SIZE \", 11) == 0)\n {\n // Media size...\n comment += 11;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (!tof)\n {\n\t(*page) ++;", " tof = 1;\n }", " if (PageDuplex && ((*page) & 1))\n\t(*page) ++;", " if (Verbosity)\n\tprogress_show(\"Formatting page %d\", *page);", " check_pages(*page);", " *right = PagePrintWidth - *right;\n *top = PagePrintLength - *top;", " set_page_size(comment);", " if (Landscape)\n {\n\tPagePrintWidth = PageLength - PageLeft - PageRight;\n\tPagePrintLength = PageWidth - PageTop - PageBottom;\n }\n else\n {\n\tPagePrintWidth = PageWidth - PageLeft - PageRight;\n\tPagePrintLength = PageLength - PageTop - PageBottom;\n }", " *right = PagePrintWidth - *right;\n *top = PagePrintLength - *top;", " *x = *left;\n *y = *top;", " pages[*page].width = PageWidth;\n pages[*page].length = PageLength;", " // Skip width...\n while (*comment && !isspace(*comment))\n comment ++;\n }\n else if (strncasecmp(comment, \"MEDIA LEFT \", 11) == 0)\n {\n // Left margin...\n comment += 11;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (!tof)\n {\n\t(*page) ++;", "\tif (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n\t*y = *top;\n tof = 1;\n }", " *x = *left;", " check_pages(*page);", " *right = PagePrintWidth - *right;\n PageLeft = pages[*page].left = get_measurement(comment);", " if (Landscape)\n\tPagePrintWidth = PageLength - PageRight - PageLeft;\n else\n\tPagePrintWidth = PageWidth - PageRight - PageLeft;", " *right = PagePrintWidth - *right;", " // Skip left...\n while (*comment && !isspace(*comment))\n comment ++;\n }\n else if (strncasecmp(comment, \"MEDIA RIGHT \", 12) == 0)\n {\n // Right margin...\n comment += 12;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (!tof)\n {\n\t(*page) ++;", "\tif (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n\t*y = *top;\n tof = 1;\n }", " *x = *left;", " check_pages(*page);", " *right = PagePrintWidth - *right;\n PageRight = pages[*page].right = get_measurement(comment);", " if (Landscape)\n\tPagePrintWidth = PageLength - PageRight - PageLeft;\n else\n\tPagePrintWidth = PageWidth - PageRight - PageLeft;", " *right = PagePrintWidth - *right;", " // Skip right...\n while (*comment && !isspace(*comment))\n comment ++;\n }\n else if (strncasecmp(comment, \"MEDIA BOTTOM \", 13) == 0)\n {\n // Bottom margin...\n comment += 13;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (!tof)\n {\n\t(*page) ++;", "\tif (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n tof = 1;\n }", " *x = *left;", " check_pages(*page);", " *top = PagePrintLength - *top;\n PageBottom = pages[*page].bottom = get_measurement(comment);", " if (Landscape)\n PagePrintLength = PageWidth - PageTop - PageBottom;\n else\n PagePrintLength = PageLength - PageTop - PageBottom;", " *top = PagePrintLength - *top;\n *y = *top;", " // Skip bottom...\n while (*comment && !isspace(*comment))\n comment ++;\n }\n else if (strncasecmp(comment, \"MEDIA TOP \", 10) == 0)\n {\n // Top margin...\n comment += 10;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (!tof)\n {\n\t(*page) ++;", "\tif (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);", " tof = 1;\n }", " *x = *left;", " check_pages(*page);", " *top = PagePrintLength - *top;\n PageTop = pages[*page].top = get_measurement(comment);", " if (Landscape)\n PagePrintLength = PageWidth - PageTop - PageBottom;\n else\n PagePrintLength = PageLength - PageTop - PageBottom;", " *top = PagePrintLength - *top;\n *y = *top;", " // Skip top...\n while (*comment && !isspace(*comment))\n comment ++;\n }\n else if (strncasecmp(comment, \"MEDIA LANDSCAPE \", 16) == 0)\n {\n // Landscape on/off...\n comment += 16;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (!tof)\n {\n\t(*page) ++;", " tof = 1;\n }", " if (PageDuplex && ((*page) & 1))\n\t(*page) ++;", " if (Verbosity)\n\tprogress_show(\"Formatting page %d\", *page);", " *x = *left;", " check_pages(*page);", " if (strncasecmp(comment, \"OFF\", 3) == 0 || tolower(comment[0]) == 'n')\n {\n if (Landscape)\n\t{\n\t *right = PageLength - PageRight - *right;\n\t PagePrintWidth = PageWidth - PageRight - PageLeft;\n\t *right = PageWidth - PageRight - *right;", "\t *top = PageWidth - PageTop - *top;\n\t PagePrintLength = PageLength - PageTop - PageBottom;\n\t *top = PageLength - PageTop - *top;\n }", " Landscape = pages[*page].landscape = 0;\n }\n else if (strncasecmp(comment, \"ON\", 2) == 0 || tolower(comment[0]) == 'y')\n {\n if (!Landscape)\n\t{\n\t *top = PageLength - PageTop - *top;\n\t PagePrintLength = PageWidth - PageTop - PageBottom;\n\t *top = PageWidth - PageTop - *top;", "\t *right = PageWidth - PageRight - *right;\n\t PagePrintWidth = PageLength - PageRight - PageLeft;\n\t *right = PageLength - PageRight - *right;\n }", " Landscape = pages[*page].landscape = 1;\n }", " *y = *top;", " // Skip landscape...\n while (*comment && !isspace(*comment))\n comment ++;\n }\n else if (strncasecmp(comment, \"MEDIA DUPLEX \", 13) == 0)\n {\n // Duplex printing on/off...\n comment += 13;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (!tof)\n {\n\t(*page) ++;", "\t*y = *top;\n tof = 1;\n }", " if (PageDuplex && ((*page) & 1))\n\t(*page) ++;", " if (Verbosity)\n\tprogress_show(\"Formatting page %d\", *page);", " *x = *left;", " check_pages(*page);", " if (strncasecmp(comment, \"OFF\", 3) == 0 || tolower(comment[0]) == 'n')\n PageDuplex = pages[*page].duplex = 0;\n else if (strncasecmp(comment, \"ON\", 2) == 0 || tolower(comment[0]) == 'y')\n {\n\tif ((*page) & 1)\n\t{\n\t (*page) ++;", " check_pages(*page);", "\t if (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n\t}", " PageDuplex = pages[*page].duplex = 1;\n }", " // Skip duplex...\n while (*comment && !isspace(*comment))\n comment ++;\n }\n else if (strncasecmp(comment, \"HEADER \", 7) == 0)\n {\n // Header string...\n comment += 7;", " while (isspace(*comment))\n\tcomment ++;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (strncasecmp(comment, \"LEFT\", 4) == 0 && isspace(comment[4]))\n {\n pos = 0;\n\tcomment += 4;\n }\n else if (strncasecmp(comment, \"CENTER\", 6) == 0 && isspace(comment[6]))\n {\n pos = 1;\n\tcomment += 6;\n }\n else if (strncasecmp(comment, \"RIGHT\", 5) == 0 && isspace(comment[5]))\n {\n pos = 2;\n\tcomment += 5;\n }\n else\n {\n progress_error(HD_ERROR_BAD_COMMENT,\n \"Bad HEADER position: \\\"%s\\\"\", comment);\n\treturn;\n }", " while (isspace(*comment))\n\tcomment ++;", " if (*comment != '\\\"')\n {\n progress_error(HD_ERROR_BAD_COMMENT,\n \"Bad HEADER string: \\\"%s\\\"\", comment);\n\treturn;\n }", " for (ptr = buffer, comment ++; *comment && *comment != '\\\"'; comment ++)\n {\n if (*comment == '\\\\')\n\t comment ++;", "\tif (ptr < (buffer + sizeof(buffer) - 1))\n\t *ptr++ = *comment;\n }", " if (*comment == '\\\"')\n comment ++;", " *ptr = '\\0';", " if (ptr > buffer)\n Header[pos] = strdup(buffer);\n else\n Header[pos] = NULL;", " if (tof)\n {\n DEBUG_printf((\"Setting header %d for page %d to \\\"%s\\\"...\\n\",\n\t pos, *page, Header[pos] ? Header[pos] : \"(null)\"));", "\tcheck_pages(*page);", "\tpages[*page].header[pos] = (uchar *)Header[pos];\n }", " // Adjust top margin as needed...\n float adjust, image_adjust, temp_adjust;", " if (maxhfheight > HeadFootSize)\n\timage_adjust = (float)(maxhfheight + HeadFootSize);\n else\n\timage_adjust = (float)(2 * HeadFootSize);", " for (adjust = 0.0, pos = 0; pos < 3; pos ++)\n {\n\tif (Header[pos] &&\n\t (strstr(Header[pos], \"$IMAGE\") != NULL ||\n\t strstr(Header[pos], \"$HFIMAGE\") != NULL))\n\t temp_adjust = image_adjust;\n\telse if (Header1[pos] &&\n\t\t (strstr(Header1[pos], \"$IMAGE\") != NULL ||\n\t\t strstr(Header1[pos], \"$HFIMAGE\") != NULL))\n\t temp_adjust = image_adjust;\n\telse if (Header[pos] || Header1[pos])\n\t temp_adjust = (float)(2 * HeadFootSize);\n\telse\n\t temp_adjust = 0.0;", "\tif (temp_adjust > adjust)\n\t adjust = temp_adjust;\n }", " *top = PagePrintLength - adjust;", " if (tof)\n *y = *top;\n }\n else if (strncasecmp(comment, \"HEADER1 \", 8) == 0)\n {\n // First page header string...\n comment += 8;", " while (isspace(*comment))\n\tcomment ++;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (strncasecmp(comment, \"LEFT\", 4) == 0 && isspace(comment[4]))\n {\n pos = 0;\n\tcomment += 4;\n }\n else if (strncasecmp(comment, \"CENTER\", 6) == 0 && isspace(comment[6]))\n {\n pos = 1;\n\tcomment += 6;\n }\n else if (strncasecmp(comment, \"RIGHT\", 5) == 0 && isspace(comment[5]))\n {\n pos = 2;\n\tcomment += 5;\n }\n else\n {\n progress_error(HD_ERROR_BAD_COMMENT,\n \"Bad HEADER1 position: \\\"%s\\\"\", comment);\n\treturn;\n }", " while (isspace(*comment))\n\tcomment ++;", " if (*comment != '\\\"')\n {\n progress_error(HD_ERROR_BAD_COMMENT,\n \"Bad HEADER1 string: \\\"%s\\\"\", comment);\n\treturn;\n }", " for (ptr = buffer, comment ++; *comment && *comment != '\\\"'; comment ++)\n {\n if (*comment == '\\\\')\n\t comment ++;", "\tif (ptr < (buffer + sizeof(buffer) - 1))\n\t *ptr++ = *comment;\n }", " if (*comment == '\\\"')\n comment ++;", " *ptr = '\\0';", " if (ptr > buffer)\n Header1[pos] = strdup(buffer);\n else\n Header1[pos] = NULL;", " // Adjust top margin as needed...\n float adjust, image_adjust, temp_adjust;", " if (maxhfheight > HeadFootSize)\n\timage_adjust = (float)(maxhfheight + HeadFootSize);\n else\n\timage_adjust = (float)(2 * HeadFootSize);", " for (adjust = 0.0, pos = 0; pos < 3; pos ++)\n {\n\tif (Header[pos] &&\n\t (strstr(Header[pos], \"$IMAGE\") != NULL ||\n\t strstr(Header[pos], \"$HFIMAGE\") != NULL))\n\t temp_adjust = image_adjust;\n\telse if (Header1[pos] &&\n\t\t (strstr(Header1[pos], \"$IMAGE\") != NULL ||\n\t\t strstr(Header1[pos], \"$HFIMAGE\") != NULL))\n\t temp_adjust = image_adjust;\n\telse if (Header[pos] || Header1[pos])\n\t temp_adjust = (float)(2 * HeadFootSize);\n\telse\n\t temp_adjust = 0.0;", "\tif (temp_adjust > adjust)\n\t adjust = temp_adjust;\n }", " *top = PagePrintLength - adjust;", " if (tof)\n *y = *top;\n }\n else if (strncasecmp(comment, \"FOOTER \", 7) == 0)\n {\n // Footer string...\n comment += 7;", " while (isspace(*comment))\n\tcomment ++;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (strncasecmp(comment, \"LEFT\", 4) == 0 && isspace(comment[4]))\n {\n pos = 0;\n\tcomment += 4;\n }\n else if (strncasecmp(comment, \"CENTER\", 6) == 0 && isspace(comment[6]))\n {\n pos = 1;\n\tcomment += 6;\n }\n else if (strncasecmp(comment, \"RIGHT\", 5) == 0 && isspace(comment[5]))\n {\n pos = 2;\n\tcomment += 5;\n }\n else\n {\n progress_error(HD_ERROR_BAD_COMMENT,\n \"Bad FOOTER position: \\\"%s\\\"\", comment);\n\treturn;\n }", " while (isspace(*comment))\n\tcomment ++;", " if (*comment != '\\\"')\n {\n progress_error(HD_ERROR_BAD_COMMENT,\n \"Bad FOOTER string: \\\"%s\\\"\", comment);\n\treturn;\n }", " for (ptr = buffer, comment ++; *comment && *comment != '\\\"'; comment ++)\n {\n if (*comment == '\\\\')\n\t comment ++;", "\tif (ptr < (buffer + sizeof(buffer) - 1))\n\t *ptr++ = *comment;\n }", " if (*comment == '\\\"')\n comment ++;", " *ptr = '\\0';", " if (ptr > buffer)\n Footer[pos] = strdup(buffer);\n else\n Footer[pos] = NULL;", " if (tof)\n {\n\tcheck_pages(*page);", "\tpages[*page].footer[pos] = (uchar *)Footer[pos];\n }", " // Adjust bottom margin as needed...\n float adjust, image_adjust, temp_adjust;", " if (maxhfheight > HeadFootSize)\n\timage_adjust = (float)(maxhfheight + HeadFootSize);\n else\n\timage_adjust = (float)(2 * HeadFootSize);", " for (adjust = 0.0, pos = 0; pos < 3; pos ++)\n {\n\tif (Footer[pos] &&\n\t (strstr(Footer[pos], \"$IMAGE\") != NULL ||\n\t strstr(Footer[pos], \"$HFIMAGE\") != NULL))\n\t temp_adjust = image_adjust;\n\telse if (Footer[pos])\n\t temp_adjust = (float)(2 * HeadFootSize);\n\telse\n\t temp_adjust = 0.0;", "\tif (temp_adjust > adjust)\n\t adjust = temp_adjust;\n }", " *bottom = adjust;\n }\n else if (strncasecmp(comment, \"NUMBER-UP \", 10) == 0)\n {\n // N-up printing...\n comment += 10;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " NumberUp = strtol(comment, (char **)&comment, 10);", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (tof)\n {\n\tcheck_pages(*page);", " pages[*page].nup = NumberUp;\n }\n }\n else\n break;\n }", " DEBUG_printf((\"LEAVING parse_comment() x=%.1f, y=%.1f, page=%d\\n\",\n *x, *y, *page));\n DEBUG_printf((\" PagePrintWidth = %d\\n\", PagePrintWidth));\n DEBUG_printf((\"PagePrintLength = %d\\n\", PagePrintLength));\n DEBUG_printf((\" PageWidth = %d\\n\", PageWidth));\n DEBUG_printf((\" PageLength = %d\\n\", PageLength));\n DEBUG_printf((\" PageLeft = %d\\n\", PageLeft));\n DEBUG_printf((\" PageBottom = %d\\n\", PageBottom));\n DEBUG_printf((\" PageRight = %d\\n\", PageRight));\n DEBUG_printf((\" PageTop = %d\\n\", PageTop));\n DEBUG_printf((\" Landscape = %d\\n\", Landscape));\n}", "#ifdef COMMENT_DEBUG\n# undef DEBUG\n# undef DEBUG_puts\n# define DEBUG_puts(x)\n# undef DEBUG_printf\n# define DEBUG_printf(x)\n#endif /* COMMENT_DEBUG */", "\n/*\n * 'find_background()' - Find the background image/color for the given document.\n */", "static void\nfind_background(tree_t *t)\t/* I - Document to search */\n{\n uchar\t\t*var;\t\t/* BGCOLOR/BACKGROUND variable */", "\n /*\n * First see if the --bodycolor or --bodyimage options have been\n * specified...\n */", " if (BodyImage[0] != '\\0')\n {\n background_image = image_load(BodyImage, !OutputColor);\n return;\n }\n else if (BodyColor[0] != '\\0')\n {\n get_color((uchar *)BodyColor, background_color, 0);\n return;\n }", " /*\n * If not, search the document tree...\n */", " while (t != NULL && background_image == NULL &&\n background_color[0] == 1.0 && background_color[1] == 1.0 &&\n\t background_color[2] == 1.0)\n {\n if (t->markup == MARKUP_BODY)\n {\n if ((var = htmlGetVariable(t, (uchar *)\"BACKGROUND\")) != NULL)\n background_image = image_load((char *)var, !OutputColor);", " if ((var = htmlGetVariable(t, (uchar *)\"BGCOLOR\")) != NULL)\n get_color(var, background_color, 0);\n }", " if (t->child != NULL)\n find_background(t->child);", " t = t->next;\n }\n}", "\n/*\n * 'write_background()' - Write the background image/color for to the current\n * page.\n */", "static void\nwrite_background(int page,\t/* I - Page we are writing for */\n FILE *out)\t/* I - File to write to */\n{\n float\tx, y;\n float\twidth, height;\n int\tpage_width, page_length;", "\n if (Landscape)\n {\n page_length = pages[page].width;\n page_width = pages[page].length;\n }\n else\n {\n page_width = pages[page].width;\n page_length = pages[page].length;\n }", " if (background_color[0] != 1.0 ||\n background_color[1] != 1.0 ||\n background_color[2] != 1.0)\n {\n if (PSLevel > 0)\n {\n render_x = -1.0;\n render_y = -1.0;\n set_color(out, background_color);\n fprintf(out, \"0 0 M %d %d F\\n\", page_width, page_length);\n }\n else\n {\n set_color(out, background_color);\n flate_printf(out, \"0 0 %d %d re f\\n\", page_width, page_length);\n }\n }", " if (background_image != NULL)\n {\n width = (float)(background_image->width * 72.0f / _htmlPPI);\n height = (float)(background_image->height * 72.0f / _htmlPPI);", " if (width < 1.0f)\n width = 1.0f;\n if (height < 1.0f)\n height = 1.0f;", " switch (PSLevel)\n {\n case 0 :\n for (x = 0.0; x < page_width; x += width)\n for (y = page_length; y >= 0.0f;)\n {\n\t y -= height;\n \t flate_printf(out, \"q %.1f 0 0 %.1f %.1f %.1f cm\", width, height, x, y);\n flate_printf(out, \"/I%d Do\\n\", background_image->obj);\n\t flate_puts(\"Q\\n\", out);\n }\n\t break;", " default :\n fprintf(out, \"0 %.1f %d{/y exch neg %d add def\\n\",\n\t height, page_length + (int)height - 1, page_length);\n\t fprintf(out, \"0 %.1f %d{/x exch def\\n\",\n\t width, page_width);\n fprintf(out, \"GS[%.1f 0 0 %.1f x y]CM/iy -1 def\\n\", width, height);\n\t fprintf(out, \"%d %d 8[%d 0 0 %d 0 %d]\",\n\t background_image->width, background_image->height,\n background_image->width, -background_image->height,\n\t\t background_image->height);\n fputs(\"{/iy iy 1 add def BG iy get}\", out);\n\t if (background_image->depth == 1)\n\t fputs(\"image\\n\", out);\n\t else\n\t fputs(\"false 3 colorimage\\n\", out);\n\t fputs(\"GR}for}for\\n\", out);\n break;\n }\n }\n}", "\n/*\n * 'new_render()' - Allocate memory for a new rendering structure.\n */", "static render_t *\t\t\t/* O - New render structure */\nnew_render(int page,\t\t/* I - Page number (0-n) */\n int type,\t\t/* I - Type of render primitive */\n double x,\t\t\t/* I - Horizontal position */\n double y,\t\t\t/* I - Vertical position */\n double width,\t\t/* I - Width */\n double height,\t\t/* I - Height */\n void *data,\t\t/* I - Data */\n\t render_t *insert)\t\t/* I - Insert before here... */\n{\n render_t\t\t*r;\t\t/* New render primitive */\n size_t\t\tdatalen = 0;\t/* Length of data */\n static render_t\tdummy;\t\t/* Dummy var for errors... */", "\n DEBUG_printf((\"new_render(page=%d, type=%d, x=%.1f, y=%.1f, width=%.1f, height=%.1f, data=%p, insert=%p)\\n\",\n page, type, x, y, width, height, (void *)data, (void *)insert));", " check_pages(page);", " if (page < 0 || page >= (int)alloc_pages)\n {\n progress_error(HD_ERROR_INTERNAL_ERROR,\n \"Page number (%d) out of range (1...%d)\\n\", page + 1,\n (int)alloc_pages);\n memset(&dummy, 0, sizeof(dummy));\n return (&dummy);\n }", " if ((type != RENDER_TEXT && type != RENDER_LINK) || data == NULL)\n r = (render_t *)calloc(sizeof(render_t), 1);\n else\n {\n datalen = strlen((char *)data);\n r = (render_t *)calloc(sizeof(render_t) + datalen, 1);\n }", " if (r == NULL)\n {\n progress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory on page %d\\n\", (int)page + 1);\n memset(&dummy, 0, sizeof(dummy));\n return (&dummy);\n }", " r->type = type;\n r->x = (float)x;\n r->y = (float)y;\n r->width = (float)width;\n r->height = (float)height;", " switch (type)\n {\n case RENDER_TEXT :\n if (data == NULL)\n {\n free(r);\n return (NULL);\n }\n\t// Safe because buffer is allocated...\n memcpy((char *)r->data.text.buffer, (char *)data, datalen);\n get_color(_htmlTextColor, r->data.text.rgb);\n break;\n case RENDER_IMAGE :\n if (data == NULL)\n {\n free(r);\n return (NULL);\n }\n r->data.image = (image_t *)data;\n break;\n case RENDER_BOX :\n memcpy(r->data.box, data, sizeof(r->data.box));\n break;\n case RENDER_LINK :\n if (data == NULL)\n {\n free(r);\n return (NULL);\n }\n\t// Safe because buffer is allocated...\n memcpy((char *)r->data.link, (char *)data, datalen);\n break;\n }", " if (insert)\n {\n if (insert->prev)\n insert->prev->next = r;\n else\n pages[page].start = r;", " r->prev = insert->prev;\n r->next = insert;\n insert->prev = r;\n }\n else\n {\n if (pages[page].end != NULL)\n pages[page].end->next = r;\n else\n pages[page].start = r;", " r->next = NULL;\n r->prev = pages[page].end;\n pages[page].end = r;\n }", " DEBUG_printf((\" returning r = %p\\n\", (void *)r));", " return (r);\n}", "\n/*\n * 'check_pages()' - Allocate memory for more pages as needed...\n */", "static void\ncheck_pages(int page)\t// I - Current page\n{\n page_t\t*temp;\t// Temporary page pointer", "\n DEBUG_printf((\"check_pages(%d)\\n\", page));", " // See if we need to allocate memory for the page...\n if (page >= (int)alloc_pages)\n {\n // Yes, allocate enough for ALLOC_PAGES more pages...\n while (page >= (int)alloc_pages)\n alloc_pages += ALLOC_PAGES;", " // Do the pages pointers...\n if (num_pages == 0)\n temp = (page_t *)malloc(sizeof(page_t) * alloc_pages);\n else\n temp = (page_t *)realloc(pages, sizeof(page_t) * alloc_pages);", " if (temp == NULL)\n {\n progress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory for %d pages - %s\",\n\t (int)alloc_pages, strerror(errno));\n alloc_pages -= ALLOC_PAGES;\n return;\n }", " memset(temp + num_pages, 0, (alloc_pages - num_pages) * sizeof(page_t));", " pages = temp;\n }", " // Initialize the page data as needed...\n for (temp = pages + num_pages; (int)num_pages <= page; num_pages ++, temp ++)\n {\n if (!temp->width)\n {\n if (num_pages == 0 || !temp[-1].width || !temp[-1].length || chapter == 0)\n {\n\ttemp->width = PageWidth;\n\ttemp->length = PageLength;\n\ttemp->left = PageLeft;\n\ttemp->right = PageRight;\n\ttemp->top = PageTop;\n\ttemp->bottom = PageBottom;\n\ttemp->duplex = PageDuplex;\n\ttemp->landscape = Landscape;\n\ttemp->nup = NumberUp;\n }\n else\n {\n\tmemcpy(temp, temp - 1, sizeof(page_t));\n\ttemp->start = NULL;\n\ttemp->end = NULL;\n }", " temp->url = current_url;", " if (chapter == 0)\n {\n\tmemcpy(temp->header, TocHeader, sizeof(temp->header));\n\tmemcpy(temp->footer, TocFooter, sizeof(temp->footer));\n }\n else\n {\n\tmemcpy(temp->header, Header, sizeof(temp->header));\n\tmemcpy(temp->header1, Header1, sizeof(temp->header1));\n\tmemcpy(temp->footer, Footer, sizeof(temp->footer));", " if (current_heading != temp->headnode)\n\t{\n\t temp->heading = htmlGetText(current_heading);\n\t temp->headnode = current_heading;\n\t}\n }", " memcpy(temp->background_color, background_color,\n sizeof(temp->background_color));\n temp->background_image = background_image;\n }\n }\n}", "\n/*\n * 'add_link()' - Add a named link...\n */", "static void\nadd_link(uchar *name,\t\t/* I - Name of link */\n int page,\t\t/* I - Page # */\n int top)\t\t/* I - Y position */\n{\n link_t\t*temp;\t\t/* New name */", "\n if (name == NULL)\n return;", " DEBUG_printf((\"add_link(name=\\\"%s\\\", page=%d, top=%d)\\n\", name, page, top));", " if ((temp = find_link(name)) != NULL)\n {\n temp->page = (short)page;\n temp->top = (short)top;\n }\n else\n {\n // See if we need to allocate memory for links...\n if (num_links >= alloc_links)\n {\n // Allocate more links...\n alloc_links += ALLOC_LINKS;", " if (num_links == 0)\n temp = (link_t *)malloc(sizeof(link_t) * alloc_links);\n else\n temp = (link_t *)realloc(links, sizeof(link_t) * alloc_links);", " if (temp == NULL)\n {\n\tprogress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory for %d links - %s\",\n\t (int)alloc_links, strerror(errno));\n alloc_links -= ALLOC_LINKS;\n\treturn;\n }", " links = temp;\n }", " // Add a new link...\n temp = links + num_links;\n num_links ++;", " strlcpy((char *)temp->name, (char *)name, sizeof(temp->name));\n temp->page = (short)page;\n temp->top = (short)top;", " if (num_links > 1)\n qsort(links, num_links, sizeof(link_t),\n (compare_func_t)compare_links);\n }\n}", "\n/*\n * 'find_link()' - Find a named link...\n */", "static link_t *\nfind_link(uchar *name)\t/* I - Name to find */\n{\n link_t\tkey,\t/* Search key */\n\t\t*match;\t/* Matching name entry */", "\n if (name == NULL || num_links == 0)\n return (NULL);", " if (name[0] == '#')\n name ++;", " strlcpy((char *)key.name, (char *)name, sizeof(key.name));\n match = (link_t *)bsearch(&key, links, num_links, sizeof(link_t),\n (compare_func_t)compare_links);", " return (match);\n}", "\n/*\n * 'compare_links()' - Compare two named links.\n */", "static int\t\t\t/* O - 0 = equal, -1 or 1 = not equal */\ncompare_links(link_t *n1,\t/* I - First name */\n link_t *n2)\t/* I - Second name */\n{\n return (strcasecmp((char *)n1->name, (char *)n2->name));\n}", "\n#ifdef TABLE_DEBUG\n# undef DEBUG_printf\n# undef DEBUG_puts\n# define DEBUG_printf(x) printf x\n# define DEBUG_puts(x) puts(x)\n#endif /* TABLE_DEBUG */", "//\n// 'get_cell_size()' - Compute the minimum width of a cell.\n//", "static float\t\t\t\t// O - Required width of cell\nget_cell_size(tree_t *t,\t\t// I - Cell\n float left,\t\t// I - Left margin\n\t float right,\t\t// I - Right margin\n\t float *minwidth,\t\t// O - Minimum width\n\t float *prefwidth,\t// O - Preferred width\n\t float *minheight)\t// O - Minimum height\n{\n tree_t\t*temp,\t\t\t// Current tree entry\n\t\t*next;\t\t\t// Next tree entry\n uchar\t\t*var;\t\t\t// Attribute value\n int\t\tnowrap;\t\t\t// NOWRAP attribute?\n float\t\twidth,\t\t\t// Width of cell\n\t\tfrag_width,\t\t// Fragment required width\n\t\tfrag_height,\t\t// Fragment height\n\t\tfrag_pref,\t\t// Fragment preferred width\n\t\tfrag_min,\t\t// Fragment minimum width\n\t\tminh,\t\t\t// Local minimum height\n\t\tminw,\t\t\t// Local minimum width\n\t\tprefw,\t\t\t// Local preferred width\n\t\tformat_width;\t\t// Working format width for images", "\n DEBUG_printf((\"get_cell_size(%p, %.1f, %.1f, %p, %p, %p)\\n\",\n (void *)t, left, right, (void *)minwidth, (void *)prefwidth, (void *)minheight));", " // First see if the width has been specified for this cell...\n if ((var = htmlGetVariable(t, (uchar *)\"WIDTH\")) != NULL &&\n (var[strlen((char *)var) - 1] != '%' || (right - left) > 0.0f))\n {\n // Yes, use it!\n if (var[strlen((char *)var) - 1] == '%')\n width = (right - left) * atoi((char *)var) * 0.01f;\n else\n width = (float)(atoi((char *)var) * PagePrintWidth / _htmlBrowserWidth);\n }\n else\n width = 0.0f;", " if ((format_width = right - left) <= 0.0f)\n format_width = PagePrintWidth;", " minw = 0.0f;\n prefw = 0.0f;", " // Then the height...\n if ((var = htmlGetVariable(t, (uchar *)\"HEIGHT\")) != NULL)\n {\n // Yes, use it!\n if (var[strlen((char *)var) - 1] == '%')\n minh = PagePrintLength * atoi((char *)var) * 0.01f;\n else\n minh = (float)(atoi((char *)var) * PagePrintWidth / _htmlBrowserWidth);\n }\n else\n minh = 0.0f;", " nowrap = (htmlGetVariable(t, (uchar *)\"NOWRAP\") != NULL);", " DEBUG_printf((\"nowrap = %d\\n\", nowrap));", " for (temp = t->child, frag_width = 0.0f, frag_pref = 0.0f;\n temp != NULL;\n temp = next)\n {\n // Point to next markup, if any...\n next = temp->child;", " switch (temp->markup)\n {\n case MARKUP_TABLE :\n\t // Update widths...\n\t if (frag_pref > prefw)\n\t prefw = frag_pref;", "\t if (frag_width > minw)\n\t {\n\t DEBUG_printf((\"Setting minw to %.1f (was %.1f) for block...\\n\",\n\t \t frag_width, minw));\n\t minw = frag_width;\n\t }", "\t if (nowrap && frag_pref > minw)\n\t {\n\t DEBUG_printf((\"Setting minw to %.1f (was %.1f) for break...\\n\",\n\t \t frag_pref, minw));\n\t minw = frag_pref;\n\t }", " // For nested tables, compute the width of the table.\n frag_width = get_table_size(temp, left, right, &frag_min,\n\t &frag_pref, &frag_height);", "\t if (frag_pref > prefw)\n\t prefw = frag_pref;", "\t if (frag_min > minw)\n\t {\n\t DEBUG_printf((\"Setting minw to %.1f (was %.1f) for nested table...\\n\",\n\t frag_min, minw));\n\t minw = frag_min;\n\t }", "\t frag_width = 0.0f;\n\t frag_pref = 0.0f;\n\t frag_min = 0.0f;\n\t next = NULL;\n\t break;", " case MARKUP_IMG :\n // Update the image width as needed...\n\t if (temp->markup == MARKUP_IMG)\n\t update_image_size(temp);\n case MARKUP_NONE :\n case MARKUP_SPACER :\n frag_height = temp->height;", "#ifdef TABLE_DEBUG2\n if (temp->markup == MARKUP_NONE)\n\t printf(\"FRAG(%s) = %.1f\\n\", temp->data, temp->width);\n\t else if (temp->markup == MARKUP_SPACER)\n\t printf(\"SPACER = %.1f\\n\", temp->width);\n\t else\n\t printf(\"IMG(%s) = %.1f\\n\", htmlGetVariable(temp, (uchar *)\"SRC\"),\n\t temp->width);\n#endif // TABLE_DEBUG2", " // Handle min/preferred widths separately...\n if (temp->width > minw)\n\t {\n\t DEBUG_printf((\"Setting minw to %.1f (was %.1f) for fragment...\\n\",\n\t temp->width, minw));\n\t minw = temp->width;\n\t }", " if (temp->preformatted && temp->data != NULL &&\n temp->data[strlen((char *)temp->data) - 1] == '\\n')\n {\n\t // End of a line - check preferred width...\n\t frag_pref += temp->width + 1;", " if (frag_pref > prefw)\n prefw = frag_pref;", " if (temp->preformatted && frag_pref > minw)\n\t {\n\t DEBUG_printf((\"Setting minw to %.1f (was %.1f) for preformatted...\\n\",\n\t frag_pref, minw));\n minw = frag_pref;\n\t }", "\t frag_pref = 0.0f;\n }\n else if (temp->data != NULL)\n\t frag_pref += temp->width + 1;\n\t else if ((frag_pref + temp->width) > format_width)\n\t {\n\t // parse_paragraph() will force a break\n if (frag_pref > prefw)\n prefw = frag_pref;", "\t frag_pref = temp->width;\n\t }\n\t else\n\t frag_pref += temp->width;", " if (temp->preformatted && temp->data != NULL &&\n temp->data[strlen((char *)temp->data) - 1] == '\\n')\n\t {\n\t // Check required width...\n frag_width += temp->width + 1;", " if (frag_width > minw)\n\t {\n\t DEBUG_printf((\"Setting minw to %.1f (was %.1f) for block...\\n\",\n\t frag_width, minw));\n minw = frag_width;\n\t }", " frag_width = 0.0f;\n\t }\n else if (!temp->preformatted && temp->data != NULL &&\n\t (isspace(temp->data[0]) ||\n\t \t (temp->data[0] && isspace(temp->data[strlen((char *)temp->data) - 1]))))\n\t {\n\t // Check required width...\n\t if (isspace(temp->data[0]))\n\t frag_width = temp->width + 1;\n\t else\n frag_width += temp->width + 1;", " if (frag_width > minw)\n\t {\n\t DEBUG_printf((\"Setting minw to %.1f (was %.1f) for block...\\n\",\n\t frag_width, minw));\n minw = frag_width;\n\t }", "\t if (!isspace(temp->data[0]))\n frag_width = 0.0f;", " DEBUG_printf((\"frag_width=%.1f after whitespace processing...\\n\",\n\t frag_width));\n\t }\n\t else if (temp->data != NULL)\n frag_width += temp->width + 1;\n\t else if ((frag_width + temp->width) > format_width)\n\t // parse_paragraph() will force a break\n\t frag_width = temp->width;\n\t else\n\t frag_width += temp->width;\n\t break;", " case MARKUP_ADDRESS :\n case MARKUP_BLOCKQUOTE :\n case MARKUP_BR :\n case MARKUP_CENTER :\n case MARKUP_DD :\n case MARKUP_DIV :\n case MARKUP_DT :\n case MARKUP_H1 :\n case MARKUP_H2 :\n case MARKUP_H3 :\n case MARKUP_H4 :\n case MARKUP_H5 :\n case MARKUP_H6 :\n case MARKUP_H7 :\n case MARKUP_H8 :\n case MARKUP_H9 :\n case MARKUP_H10 :\n case MARKUP_H11 :\n case MARKUP_H12 :\n case MARKUP_H13 :\n case MARKUP_H14 :\n case MARKUP_H15 :\n case MARKUP_HR :\n case MARKUP_LI :\n case MARKUP_P :\n case MARKUP_PRE :\n DEBUG_printf((\"BREAK at %.1f\\n\", frag_pref));", "\t if (frag_pref > prefw)\n\t prefw = frag_pref;", " if (frag_width > minw)\n\t {\n\t DEBUG_printf((\"Setting minw to %.1f (was %.1f) for block...\\n\",\n\t frag_width, minw));\n minw = frag_width;\n\t }", "\t if (nowrap && frag_pref > minw)\n\t {\n\t DEBUG_printf((\"Setting minw to %.1f (was %.1f) for break...\\n\",\n\t frag_pref, minw));\n\t minw = frag_pref;\n\t }", " frag_pref = 0.0f;\n\t frag_width = 0.0f;", " default :\n frag_height = 0.0f;\n\t break;\n }", " // Update minimum height...\n if (frag_height > minh)\n minh = frag_height;", " // Update next pointer as needed...\n if (next == NULL)\n next = temp->next;", " if (next == NULL)\n {\n // This code is almost funny if you say it fast... :)\n for (next = temp->parent; next != NULL && next != t; next = next->parent)\n\tif (next->next != NULL)\n\t break;", " if (next == t)\n\tnext = NULL;\n else if (next)\n\tnext = next->next;\n }\n }", " // Check the last fragment's width...\n if (frag_pref > prefw)\n prefw = frag_pref;", " if (frag_width > minw)\n {\n DEBUG_printf((\"Setting minw to %.1f (was %.1f) for block...\\n\",\n\t frag_width, minw));\n minw = frag_width;\n }", " // Handle the \"NOWRAP\" option...\n if (nowrap && prefw > minw)\n {\n DEBUG_printf((\"Setting minw to %.1f (was %.1f) for NOWRAP...\\n\",\n\t prefw, minw));\n minw = prefw;\n }", " // Return the required, minimum, and preferred size of the cell...\n *minwidth = minw;\n *prefwidth = prefw;\n *minheight = minh;", " DEBUG_printf((\"get_cell_size(): width=%.1f, minw=%.1f, prefw=%.1f, minh=%.1f\\n\",\n width, minw, prefw, minh));", " return (width);\n}", "\n//\n// 'get_table_size()' - Compute the minimum width of a table.\n//", "static float\t\t\t\t// O - Minimum width of table\nget_table_size(tree_t *t,\t\t// I - Table\n float left,\t\t// I - Left margin\n\t float right,\t\t// I - Right margin\n\t float *minwidth,\t// O - Minimum width\n\t float *prefwidth,\t// O - Preferred width\n\t float *minheight)\t// O - Minimum height\n{\n tree_t\t*temp,\t\t\t// Current tree entry\n\t\t*next;\t\t\t// Next tree entry\n uchar\t\t*var;\t\t\t// Attribute value\n float\t\twidth,\t\t\t// Required width of table\n\t\tminw,\t\t\t// Minimum width of table\n\t\tminh,\t\t\t// Minimum height of table\n\t\tprefw,\t\t\t// Preferred width of table\n\t\tcell_width,\t\t// Cell required width\n\t\tcell_pref,\t\t// Cell preferred width\n\t\tcell_min,\t\t// Cell minimum width\n\t\tcell_height,\t\t// Cell minimum height\n\t\trow_width,\t\t// Row required width\n\t\trow_pref,\t\t// Row preferred width\n\t\trow_min,\t\t// Row minimum width\n\t\trow_height,\t\t// Row minimum height\n\t\tborder,\t\t\t// Border around cells\n\t\tcellpadding,\t\t// Padding inside cells\n\t\tcellspacing;\t\t// Spacing around cells\n int\t\tcolumns,\t\t// Current number of columns\n\t\tmax_columns,\t\t// Maximum columns\n\t\trows;\t\t\t// Number of rows", "\n DEBUG_printf((\"get_table_size(%p, %.1f, %.1f, %p, %p, %p)\\n\",\n (void *)t, left, right, (void *)minwidth, (void *)prefwidth, (void *)minheight));", " // First see if the width has been specified for this table...\n if ((var = htmlGetVariable(t, (uchar *)\"WIDTH\")) != NULL &&\n (var[strlen((char *)var) - 1] != '%' || (right - left) > 0.0f))\n {\n // Yes, use it!\n if (var[strlen((char *)var) - 1] == '%')\n width = (right - left) * atoi((char *)var) * 0.01f;\n else\n width = (float)(atoi((char *)var) * PagePrintWidth / _htmlBrowserWidth);\n }\n else\n width = 0.0f;", " minw = 0.0f;\n prefw = 0.0f;", " // Then the height...\n if ((var = htmlGetVariable(t, (uchar *)\"HEIGHT\")) != NULL)\n {\n // Yes, use it!\n if (var[strlen((char *)var) - 1] == '%')\n minh = PagePrintLength * atoi((char *)var) * 0.01f;\n else\n minh = (float)(atoi((char *)var) * PagePrintWidth / _htmlBrowserWidth);\n }\n else\n minh = 0.0f;", " // Update the size as needed...\n for (temp = t->child, row_width = 0.0f, row_min = 0.0f, row_pref = 0.0f,\n\t row_height = 0.0f, columns = 0, rows = 0, max_columns = 0;\n temp != NULL;\n temp = next)\n {\n // Point to next markup, if any...\n next = temp->child;", " // Start a new row or add the cell width as needed...\n if (temp->markup == MARKUP_TR)\n {\n minh += row_height;", " row_width = 0.0f;\n row_pref = 0.0f;\n row_min = 0.0f;\n row_height = 0.0f;\n rows ++;\n columns = 0;\n }\n else if (temp->markup == MARKUP_TD || temp->markup == MARKUP_TH)\n {\n // Update columns...\n columns ++;\n if (columns > max_columns)\n\tmax_columns = columns;", " // Get widths of cell...\n cell_width = get_cell_size(temp, left, right, &cell_min, &cell_pref,\n &cell_height);", " // Update row widths...\n row_width += cell_width;\n row_pref += cell_pref;\n row_min += cell_min;", " if (cell_height > row_height)\n\trow_height = cell_height;", " // Check current row widths against table...\n if (row_pref > prefw)\n\tprefw = row_pref;", " if (row_min > minw)\n\tminw = row_min;\n }", " // Update next pointer as needed...\n if (next == NULL)\n next = temp->next;", " if (next == NULL)\n {\n // This code is almost funny if you say it fast... :)\n for (next = temp->parent; next != NULL && next != t; next = next->parent)\n\tif (next->next != NULL)\n\t break;", " if (next == t)\n\tnext = NULL;\n else if (next)\n\tnext = next->next;\n }\n }", " // Make sure last row is counted in min height calcs.\n minh += row_height;", " // Add room for spacing and padding...\n if ((var = htmlGetVariable(t, (uchar *)\"CELLPADDING\")) != NULL)\n cellpadding = atoi((char *)var);\n else\n cellpadding = 1.0f;", " if ((var = htmlGetVariable(t, (uchar *)\"CELLSPACING\")) != NULL)\n cellspacing = atoi((char *)var);\n else\n cellspacing = 0.0f;", " if ((var = htmlGetVariable(t, (uchar *)\"BORDER\")) != NULL)\n {\n if ((border = (float)atof((char *)var)) == 0.0 && var[0] != '0')\n border = 1.0f;", " cellpadding += border;\n }\n else\n border = 0.0f;", " if (border == 0.0f && cellpadding > 0.0f)\n {\n /*\n * Ah, the strange table formatting nightmare that is HTML.\n * Netscape and MSIE assign an invisible border width of 1\n * pixel if no border is specified...\n */", " cellpadding += 1.0f;\n }", " cellspacing *= PagePrintWidth / _htmlBrowserWidth;\n cellpadding *= PagePrintWidth / _htmlBrowserWidth;", " DEBUG_printf((\"ADDING %.1f for table space for %d columns...\\n\",\n max_columns * (2 * cellpadding + cellspacing) - cellspacing,\n\t\tmax_columns));", " if (width > 0.0f)\n width += max_columns * (2 * cellpadding + cellspacing) - cellspacing;", " minw += max_columns * (2 * cellpadding + cellspacing) - cellspacing;\n prefw += max_columns * (2 * cellpadding + cellspacing) - cellspacing;\n minh += rows * (2 * cellpadding + cellspacing) - cellspacing;", " // Return the required, minimum, and preferred size of the table...\n *minwidth = minw;\n *prefwidth = prefw;\n *minheight = minh;", " DEBUG_printf((\"get_table_size(): width=%.1f, minw=%.1f, prefw=%.1f, minh=%.1f\\n\",\n width, minw, prefw, minh));", " return (width);\n}", "#ifdef TABLE_DEBUG\n# undef DEBUG_printf\n# undef DEBUG_puts\n# define DEBUG_printf(x)\n# define DEBUG_puts(x)\n#endif /* TABLE_DEBUG */", "\n/*\n * 'flatten_tree()' - Flatten an HTML tree to only include the text, image,\n * link, and break markups.\n */", "static tree_t *\t\t\t/* O - Flattened markup tree */\nflatten_tree(tree_t *t)\t\t/* I - Markup tree to flatten */\n{\n tree_t\t*temp,\t\t/* New tree node */\n\t\t*flat;\t\t/* Flattened tree */", "\n flat = NULL;", " while (t != NULL)\n {\n switch (t->markup)\n {\n case MARKUP_NONE :\n if (t->data == NULL)\n\t break;\n case MARKUP_COMMENT :\n case MARKUP_BR :\n case MARKUP_SPACER :\n case MARKUP_IMG :\n\t temp = (tree_t *)calloc(sizeof(tree_t), 1);\n\t memcpy(temp, t, sizeof(tree_t));\n\t temp->parent = NULL;\n\t temp->child = NULL;\n\t temp->prev = flat;\n\t temp->next = NULL;\n\t if (flat != NULL)\n flat->next = temp;\n flat = temp;", " if (temp->markup == MARKUP_IMG)\n update_image_size(temp);\n break;", " case MARKUP_A :\n if (htmlGetVariable(t, (uchar *)\"NAME\") != NULL)\n {\n\t temp = (tree_t *)calloc(sizeof(tree_t), 1);\n\t memcpy(temp, t, sizeof(tree_t));\n\t temp->parent = NULL;\n\t temp->child = NULL;\n\t temp->prev = flat;\n\t temp->next = NULL;\n\t if (flat != NULL)\n flat->next = temp;\n flat = temp;\n }\n\t break;", " case MARKUP_P :\n case MARKUP_PRE :\n case MARKUP_H1 :\n case MARKUP_H2 :\n case MARKUP_H3 :\n case MARKUP_H4 :\n case MARKUP_H5 :\n case MARKUP_H6 :\n case MARKUP_H7 :\n case MARKUP_H8 :\n case MARKUP_H9 :\n case MARKUP_H10 :\n case MARKUP_H11 :\n case MARKUP_H12 :\n case MARKUP_H13 :\n case MARKUP_H14 :\n case MARKUP_H15 :\n case MARKUP_UL :\n case MARKUP_DIR :\n case MARKUP_MENU :\n case MARKUP_OL :\n case MARKUP_DL :\n case MARKUP_LI :\n case MARKUP_DD :\n case MARKUP_DT :\n case MARKUP_TR :\n case MARKUP_CAPTION :\n\t temp = (tree_t *)calloc(sizeof(tree_t), 1);\n\t temp->markup = MARKUP_BR;\n\t temp->parent = NULL;\n\t temp->child = NULL;\n\t temp->prev = flat;\n\t temp->next = NULL;\n\t if (flat != NULL)\n flat->next = temp;\n flat = temp;\n break;", " default :\n break;\n }", " if (t->child != NULL && t->markup != MARKUP_UNKNOWN)\n {\n temp = flatten_tree(t->child);", " if (temp != NULL)\n temp->prev = flat;\n if (flat != NULL)\n flat->next = temp;\n else\n flat = temp;\n }", " if (flat != NULL)\n while (flat->next != NULL)\n flat = flat->next;", " t = t->next;\n }", " if (flat == NULL)\n return (NULL);", " while (flat->prev != NULL)\n flat = flat->prev;", " return (flat);\n}", "\n/*\n * 'update_image_size()' - Update the size of an image based upon the\n * printable width.\n */", "static void\nupdate_image_size(tree_t *t)\t/* I - Tree entry */\n{\n image_t\t*img;\t\t/* Image file */\n uchar\t\t*width,\t\t/* Width string */\n\t\t*height;\t/* Height string */", "\n width = htmlGetVariable(t, (uchar *)\"WIDTH\");\n height = htmlGetVariable(t, (uchar *)\"HEIGHT\");", " if (width != NULL && height != NULL)\n {\n if (width[strlen((char *)width) - 1] == '%')\n t->width = (float)(atof((char *)width) * PagePrintWidth / 100.0f);\n else\n t->width = (float)(atoi((char *)width) * PagePrintWidth / _htmlBrowserWidth);", " if (height[strlen((char *)height) - 1] == '%')\n t->height = (float)(atof((char *)height) * PagePrintWidth / 100.0f);\n else\n t->height = (float)(atoi((char *)height) * PagePrintWidth / _htmlBrowserWidth);", " return;\n }", " img = image_find((char *)htmlGetVariable(t, (uchar *)\"REALSRC\"));", " if (img == NULL)\n return;", " if (width != NULL)\n {\n if (width[strlen((char *)width) - 1] == '%')\n t->width = (float)(atof((char *)width) * PagePrintWidth / 100.0f);\n else\n t->width = (float)(atoi((char *)width) * PagePrintWidth / _htmlBrowserWidth);", " t->height = t->width * img->height / img->width;\n }\n else if (height != NULL)\n {\n if (height[strlen((char *)height) - 1] == '%')\n t->height = (float)(atof((char *)height) * PagePrintWidth / 100.0f);\n else\n t->height = (float)(atoi((char *)height) * PagePrintWidth / _htmlBrowserWidth);", " t->width = t->height * img->width / img->height;\n }\n else\n {\n t->width = (float)(img->width * PagePrintWidth / _htmlBrowserWidth);\n t->height = (float)(img->height * PagePrintWidth / _htmlBrowserWidth);\n }\n}", "\n/*\n * 'get_width()' - Get the width of a string in points.\n */", "static float\t\t\t/* O - Width in points */\nget_width(uchar *s,\t\t/* I - String to scan */\n int typeface,\t/* I - Typeface code */\n int style,\t\t/* I - Style code */\n int size)\t\t/* I - Size */\n{\n uchar\t*ptr;\t\t\t/* Current character */\n int\twidth;\t\t\t/* Current width */", "\n DEBUG_printf((\"get_width(\\\"%s\\\", %d, %d, %d)\\n\",\n s == NULL ? \"(null)\" : (const char *)s,\n typeface, style, size));", " if (s == NULL)\n return (0.0);", " if (!_htmlWidthsLoaded[typeface][style])\n htmlLoadFontWidths(typeface, style);", " for (width = 0, ptr = s; *ptr != '\\0'; ptr ++)\n width += _htmlWidths[typeface][style][*ptr];", " return (width * _htmlSizes[size] * 0.001f);\n}", "\n/*\n * 'get_title()' - Get the title string for a document.\n */", "static uchar *\t\t/* O - Title string */\nget_title(tree_t *doc)\t/* I - Document */\n{\n uchar\t*temp;", "\n while (doc != NULL)\n {\n if (doc->markup == MARKUP_TITLE)\n return (htmlGetText(doc->child));\n else if (doc->child != NULL)\n if ((temp = get_title(doc->child)) != NULL)\n return (temp);\n doc = doc->next;\n }", " return (NULL);\n}", "\n/*\n * 'open_file()' - Open an output file for the current chapter.\n */", "static FILE *\t\t/* O - File pointer */\nopen_file(void)\n{\n char\tfilename[255];\t/* Filename */", "\n if (OutputFiles && PSLevel > 0)\n {\n if (chapter == -1)\n snprintf(filename, sizeof(filename), \"%s/cover.ps\", OutputPath);\n else if (chapter == 0)\n snprintf(filename, sizeof(filename), \"%s/contents.ps\", OutputPath);\n else\n snprintf(filename, sizeof(filename), \"%s/doc%d.ps\", OutputPath, chapter);", " return (fopen(filename, \"wb+\"));\n }\n else if (OutputFiles)\n {\n snprintf(filename, sizeof(filename), \"%s/doc.pdf\", OutputPath);", " return (fopen(filename, \"wb+\"));\n }\n else if (OutputPath[0] != '\\0')\n return (fopen(OutputPath, \"wb+\"));\n else if (PSLevel == 0)\n return (file_temp(stdout_filename, sizeof(stdout_filename)));\n else\n return (stdout);\n}", "\n/*\n * 'set_color()' - Set the current text color...\n */", "static void\nset_color(FILE *out,\t/* I - File to write to */\n float *rgb)\t/* I - RGB color */\n{\n if (rgb[0] == render_rgb[0] &&\n rgb[1] == render_rgb[1] &&\n rgb[2] == render_rgb[2])\n return;", " render_rgb[0] = rgb[0];\n render_rgb[1] = rgb[1];\n render_rgb[2] = rgb[2];", " if (OutputColor)\n {\n // Output RGB color...\n if (PSLevel > 0)\n fprintf(out, \"%.2f %.2f %.2f C \", rgb[0], rgb[1], rgb[2]);\n else\n flate_printf(out, \"%.2f %.2f %.2f rg \", rgb[0], rgb[1], rgb[2]);\n }\n else\n {\n // Output grayscale...\n if (PSLevel > 0)\n fprintf(out, \"%.2f G \",\n rgb[0] * 0.31f + rgb[1] * 0.61f + rgb[2] * 0.08f);\n else\n flate_printf(out, \"%.2f g \",\n rgb[0] * 0.31f + rgb[1] * 0.61f + rgb[2] * 0.08f);\n }\n}", "\n/*\n * 'set_font()' - Set the current text font.\n */", "static void\nset_font(FILE *out,\t\t\t/* I - File to write to */\n int typeface,\t\t/* I - Typeface code */\n int style,\t\t\t/* I - Style code */\n float size)\t\t\t/* I - Size */\n{\n char\tsizes[255],\t/* Formatted string for size... */\n\t*s;\t\t/* Pointer to end of string */", "\n if (typeface == render_typeface &&\n style == render_style &&\n size == render_size)\n return;", " /*\n * Format size and strip trailing 0's and decimals...\n */", " snprintf(sizes, sizeof(sizes), \"%.1f\", size);", " for (s = sizes + strlen(sizes) - 1; s > sizes && *s == '0'; s --)\n *s = '\\0';", " if (*s == '.')\n *s = '\\0';", " /*\n * Set the new typeface, style, and size.\n */", " if (PSLevel > 0)\n {\n if (size != render_size)\n fprintf(out, \"%s FS\", sizes);", " fprintf(out, \"/F%x SF \", typeface * 4 + style);\n }\n else\n flate_printf(out, \"/F%x %s Tf \", typeface * 4 + style, sizes);", " render_typeface = typeface;\n render_style = style;\n render_size = size;\n}", "\n/*\n * 'set_pos()' - Set the current text position.\n */", "static void\nset_pos(FILE *out,\t\t\t/* I - File to write to */\n float x,\t\t\t/* I - X position */\n float y)\t\t\t/* I - Y position */\n{\n char\txs[255],\t\t\t/* Formatted string for X... */\n\tys[255],\t\t\t/* Formatted string for Y... */\n\t*s;\t\t\t\t/* Pointer to end of string */", "\n if (fabs(render_x - x) < 0.1 && fabs(render_y - y) < 0.1)\n return;", " /*\n * Format X and Y...\n */", " if (PSLevel > 0 || render_x == -1.0)\n {\n snprintf(xs, sizeof(xs), \"%.3f\", x);\n snprintf(ys, sizeof(ys), \"%.3f\", y);\n }\n else\n {\n snprintf(xs, sizeof(xs), \"%.3f\", x - render_startx);\n snprintf(ys, sizeof(ys), \"%.3f\", y - render_y);\n }", " /*\n * Strip trailing 0's and decimals...\n */", " for (s = xs + strlen(xs) - 1; s > xs && *s == '0'; s --)\n *s = '\\0';", " if (*s == '.')\n *s = '\\0';", " for (s = ys + strlen(ys) - 1; s > ys && *s == '0'; s --)\n *s = '\\0';", " if (*s == '.')\n *s = '\\0';", " if (PSLevel > 0)\n fprintf(out, \"%s %s M\", xs, ys);\n else\n flate_printf(out, \"%s %s Td\", xs, ys);", " render_x = render_startx = x;\n render_y = y;\n}", "\n/*\n * 'ps_hex()' - Print binary data as a series of hexadecimal numbers.\n */", "static void\nps_hex(FILE *out,\t\t\t/* I - File to print to */\n uchar *data,\t\t\t/* I - Data to print */\n int length)\t\t\t/* I - Number of bytes to print */\n{\n int\t\tcol;\n static const char *hex = \"0123456789ABCDEF\";", "\n col = 0;\n while (length > 0)\n {\n /*\n * Put the hex uchars out to the file; note that we don't use fprintf()\n * for speed reasons...\n */", " putc(hex[*data >> 4], out);\n putc(hex[*data & 15], out);", " data ++;\n length --;", " col = (col + 1) % 40;\n if (col == 0)\n putc('\\n', out);\n }", " if (col > 0)\n putc('\\n', out);\n}", "", "#ifdef HTMLDOC_ASCII85\n/*\n * 'ps_ascii85()' - Print binary data as a series of base-85 numbers.\n */", "static void\nps_ascii85(FILE *out,\t\t\t/* I - File to print to */\n\t uchar *data,\t\t\t/* I - Data to print */\n\t int length,\t\t/* I - Number of bytes to print */\n\t int eod)\t\t\t/* I - 1 = end-of-data */\n{\n unsigned\tb = 0;\t\t\t/* Current 32-bit word */\n uchar\t\tc[5];\t\t\t/* Base-85 encoded characters */\n static int\tcol = 0;\t\t/* Column */\n static uchar\tleftdata[4];\t\t/* Leftover data at the end */\n static int\tleftcount = 0;\t\t/* Size of leftover data */", "\n length += leftcount;", " while (length > 3)\n {\n switch (leftcount)\n {\n case 0 :\n b = (unsigned)((((((data[0] << 8) | data[1]) << 8) | data[2]) << 8) | data[3]);\n\t break;\n case 1 :\n b = (unsigned)((((((leftdata[0] << 8) | data[0]) << 8) | data[1]) << 8) | data[2]);\n\t break;\n case 2 :\n b = (unsigned)((((((leftdata[0] << 8) | leftdata[1]) << 8) | data[0]) << 8) | data[1]);\n\t break;\n case 3 :\n b = (unsigned)((((((leftdata[0] << 8) | leftdata[1]) << 8) | leftdata[2]) << 8) | data[0]);\n\t break;\n }", " if (col >= 76)\n {\n col = 0;\n putc('\\n', out);\n }", " if (b == 0)\n {\n putc('z', out);\n col ++;\n }\n else\n {\n c[4] = (b % 85) + '!';\n b /= 85;\n c[3] = (b % 85) + '!';\n b /= 85;\n c[2] = (b % 85) + '!';\n b /= 85;\n c[1] = (b % 85) + '!';\n b /= 85;\n c[0] = (uchar)(b + '!');", " fwrite(c, 1, 5, out);\n col += 5;\n }", " data += 4 - leftcount;\n length -= 4 - leftcount;\n leftcount = 0;\n }", " if (length > 0)\n {\n // Copy any remainder into the leftdata array...\n if ((length - leftcount) > 0)\n memcpy(leftdata + leftcount, data, (size_t)(length - leftcount));", " memset(leftdata + length, 0, (size_t)(4 - length));", " leftcount = length;\n }", " if (eod)\n {\n // Do the end-of-data dance...\n if (col >= 76)\n {\n col = 0;\n putc('\\n', out);\n }", " if (leftcount > 0)\n {\n // Write the remaining bytes as needed...\n b = (unsigned)((((((leftdata[0] << 8) | leftdata[1]) << 8) | leftdata[2]) << 8) | leftdata[3]);", " c[4] = (b % 85) + '!';\n b /= 85;\n c[3] = (b % 85) + '!';\n b /= 85;\n c[2] = (b % 85) + '!';\n b /= 85;\n c[1] = (b % 85) + '!';\n b /= 85;\n c[0] = (uchar)(b + '!');", " fwrite(c, (size_t)(leftcount + 1), 1, out);", " leftcount = 0;\n }", " fputs(\"~>\\n\", out);\n col = 0;\n }\n}\n#endif // HTMLDOC_ASCII85", "\n/*\n * JPEG library destination data manager. These routines direct\n * compressed data from libjpeg into the PDF or PostScript file.\n */", "static FILE\t\t\t*jpg_file;\t/* JPEG file */\nstatic uchar\t\t\tjpg_buf[8192];\t/* JPEG buffer */\nstatic jpeg_destination_mgr\tjpg_dest;\t/* JPEG destination manager */\nstatic struct jpeg_error_mgr\tjerr;\t\t/* JPEG error handler */", "\n/*\n * 'jpg_init()' - Initialize the JPEG destination.\n */", "static void\njpg_init(j_compress_ptr cinfo)\t\t/* I - Compressor info */\n{\n (void)cinfo;", " jpg_dest.next_output_byte = jpg_buf;\n jpg_dest.free_in_buffer = sizeof(jpg_buf);\n}", "\n/*\n * 'jpg_empty()' - Empty the JPEG output buffer.\n */", "static boolean\t\t\t\t/* O - True if buffer written OK */\njpg_empty(j_compress_ptr cinfo)\t\t/* I - Compressor info */\n{\n (void)cinfo;", " if (PSLevel > 0)\n#ifdef HTMLDOC_ASCII85\n ps_ascii85(jpg_file, jpg_buf, sizeof(jpg_buf));\n#else\n ps_hex(jpg_file, jpg_buf, sizeof(jpg_buf));\n#endif // HTMLDOC_ASCII85\n else\n flate_write(jpg_file, jpg_buf, sizeof(jpg_buf));", " jpg_dest.next_output_byte = jpg_buf;\n jpg_dest.free_in_buffer = sizeof(jpg_buf);", " return (TRUE);\n}", "\n/*\n * 'jpg_term()' - Write the last JPEG data to the file.\n */", "static void\njpg_term(j_compress_ptr cinfo)\t\t/* I - Compressor info */\n{\n int nbytes;\t\t\t\t/* Number of bytes to write */", "\n (void)cinfo;", " nbytes = sizeof(jpg_buf) - jpg_dest.free_in_buffer;", " if (PSLevel > 0)\n#ifdef HTMLDOC_ASCII85\n ps_ascii85(jpg_file, jpg_buf, nbytes);\n#else\n ps_hex(jpg_file, jpg_buf, nbytes);\n#endif // HTMLDOC_ASCII85\n else\n flate_write(jpg_file, jpg_buf, nbytes);\n}", "\n/*\n * 'jpg_setup()' - Setup the JPEG compressor for writing an image.\n */", "static void\njpg_setup(FILE *out,\t/* I - Output file */\n image_t *img,\t/* I - Output image */\n j_compress_ptr cinfo)\t/* I - Compressor info */\n{\n int\ti;\t\t\t// Looping var", "\n jpg_file = out;\n cinfo->err = jpeg_std_error(&jerr);", " jpeg_create_compress(cinfo);", " cinfo->dest = &jpg_dest;\n jpg_dest.init_destination = jpg_init;\n jpg_dest.empty_output_buffer = jpg_empty;\n jpg_dest.term_destination = jpg_term;", " cinfo->image_width = (JDIMENSION)img->width;\n cinfo->image_height = (JDIMENSION)img->height;\n cinfo->input_components = img->depth;\n cinfo->in_color_space = img->depth == 1 ? JCS_GRAYSCALE : JCS_RGB;", " jpeg_set_defaults(cinfo);\n jpeg_set_quality(cinfo, OutputJPEG, TRUE);", " // Update things when writing to PS files...\n if (PSLevel)\n {\n // Adobe uses sampling == 1\n for (i = 0; i < img->depth; i ++)\n {\n cinfo->comp_info[i].h_samp_factor = 1;\n cinfo->comp_info[i].v_samp_factor = 1;\n }\n }", " cinfo->write_JFIF_header = FALSE;\n cinfo->write_Adobe_marker = TRUE;", " jpeg_start_compress(cinfo, TRUE);\n}", "\n/*\n * 'compare_rgb()' - Compare two RGB colors...\n */", "static int\t\t\t\t/* O - -1 if rgb1<rgb2, etc. */\ncompare_rgb(unsigned *rgb1,\t\t/* I - First color */\n unsigned *rgb2)\t\t/* I - Second color */\n{\n return ((int)*rgb1 - (int)*rgb2);\n}", "\n/*\n * 'write_image()' - Write an image to the given output file...\n */", "static void\nwrite_image(FILE *out,\t\t/* I - Output file */\n render_t *r,\t\t/* I - Image to write */\n\t int write_obj)\t\t/* I - Write an object? */\n{\n int\t\ti, j, k, m,\t\t/* Looping vars */\n\t\tncolors;\t\t/* Number of colors */\n uchar\t\t*pixel,\t\t\t/* Current pixel */\n\t\t*indices,\t\t/* New indexed pixel array */\n\t\t*indptr;\t\t/* Current index */\n int\t\tindwidth,\t\t/* Width of indexed line */\n\t\tindbits;\t\t/* Bits per index */\n int\t\tmax_colors;\t\t/* Max colors to use */\n unsigned\tcolors[256],\t\t/* Colormap values */\n\t\tkey,\t\t\t/* Color key */\n\t\t*match;\t\t\t/* Matching color value */\n uchar\t\tgrays[256],\t\t/* Grayscale usage */\n\t\tcmap[256][3];\t\t/* Colormap */\n image_t \t*img;\t\t\t/* Image */\n struct jpeg_compress_struct cinfo;\t/* JPEG compressor */\n uchar\t\t*data,\t\t\t/* PS Level 3 image data */\n\t\t*dataptr,\t\t/* Pointer into image data */\n\t\t*maskptr;\t\t/* Pointer into mask data */", "\n /*\n * See if we can optimize the image as indexed without color loss...\n */", " img = r->data.image;\n ncolors = 0;\n indices = NULL;\n indwidth = 0;", " if (!img->pixels && !img->obj)\n image_load(img->filename, !OutputColor, 1);", " // Note: Acrobat 6 tries to decrypt the colormap of indexed in-line images twice, which\n // is 1) not consistent with prior Acrobat releases and 2) in violation of their\n // PDF spec. The \"img->use > 1 || !Encryption\" test prevents the use of indexed\n // in-line images when encryption is enabled.\n //\n // We are filing a bug on this with Adobe, but if history is any indicator, we are\n // stuck with this workaround forever...\n if (PSLevel != 1 && PDFVersion >= 12 && img->obj == 0 && (img->use > 1 || !Encryption))\n {\n if (img->depth == 1)\n {\n /*\n * Greyscale image...\n */", " memset(grays, 0, sizeof(grays));", " for (i = img->width * img->height, pixel = img->pixels;\n\t i > 0;\n\t i --, pixel ++)\n\tif (!grays[*pixel])\n\t{\n if (ncolors >= 16)\n\t break;", "\t grays[*pixel] = 1;\n\t ncolors ++;\n\t}", " if (i == 0)\n {\n\tfor (i = 0, j = 0; i < 256; i ++)\n\t if (grays[i])\n\t {\n\t colors[j] = (unsigned)((((i << 8) | i) << 8) | i);\n\t grays[i] = (uchar)j;\n\t j ++;\n\t }\n }\n else\n ncolors = 0;\n }\n else\n {\n /*\n * Color image...\n */", " if (OutputJPEG && !Compression)\n max_colors = 16;\n else\n max_colors = 256;", " for (i = img->width * img->height, pixel = img->pixels, match = NULL;\n\t i > 0;\n\t i --, pixel += 3)\n {\n key = (unsigned)((((pixel[0] << 8) | pixel[1]) << 8) | pixel[2]);", "\tif (!match || *match != key)\n\t{\n if (ncolors > 0)\n match = (unsigned *)bsearch(&key, colors, (size_t)ncolors, sizeof(unsigned), (compare_func_t)compare_rgb);\n else\n match = NULL;\n }", " if (match == NULL)\n {\n if (ncolors >= max_colors)\n break;", " colors[ncolors] = key;\n ncolors ++;", " if (ncolors > 1)\n qsort(colors, (size_t)ncolors, sizeof(unsigned), (compare_func_t)compare_rgb);\n }\n }", " if (i > 0)\n ncolors = 0;\n }\n }", " if (ncolors > 0)\n {\n if (PSLevel == 3 && img->mask)\n indbits = 8;\n else if (ncolors <= 2)\n indbits = 1;\n else if (ncolors <= 4)\n indbits = 2;\n else if (ncolors <= 16)\n indbits = 4;\n else\n indbits = 8;", " indwidth = (img->width * indbits + 7) / 8;\n indices = (uchar *)calloc((size_t)indwidth, (size_t)(img->height + 1));\n\t\t\t\t\t// height + 1 for PS odd-row-count bug", " if (img->depth == 1)\n {\n /*\n * Convert a grayscale image...\n */", " switch (indbits)\n {\n case 1 :\n\t for (i = img->height, pixel = img->pixels, indptr = indices;\n\t\t i > 0;\n\t\t i --)\n\t {\n\t for (j = img->width, k = 7; j > 0; j --, k = (k + 7) & 7, pixel ++)\n\t\tswitch (k)\n\t\t{\n\t\t case 7 :\n\t *indptr = (uchar)(grays[*pixel] << 7);\n\t\t break;\n\t\t default :\n\t *indptr |= (uchar)(grays[*pixel] << k);\n\t\t break;\n\t\t case 0 :\n\t *indptr++ |= (uchar)grays[*pixel];\n\t\t break;\n \t}", "\t if (k != 7)\n\t\tindptr ++;\n\t }\n\t break;", " case 2 :\n\t for (i = img->height, pixel = img->pixels, indptr = indices;\n\t\t i > 0;\n\t\t i --)\n\t {\n\t for (j = img->width, k = 0; j > 0; j --, k = (k + 1) & 3, pixel ++)\n\t\tswitch (k)\n\t\t{\n\t\t case 0 :\n\t *indptr = (uchar)(grays[*pixel] << 6);\n\t\t break;\n\t\t case 1 :\n\t *indptr |= (uchar)(grays[*pixel] << 4);\n\t\t break;\n\t\t case 2 :\n\t *indptr |= (uchar)(grays[*pixel] << 2);\n\t\t break;\n\t\t case 3 :\n\t *indptr++ |= (uchar)grays[*pixel];\n\t\t break;\n \t}", "\t if (k)\n\t\tindptr ++;\n\t }\n\t break;", " case 4 :\n\t for (i = img->height, pixel = img->pixels, indptr = indices;\n\t\t i > 0;\n\t\t i --)\n\t {\n\t for (j = img->width, k = 0; j > 0; j --, k ^= 1, pixel ++)\n\t\tif (k)\n\t\t *indptr++ |= grays[*pixel];\n\t\telse\n\t\t *indptr = (uchar)(grays[*pixel] << 4);", "\t if (k)\n\t\tindptr ++;\n\t }\n\t break;\n }\n }\n else\n {\n /*\n * Convert a color image...\n */", " switch (indbits)\n {\n case 1 :\n\t for (i = img->height, pixel = img->pixels, indptr = indices,\n\t match = colors;\n\t\t i > 0;\n\t\t i --)\n\t {\n\t for (j = img->width, k = 7;\n\t j > 0;\n\t\t j --, k = (k + 7) & 7, pixel += 3)\n\t {\n key = (unsigned)((((pixel[0] << 8) | pixel[1]) << 8) | pixel[2]);", "\t\tif (*match != key)\n \t match = (unsigned *)bsearch(&key, colors, (size_t)ncolors, sizeof(unsigned), (compare_func_t)compare_rgb);\n\t m = match - colors;", "\t\tswitch (k)\n\t\t{\n\t\t case 7 :\n\t *indptr = (uchar)(m << 7);\n\t\t break;\n\t\t default :\n\t *indptr |= (uchar)(m << k);\n\t\t break;\n\t\t case 0 :\n\t *indptr++ |= (uchar)m;\n\t\t break;\n \t}\n\t }", "\t if (k != 7)\n\t indptr ++;\n\t }\n\t break;", " case 2 :\n\t for (i = img->height, pixel = img->pixels, indptr = indices,\n\t match = colors;\n\t\t i > 0;\n\t\t i --)\n\t {\n\t for (j = img->width, k = 0;\n\t j > 0;\n\t\t j --, k = (k + 1) & 3, pixel += 3)\n\t {\n key = (unsigned)((((pixel[0] << 8) | pixel[1]) << 8) | pixel[2]);", "\t\tif (*match != key)\n \t match = (unsigned *)bsearch(&key, colors, (size_t)ncolors, sizeof(unsigned), (compare_func_t)compare_rgb);\n\t m = match - colors;", "\t\tswitch (k)\n\t\t{\n\t\t case 0 :\n\t *indptr = (uchar)(m << 6);\n\t\t break;\n\t\t case 1 :\n\t *indptr |= (uchar)(m << 4);\n\t\t break;\n\t\t case 2 :\n\t *indptr |= (uchar)(m << 2);\n\t\t break;\n\t\t case 3 :\n\t *indptr++ |= (uchar)m;\n\t\t break;\n \t}\n\t }", "\t if (k)\n\t indptr ++;\n\t }\n\t break;", " case 4 :\n\t for (i = img->height, pixel = img->pixels, indptr = indices,\n\t match = colors;\n\t\t i > 0;\n\t\t i --)\n\t {\n\t for (j = img->width, k = 0; j > 0; j --, k ^= 1, pixel += 3)\n\t {\n key = (unsigned)((((pixel[0] << 8) | pixel[1]) << 8) | pixel[2]);", "\t\tif (*match != key)\n \t match = (unsigned *)bsearch(&key, colors, (size_t)ncolors, sizeof(unsigned), (compare_func_t)compare_rgb);\n\t m = match - colors;", "\t\tif (k)\n\t\t *indptr++ |= (uchar)m;\n\t\telse\n\t\t *indptr = (uchar)(m << 4);\n\t }", "\t if (k)\n\t indptr ++;\n\t }\n\t break;", " case 8 :\n\t for (i = img->height, pixel = img->pixels, indptr = indices,\n\t match = colors;\n\t\t i > 0;\n\t\t i --)\n\t {\n\t for (j = img->width; j > 0; j --, pixel += 3, indptr ++)\n\t {\n key = (unsigned)((((pixel[0] << 8) | pixel[1]) << 8) | pixel[2]);", "\t\tif (*match != key)\n \t match = (unsigned *)bsearch(&key, colors, (size_t)ncolors, sizeof(unsigned), (compare_func_t)compare_rgb);\n\t *indptr = (uchar)(match - colors);\n\t }\n\t }\n\t break;\n }\n }\n }\n else\n indbits = 8;", " if (ncolors == 1)\n {\n /*\n * Adobe doesn't like 1 color images...\n */", " ncolors = 2;\n colors[1] = 0;\n }", " /*\n * Now write the image...\n */", " switch (PSLevel)\n {\n case 0 : /* PDF */\n if (!write_obj)\n\t flate_printf(out, \"q %.1f 0 0 %.1f %.1f %.1f cm\\n\", r->width, r->height,\n\t r->x, r->y);", " if (img->obj)\n\t{\n\t if (img->mask && PDFVersion < 13)\n\t write_imagemask(out, r);", "\t flate_printf(out, \"/I%d Do Q\\n\", img->obj);\n\t break;\n\t}", " if (img->mask && write_obj && PDFVersion >= 13)\n\t{\n\t // We have a mask image, write it!\n pdf_start_object(out);\n\t fputs(\"/Type/XObject/Subtype/Image\", out);\n fputs(\"/ColorSpace/DeviceGray\", out);\n\t if (img->maskscale == 8)\n\t fprintf(out, \"/Width %d/Height %d/BitsPerComponent 8\",\n\t img->width, img->height);\n else\n\t fprintf(out, \"/Width %d/Height %d/BitsPerComponent 1/ImageMask true\",\n\t img->width * img->maskscale, img->height * img->maskscale);\n if (Compression)\n fputs(\"/Filter/FlateDecode\", out);", " pdf_start_stream(out);\n flate_open_stream(out);\n\t if (img->maskscale == 8)\n \t flate_write(out, img->mask, img->width * img->height);\n\t else\n \t flate_write(out, img->mask,\n\t img->maskwidth * img->height * img->maskscale);\n\t flate_close_stream(out);", " pdf_end_object(out);\n\t}", " if (write_obj)\n\t{\n\t // Write an image object...\n\t img->obj = pdf_start_object(out);", "\t fputs(\"/Type/XObject/Subtype/Image\", out);\n\t if (img->mask && PDFVersion >= 13)\n\t {\n\t if (img->maskscale == 8)\n\t fprintf(out, \"/SMask %d 0 R\", img->obj - 1);\n\t else\n\t fprintf(out, \"/Mask %d 0 R\", img->obj - 1);\n\t }", "\t if (ncolors > 0)\n\t {\n\t for (i = 0; i < ncolors; i ++)\n\t {\n\t cmap[i][0] = (uchar)(colors[i] >> 16);\n\t cmap[i][1] = (uchar)(colors[i] >> 8);\n\t cmap[i][2] = (uchar)colors[i];\n\t }", "\t if (Encryption)\n\t {\n\t // Encrypt the colormap...\n\t encrypt_init();\n\t rc4_encrypt(&encrypt_state, cmap[0], cmap[0], (unsigned)(ncolors * 3));\n\t }", "\t fprintf(out, \"/ColorSpace[/Indexed/DeviceRGB %d<\", ncolors - 1);\n\t for (i = 0; i < ncolors; i ++)\n\t fprintf(out, \"%02X%02X%02X\", cmap[i][0], cmap[i][1],\n\t cmap[i][2]);\n\t fputs(\">]\", out);\n }\n\t else if (img->depth == 1)\n fputs(\"/ColorSpace/DeviceGray\", out);\n else\n fputs(\"/ColorSpace/DeviceRGB\", out);", "#ifdef HTMLDOC_INTERPOLATION\n if (ncolors != 2)\n fputs(\"/Interpolate true\", out);\n#endif // HTMLDOC_INTERPOLATION", " if (Compression && (ncolors || !OutputJPEG))\n fputs(\"/Filter/FlateDecode\", out);\n\t else if (OutputJPEG && ncolors == 0)\n\t {\n\t if (Compression)\n\t fputs(\"/Filter[/FlateDecode/DCTDecode]\", out);\n\t else\n\t fputs(\"/Filter/DCTDecode\", out);\n\t }", " \t fprintf(out, \"/Width %d/Height %d/BitsPerComponent %d\",\n\t img->width, img->height, indbits);\n pdf_start_stream(out);\n flate_open_stream(out);", " if (OutputJPEG && ncolors == 0)\n\t {\n\t jpg_setup(out, img, &cinfo);", "\t for (i = img->height, pixel = img->pixels;\n\t i > 0;\n\t i --, pixel += img->width * img->depth)\n\t jpeg_write_scanlines(&cinfo, &pixel, 1);", "\t jpeg_finish_compress(&cinfo);\n\t jpeg_destroy_compress(&cinfo);\n\t }\n else\n\t {\n\t if (ncolors > 0)\n \t flate_write(out, indices, indwidth * img->height);\n\t else\n \t flate_write(out, img->pixels,\n\t img->width * img->height * img->depth);\n }", " flate_close_stream(out);\n pdf_end_object(out);\n\t}\n\telse\n\t{\n\t // Put the image in-line...\n flate_puts(\"BI\", out);", "\t if (ncolors > 0)\n\t {\n\t flate_printf(out, \"/CS[/I/RGB %d<\", ncolors - 1);\n\t for (i = 0; i < ncolors; i ++)\n\t flate_printf(out, \"%02X%02X%02X\", colors[i] >> 16,\n\t \t (colors[i] >> 8) & 255, colors[i] & 255);\n\t flate_puts(\">]\", out);\n }\n\t else if (img->depth == 1)\n flate_puts(\"/CS/G\", out);\n else\n flate_puts(\"/CS/RGB\", out);", " if (ncolors != 2)\n flate_puts(\"/I true\", out);", " \t flate_printf(out, \"/W %d/H %d/BPC %d\", img->width, img->height, indbits);", "\t if (ncolors > 0)\n\t {\n \t flate_puts(\" ID\\n\", out);\n \t flate_write(out, indices, indwidth * img->height, 1);\n\t }\n\t else if (OutputJPEG)\n\t {\n \t flate_puts(\"/F/DCT ID\\n\", out);", "\t jpg_setup(out, img, &cinfo);", "\t for (i = img->height, pixel = img->pixels;\n\t i > 0;\n\t i --, pixel += img->width * img->depth)\n\t jpeg_write_scanlines(&cinfo, &pixel, 1);", "\t jpeg_finish_compress(&cinfo);\n\t jpeg_destroy_compress(&cinfo);\n }\n\t else\n\t {\n \t flate_puts(\" ID\\n\", out);\n \t flate_write(out, img->pixels, img->width * img->height * img->depth, 1);\n }", "\t flate_write(out, (uchar *)\"\\nEI\\nQ\\n\", 6, 1);\n\t}\n break;", " case 1 : /* PostScript, Level 1 */\n fputs(\"GS\", out);\n\tfprintf(out, \"[%.1f 0 0 %.1f %.1f %.1f]CM\", r->width, r->height,\n\t r->x, r->y);", "\tif (img->mask)\n\t write_imagemask(out, r);", "\tfprintf(out, \"/picture %d string def\\n\", img->width * img->depth);", "\tif (img->depth == 1)\n\t fprintf(out, \"%d %d 8 [%d 0 0 %d 0 %d] {currentfile picture readhexstring pop} image\\n\",\n \t img->width, img->height,\n \t img->width, -img->height,\n \t img->height);\n\telse\n\t fprintf(out, \"%d %d 8 [%d 0 0 %d 0 %d] {currentfile picture readhexstring pop} false 3 colorimage\\n\",\n \t img->width, img->height,\n \t img->width, -img->height,\n \t img->height);", "\tps_hex(out, img->pixels, img->width * img->height * img->depth);", "\tfputs(\"GR\\n\", out);\n break;\n case 3 : /* PostScript, Level 3 */\n // Fallthrough to Level 2 output if compression is disabled and\n\t// we aren't doing transparency...\n if ((Compression && (!OutputJPEG || ncolors > 0)) ||\n\t (img->mask && img->maskscale == 8))\n\t{\n fputs(\"GS\", out);\n\t fprintf(out, \"[%.1f 0 0 %.1f %.1f %.1f]CM\", r->width, r->height,\n\t r->x, r->y);", "\t if (img->mask && img->maskscale != 8)\n\t write_imagemask(out, r);", " if (ncolors > 0)\n {\n\t if (ncolors <= 2)\n\t ncolors = 2; /* Adobe doesn't like 1 color images... */", "\t fprintf(out, \"[/Indexed/DeviceRGB %d\\n<\", ncolors - 1);\n\t for (i = 0; i < ncolors; i ++)\n\t {\n\t fprintf(out, \"%02X%02X%02X\", colors[i] >> 16,\n\t (colors[i] >> 8) & 255, colors[i] & 255);\n\t if ((i % 13) == 12)\n\t putc('\\n', out);\n }\n\t fputs(\">]setcolorspace\\n\", out);", "\t if (img->mask && img->maskscale == 8)\n\t fprintf(out, \"<<\"\n\t \"/ImageType 3\"\n\t\t\t \"/InterleaveType 1\"\n\t\t\t \"/MaskDict<<\"\n\t \"/ImageType 1\"\n\t \"/Width %d\"\n\t \"/Height %d\"\n\t \"/BitsPerComponent 8\"\n\t \"/ImageMatrix[%d 0 0 %d 0 %d]\"\n\t\t\t \"/Decode[0 1]\"\n\t \">>\\n\"\n\t\t\t \"/DataDict\",\n\t img->width, img->height,\n \t img->width, -img->height, img->height);", "\t fprintf(out, \"<<\"\n\t \"/ImageType 1\"\n\t \"/Width %d\"\n\t \"/Height %d\"\n\t \"/BitsPerComponent %d\"\n\t \"/ImageMatrix[%d 0 0 %d 0 %d]\"\n\t \"/Decode[0 %d]\",\n\t img->width, img->height, indbits,\n \t img->width, -img->height, img->height,\n \t (1 << indbits) - 1);", "#ifdef HTMLDOC_INTERPOLATION\n if (ncolors != 2)\n\t fputs(\"/Interpolate true\", out);\n#endif // HTMLDOC_INTERPOLATION", "#ifdef HTMLDOC_ASCII85\n fputs(\"/DataSource currentfile/ASCII85Decode filter\", out);\n#else\n fputs(\"/DataSource currentfile/ASCIIHexDecode filter\", out);\n#endif // HTMLDOC_ASCII85", " if (Compression)\n\t fputs(\"/FlateDecode filter\", out);", "\t fputs(\">>\\n\", out);", "\t if (img->mask && img->maskscale == 8)\n\t fputs(\">>\\n\", out);", "\t fputs(\"image\\n\", out);", " flate_open_stream(out);", "\t if (img->mask && img->maskscale == 8)\n\t {\n\t data = (uchar *)malloc((size_t)(img->width * 2));", "\t for (i = 0, maskptr = img->mask, indptr = indices;\n\t i < img->height;\n\t\t i ++)\n\t {\n\t for (j = img->width, dataptr = data; j > 0; j --)\n\t\t{\n\t\t *dataptr++ = *maskptr++;\n\t\t *dataptr++ = *indptr++;\n\t\t}", "\t\tflate_write(out, data, img->width * 2);\n\t }", "\t free(data);\n\t }\n\t else\n\t flate_write(out, indices, indwidth * img->height);", "\t flate_close_stream(out);\n }\n else\n {\n\t if (img->depth == 1)\n\t fputs(\"/DeviceGray setcolorspace\", out);\n\t else\n\t fputs(\"/DeviceRGB setcolorspace\", out);", "\t if (img->mask && img->maskscale == 8)\n\t fprintf(out, \"<<\"\n\t \"/ImageType 3\"\n\t\t\t \"/InterleaveType 1\"\n\t\t\t \"/MaskDict<<\"\n\t \"/ImageType 1\"\n\t \"/Width %d\"\n\t \"/Height %d\"\n\t \"/BitsPerComponent 8\"\n\t \"/ImageMatrix[%d 0 0 %d 0 %d]\"\n\t\t\t \"/Decode[0 1]\"\n\t \">>\\n\"\n\t\t\t \"/DataDict\",\n\t img->width, img->height,\n \t img->width, -img->height, img->height);", "\t fprintf(out, \"<<\"\n\t \"/ImageType 1\"\n\t \"/Width %d\"\n\t \"/Height %d\"\n\t \"/BitsPerComponent 8\"\n\t \"/ImageMatrix[%d 0 0 %d 0 %d]\"\n\t \"/Decode[%s]\",\n\t img->width, img->height,\n \t img->width, -img->height, img->height,\n \t img->depth == 1 ? \"0 1\" : \"0 1 0 1 0 1\");", "#ifdef HTMLDOC_INTERPOLATION\n\t fputs(\"/Interpolate true\", out);\n#endif // HTMLDOC_INTERPOLATION", "#ifdef HTMLDOC_ASCII85\n fputs(\"/DataSource currentfile/ASCII85Decode filter\", out);\n#else\n fputs(\"/DataSource currentfile/ASCIIHexDecode filter\", out);\n#endif // HTMLDOC_ASCII85", " if (Compression)\n\t fputs(\"/FlateDecode filter\", out);", "\t fputs(\">>\\n\", out);", "\t if (img->mask && img->maskscale == 8)\n\t fputs(\">>\\n\", out);", "\t fputs(\"image\\n\", out);", " flate_open_stream(out);", "\t if (img->mask && img->maskscale == 8)\n\t {\n\t data = (uchar *)malloc((size_t)(img->width * (img->depth + 1)));", "\t for (i = 0, maskptr = img->mask, pixel = img->pixels;\n\t i < img->height;\n\t\t i ++)\n\t {\n\t if (img->depth == 1)\n\t\t{\n\t for (j = img->width, dataptr = data; j > 0; j --)\n\t\t {\n\t\t *dataptr++ = *maskptr++;\n\t\t *dataptr++ = *pixel++;\n\t\t }\n\t\t}\n\t\telse\n\t\t{\n\t for (j = img->width, dataptr = data; j > 0; j --)\n\t\t {\n\t\t *dataptr++ = *maskptr++;\n\t\t *dataptr++ = *pixel++;\n\t\t *dataptr++ = *pixel++;\n\t\t *dataptr++ = *pixel++;\n\t\t }\n\t\t}", "\t\tflate_write(out, data, img->width * (img->depth + 1));\n\t }", "\t free(data);\n\t }\n\t else\n\t flate_write(out, img->pixels,\n\t img->width * img->height * img->depth);", "\t flate_close_stream(out);\n }", "\t fputs(\"GR\\n\", out);\n break;\n\t}", " case 2 : /* PostScript, Level 2 */\n fputs(\"GS\", out);\n\tfprintf(out, \"[%.1f 0 0 %.1f %.1f %.1f]CM\", r->width, r->height,\n\t r->x, r->y);", "\tif (img->mask)\n\t write_imagemask(out, r);", " if (ncolors > 0)\n {\n\t fprintf(out, \"[/Indexed/DeviceRGB %d\\n<\", ncolors - 1);\n\t for (i = 0; i < ncolors; i ++)\n\t {\n\t fprintf(out, \"%02X%02X%02X\", colors[i] >> 16,\n\t (colors[i] >> 8) & 255, colors[i] & 255);\n\t if ((i % 13) == 12)\n\t putc('\\n', out);\n }", "\t fputs(\">]setcolorspace\\n\", out);", "\t fprintf(out, \"<<\"\n\t \"/ImageType 1\"\n\t \"/Width %d\"\n\t \"/Height %d\"\n\t \"/BitsPerComponent %d\"\n\t \"/ImageMatrix[%d 0 0 %d 0 %d]\"\n\t \"/Decode[0 %d]\",\n\t img->width, img->height, indbits,\n \t img->width, -img->height, img->height,\n \t (1 << indbits) - 1);", "#ifdef HTMLDOC_INTERPOLATION\n if (ncolors != 2)\n\t fputs(\"/Interpolate true\", out);\n#endif // HTMLDOC_INTERPOLATION", "#ifdef HTMLDOC_ASCII85\n\t fputs(\"/DataSource currentfile/ASCII85Decode filter>>image\\n\", out);", " ps_ascii85(out, indices, indwidth * img->height, 1);\n#else\n\t fputs(\"/DataSource currentfile/ASCIIHexDecode filter>>image\\n\", out);", " ps_hex(out, indices, indwidth * img->height);\n\t // End of data marker...\n\t fputs(\">\\n\", out);\n#endif /* HTMLDOC_ASCII85 */\n }\n\telse if (OutputJPEG)\n\t{\n\t if (img->depth == 1)\n\t fputs(\"/DeviceGray setcolorspace\\n\", out);\n\t else\n\t fputs(\"/DeviceRGB setcolorspace\\n\", out);", "\t fprintf(out, \"<<\"\n\t \"/ImageType 1\"\n\t \"/Width %d\"\n\t \"/Height %d\"\n\t \"/BitsPerComponent 8\"\n\t \"/ImageMatrix[%d 0 0 %d 0 %d]\"\n\t \"/Decode[%s]\",\n\t img->width, img->height,\n \t img->width, -img->height, img->height,\n \t img->depth == 1 ? \"0 1\" : \"0 1 0 1 0 1\");", "#ifdef HTMLDOC_INTERPOLATION\n\t fputs(\"/Interpolate true\", out);\n#endif // HTMLDOC_INTERPOLATION", "#ifdef HTMLDOC_ASCII85\n\t fputs(\"/DataSource currentfile/ASCII85Decode filter/DCTDecode filter\"\n\t \">>image\\n\", out);\n#else\n\t fputs(\"/DataSource currentfile/ASCIIHexDecode filter/DCTDecode filter\"\n\t \">>image\\n\", out);\n#endif // HTMLDOC_ASCII85", "\t jpg_setup(out, img, &cinfo);", "\t for (i = img->height, pixel = img->pixels;\n\t i > 0;\n\t i --, pixel += img->width * img->depth)\n\t jpeg_write_scanlines(&cinfo, &pixel, 1);", "\t jpeg_finish_compress(&cinfo);\n\t jpeg_destroy_compress(&cinfo);", "#ifdef HTMLDOC_ASCII85\n ps_ascii85(out, (uchar *)\"\", 0, 1);\n#else\n\t // End of data marker...\n\t fputs(\">\\n\", out);\n#endif // HTMLDOC_ASCII85\n }\n else\n {\n\t if (img->depth == 1)\n\t fputs(\"/DeviceGray setcolorspace\\n\", out);\n\t else\n\t fputs(\"/DeviceRGB setcolorspace\\n\", out);", "\t fprintf(out, \"<<\"\n\t \"/ImageType 1\"\n\t \"/Width %d\"\n\t \"/Height %d\"\n\t \"/BitsPerComponent 8\"\n\t \"/ImageMatrix[%d 0 0 %d 0 %d]\"\n\t \"/Decode[%s]\",\n\t img->width, img->height,\n \t img->width, -img->height, img->height,\n \t img->depth == 1 ? \"0 1\" : \"0 1 0 1 0 1\");", "#ifdef HTMLDOC_INTERPOLATION\n\t fputs(\"/Interpolate true\", out);\n#endif // HTMLDOC_INTERPOLATION", "#ifdef HTMLDOC_ASCII85\n fputs(\"/DataSource currentfile/ASCII85Decode filter\"\n\t \">>image\\n\", out);", "\t ps_ascii85(out, img->pixels, img->width * img->height *\n\t img->depth, 1);\n#else\n fputs(\"/DataSource currentfile/ASCIIHexDecode filter\"\n\t \">>image\\n\", out);", " ps_hex(out, img->pixels, img->width * img->depth * img->height);\n\t // End of data marker...\n\t fputs(\">\\n\", out);\n#endif // HTMLDOC_ASCII85\n }", "\tfputs(\"GR\\n\", out);\n break;\n }", " if (ncolors > 0)\n free(indices);", " image_unload(img);\n}", "\n/*\n * 'write_imagemask()' - Write an imagemask to the output file...\n */", "static void\nwrite_imagemask(FILE *out,\t\t/* I - Output file */\n render_t *r)\t\t/* I - Image to write */\n{\n image_t\t*img;\t\t\t/* Current image */\n int\t\tx, y;\t\t\t/* Position in mask image */\n int\t\tstartx, count;\t\t/* Start and count */\n uchar\t\t*ptr,\t\t\t/* Pointer into mask image */\n\t\tbyte,\t\t\t/* Current byte */\n\t\tbit;\t\t\t/* Current bit */\n float\t\tscalex, scaley;\t\t/* 1/(w-1) and 1/(h-1) scaling factors */\n int\t\twidth, height;\t\t/* Scaled width and height */", "\n img = r->data.image;\n width = img->width * img->maskscale;\n height = img->height * img->maskscale;\n scalex = 1.0f / width;\n scaley = 1.0f / height;", " switch (PSLevel)\n {\n case 0 : // PDF\n break;", " default : // PostScript\n fputs(\"\\nnewpath\\n\", out);\n break;\n }", " for (y = 0; y < height; y ++)\n {\n for (x = 0, ptr = img->mask + (height - y - 1) * img->maskwidth,\n bit = 128, byte = *ptr++, startx = 0, count = 0;\n x < width;\n\t x ++)\n {\n if (!(bit & byte))\n {\n if (!count)\n\t startx = x;", " count ++;\n }\n else if (count)\n {\n\tswitch (PSLevel)\n\t{\n\t case 0 : // PDF\n\t flate_printf(out, \"%.6f %.6f %.6f %.6f re\\n\",\n\t\t\t (float)startx * scalex,\n\t\t\t (float)y * scaley,\n\t\t\t (float)count * scalex,\n\t\t\t 1.0f * scaley);\n break;", "\t default : // PostScript\n\t fprintf(out, \"%.6f %.6f %.6f %.6f re\\n\",\n\t\t (float)startx * scalex,\n\t\t (float)y * scaley,\n\t\t (float)count * scalex,\n\t\t 1.0f * scaley);\n break;\n\t}", "\tcount = 0;\n }", " if (bit > 1)\n bit >>= 1;\n else\n {\n bit = 128;\n\tbyte = *ptr++;\n }\n }", " if (count)\n {\n switch (PSLevel)\n {\n\tcase 0 : // PDF\n\t flate_printf(out, \"%.6f %.6f %.6f %.6f re\\n\",\n\t\t\t (float)startx * scalex,\n\t\t\t (float)y * scaley,\n\t\t\t (float)count * scalex,\n\t\t\t 1.0f * scaley);\n break;", "\tdefault : // PostScript\n\t fprintf(out, \"%.6f %.6f %.6f %.6f re\\n\",\n\t\t (float)startx * scalex,\n\t\t (float)y * scaley,\n\t\t (float)count * scalex,\n\t\t 1.0f * scaley);\n break;\n }\n }\n }", " switch (PSLevel)\n {\n case 0 : // PDF\n flate_puts(\"W n\\n\", out);\n break;", " default : // PostScript\n fputs(\"clip\\n\", out);\n break;\n }\n}", "\n/*\n * 'write_prolog()' - Write the file prolog...\n */", "static void\nwrite_prolog(FILE *out,\t\t/* I - Output file */\n int page_count,\t\t/* I - Number of pages (0 if not known) */\n uchar *author,\t\t/* I - Author of document */\n uchar *creator,\t\t/* I - Application that generated the HTML file */\n uchar *copyright,\t\t/* I - Copyright (if any) on the document */\n uchar *keywords,\t\t/* I - Search keywords */\n\t uchar *subject)\t\t/* I - Subject */\n{\n FILE\t\t*prolog;\t\t/* PostScript prolog file */\n int\t\ti, j,\t\t\t/* Looping vars */\n\t\tencoding_object;\t/* Font encoding object */\n int\t\tpage;\t\t\t/* Current page */\n render_t\t*r;\t\t\t/* Current render data */\n int\t\tfonts_used[TYPE_MAX][STYLE_MAX];\n\t\t\t\t\t/* Whether or not a font is used */\n int\t\tfont_desc[TYPE_MAX][STYLE_MAX];\n\t\t\t\t\t/* Font descriptor objects */\n char\t\ttemp[1024];\t\t/* Temporary string */\n md5_state_t\tmd5;\t\t\t/* MD5 state */\n md5_byte_t\tdigest[16];\t\t/* MD5 digest value */\n rc4_context_t\trc4;\t\t\t/* RC4 context */\n uchar\t\towner_pad[32],\t\t/* Padded owner password */\n\t\towner_key[32],\t\t/* Owner key */\n\t\tuser_pad[32],\t\t/* Padded user password */\n\t\tuser_key[32];\t\t/* User key */\n uchar\t\tperm_bytes[4];\t\t/* Permission bytes */\n unsigned\tperm_value;\t\t/* Permission value, unsigned */\n static unsigned char pad[32] =\n\t\t{\t\t\t/* Padding for passwords */\n\t\t 0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41,\n\t\t 0x64, 0x00, 0x4e, 0x56, 0xff, 0xfa, 0x01, 0x08,\n\t\t 0x2e, 0x2e, 0x00, 0xb6, 0xd0, 0x68, 0x3e, 0x80,\n\t\t 0x2f, 0x0c, 0xa9, 0xfe, 0x64, 0x53, 0x69, 0x7a\n\t\t};", "\n /*\n * See what fonts are used...\n */", " memset(fonts_used, 0, sizeof(fonts_used));\n fonts_used[HeadFootType][HeadFootStyle] = 1;", " for (page = 0; page < (int)num_pages; page ++)\n for (r = pages[page].start; r != NULL; r = r->next)\n if (r->type == RENDER_TEXT)\n\tfonts_used[r->data.text.typeface][r->data.text.style] = 1;", "#ifdef DEBUG\n puts(\"The following fonts were used:\");\n for (i = 0; i < TYPE_MAX; i ++)\n for (j = 0; j < STYLE_MAX; j ++)\n if (fonts_used[i][j])\n printf(\" %s\\n\", _htmlFonts[i][j]);\n#endif // DEBUG", " /*\n * Generate the heading...\n */", " if (PSLevel > 0)\n {\n /*\n * Write PostScript prolog stuff...\n */", " if (XRXComments)\n {\n int start, end;\t// Start and end of document pages...\n int count;\t// Number of exception pages in this range...", "\n // The following comments are Xerox job ticket information that\n // is used on the high-end Laser Printing Systems rather than\n // embedded commands...\n fputs(\"%XRXbegin: 001.0300\\n\", out);\n fputs(\"%XRXPDLformat: PS-Adobe\\n\", out);\n if (doc_title)\n\tfprintf(out, \"%%XRXtitle: %s\\n\", doc_title);", " if (OutputFiles)\n {\n // Output a single chapter...\n\tif (chapter < 0)\n\t{\n\t start = 0;\n\t end = chapter_outstarts[1] - 1;\n\t}\n\telse\n\t{\n\t start = chapter_outstarts[chapter];\n\t end = chapter_outends[chapter];\n\t}\n }\n else\n {\n start = 0;\n\tend = 0;\n }", " if (pages[outpages[start].pages[0]].duplex)\n {\n\tif (pages[outpages[start].pages[0]].landscape)\n\t fputs(\"%XRXrequirements: duplex(tumble)\\n\", out);\n\telse\n\t fputs(\"%XRXrequirements: duplex\\n\", out);\n }\n else\n\tfputs(\"%XRXrequirements: simplex\\n\", out);", " fputs(\"%XRXdisposition: PRINT\\n\", out);\n fputs(\"%XRXsignature: False\\n\", out);\n fprintf(out, \"%%XRXpaperType-size: %.0f %.0f\\n\",\n pages[outpages[start].pages[0]].width * 25.4f / 72.0f,\n pages[outpages[start].pages[0]].length * 25.4f / 72.0f);\n if (pages[outpages[start].pages[0]].media_type[0])\n\tfprintf(out, \"%%XRXpaperType-preFinish: %s 0 0\\n\",\n \tpages[start].media_type);\n if (pages[outpages[start].pages[0]].media_color[0])\n\tfprintf(out, \"%%XRXdocumentPaperColors: %c%s\\n\",\n \ttolower(pages[start].media_color[0]),\n\t\tpages[start].media_color + 1);", " if (OutputFiles)\n {\n // Handle document settings per-chapter...\n\tfor (i = start + 1; i < end; i += count)\n\t{\n\t if (pages[outpages[i].pages[0]].width != pages[0].width ||\n\t pages[outpages[i].pages[0]].length != pages[0].length ||\n\t strcmp(pages[outpages[i].pages[0]].media_type,\n\t pages[0].media_type) != 0 ||\n\t strcmp(pages[outpages[i].pages[0]].media_color,\n\t pages[0].media_color) != 0 ||\n\t pages[outpages[i].pages[0]].duplex != pages[0].duplex)\n\t {\n\t for (count = 1; (i + count) <= end; count ++)\n\t if (pages[outpages[i].pages[0]].width !=\n\t pages[outpages[i + count].pages[0]].width ||\n\t\t pages[outpages[i].pages[0]].length !=\n\t\t pages[outpages[i + count].pages[0]].length ||\n\t\t strcmp(pages[outpages[i].pages[0]].media_type,\n\t\t pages[outpages[i + count].pages[0]].media_type) != 0 ||\n\t\t strcmp(pages[outpages[i].pages[0]].media_color,\n\t\t pages[outpages[i + count].pages[0]].media_color) != 0 ||\n\t\t pages[outpages[i].pages[0]].duplex !=\n\t\t pages[outpages[i + count].pages[0]].duplex)\n\t\tbreak;", "\t fprintf(out, \"%%XRXpageExceptions: %d %d %.0f %.0f %c%s opaque %s 0 0\\n\",\n\t i + 1, i + count,\n\t\t pages[outpages[i].pages[0]].width * 25.4f / 72.0f,\n\t\t pages[outpages[i].pages[0]].length * 25.4f / 72.0f,\n\t\t tolower(pages[outpages[i].pages[0]].media_color[0]),\n\t\t pages[outpages[i].pages[0]].media_color + 1,\n\t\t pages[outpages[i].pages[0]].media_type[0] ?\n\t\t pages[outpages[i].pages[0]].media_type : \"Plain\");", "\t if (pages[outpages[i].pages[0]].duplex &&\n\t pages[outpages[i].pages[0]].landscape)\n\t fprintf(out, \"%%XRXpageExceptions-plex: %d %d duplex(tumble)\\n\",\n\t i + 1, i + count);\n\t else if (pages[outpages[i].pages[0]].duplex)\n\t fprintf(out, \"%%XRXpageExceptions-plex: %d %d duplex\\n\",\n\t i + 1, i + count);\n else\n\t fprintf(out, \"%%XRXpageExceptions-plex: %d %d simplex\\n\",\n\t i + 1, i + count);\n\t }\n\t else\n\t count = 1;\n }\n }\n else\n {\n // All pages are in a single file...\n for (j = (TocLevels == 0); j <= TocDocCount; j ++)\n\t{\n\t start = chapter_outstarts[j];\n\t end = chapter_outends[j];", "\t for (i = start + 1; i < end; i += count)\n\t {\n\t if (pages[outpages[i].pages[0]].width != pages[0].width ||\n\t\tpages[outpages[i].pages[0]].length != pages[0].length ||\n\t\tstrcmp(pages[outpages[i].pages[0]].media_type,\n\t\t pages[0].media_type) != 0 ||\n\t\tstrcmp(pages[outpages[i].pages[0]].media_color,\n\t\t pages[0].media_color) != 0 ||\n\t\tpages[outpages[i].pages[0]].duplex != pages[0].duplex)\n\t {\n\t for (count = 1; (i + count) < end; count ++)\n\t\tif (pages[outpages[i].pages[0]].width !=\n\t\t pages[outpages[i + count].pages[0]].width ||\n\t\t pages[outpages[i].pages[0]].length !=\n\t\t pages[outpages[i + count].pages[0]].length ||\n\t\t strcmp(pages[outpages[i].pages[0]].media_type,\n\t\t pages[outpages[i + count].pages[0]].media_type) != 0 ||\n\t\t strcmp(pages[outpages[i].pages[0]].media_color,\n\t\t pages[outpages[i + count].pages[0]].media_color) != 0 ||\n\t\t pages[outpages[i].pages[0]].duplex !=\n\t\t pages[outpages[i + count].pages[0]].duplex)\n\t\t break;", "\t fprintf(out, \"%%XRXpageExceptions: %d %d %.0f %.0f %c%s opaque %s 0 0\\n\",\n\t i + 1, i + count,\n\t\t pages[outpages[i].pages[0]].width * 25.4f / 72.0f,\n\t\t pages[outpages[i].pages[0]].length * 25.4f / 72.0f,\n\t\t tolower(pages[outpages[i].pages[0]].media_color[0]),\n\t\t pages[outpages[i].pages[0]].media_color + 1,\n\t\t pages[outpages[i].pages[0]].media_type[0] ?\n\t\t pages[outpages[i].pages[0]].media_type : \"Plain\");", "\t if (pages[outpages[i].pages[0]].duplex && pages[outpages[i].pages[0]].landscape)\n\t\tfprintf(out, \"%%XRXpageExceptions-plex: %d %d duplex(tumble)\\n\",\n\t \ti + 1, i + count);\n\t else if (pages[outpages[i].pages[0]].duplex)\n\t\tfprintf(out, \"%%XRXpageExceptions-plex: %d %d duplex\\n\",\n\t \ti + 1, i + count);\n else\n\t\tfprintf(out, \"%%XRXpageExceptions-plex: %d %d simplex\\n\",\n\t \ti + 1, i + count);\n\t }\n\t else\n\t count = 1;\n }\n\t}\n }", " fputs(\"%XRXend\\n\", out);\n }", " fputs(\"%!PS-Adobe-3.0\\n\", out);\n if (Landscape)\n fprintf(out, \"%%%%BoundingBox: 0 0 %d %d\\n\", PageLength, PageWidth);\n else\n fprintf(out, \"%%%%BoundingBox: 0 0 %d %d\\n\", PageWidth, PageLength);\n fprintf(out,\"%%%%LanguageLevel: %d\\n\", PSLevel);\n fputs(\"%%Creator: \" HTMLDOC_PRODUCER \"\\n\", out);\n fprintf(out, \"%%%%CreationDate: D:%04d%02d%02d%02d%02d%02d+0000\\n\",\n doc_date.tm_year + 1900, doc_date.tm_mon + 1, doc_date.tm_mday,\n doc_date.tm_hour, doc_date.tm_min, doc_date.tm_sec);\n if (doc_title != NULL)\n fprintf(out, \"%%%%Title: %s\\n\", doc_title);\n if (author != NULL)\n fprintf(out, \"%%%%Author: %s\\n\", author);\n if (creator != NULL)\n fprintf(out, \"%%%%Generator: %s\\n\", creator);\n if (copyright != NULL)\n fprintf(out, \"%%%%Copyright: %s\\n\", copyright);\n if (keywords != NULL)\n fprintf(out, \"%%%%Keywords: %s\\n\", keywords);\n if (subject != NULL)\n fprintf(out, \"%%%%Subject: %s\\n\", keywords);\n if (page_count > 0)\n fprintf(out, \"%%%%Pages: %d\\n\", page_count);\n else\n fputs(\"%%Pages: (atend)\\n\", out);", " if (!EmbedFonts)\n {\n fputs(\"%%DocumentNeededResources:\\n\", out);", " for (i = 0; i < TYPE_MAX; i ++)\n for (j = 0; j < STYLE_MAX; j ++)\n if (fonts_used[i][j] && _htmlStandardFonts[i])\n fprintf(out, \"%%%%+ font %s\\n\", _htmlFonts[i][j]);\n }", " fputs(\"%%DocumentProvidedResources:\\n\", out);", " for (i = 0; i < TYPE_MAX; i ++)\n for (j = 0; j < STYLE_MAX; j ++)\n if (fonts_used[i][j] && (EmbedFonts || !_htmlStandardFonts[i]))\n fprintf(out, \"%%%%+ font %s\\n\", _htmlFonts[i][j]);\n fputs(\"%%DocumentData: Clean7bit\\n\", out);\n fputs(\"%%EndComments\\n\", out);", " fputs(\"%%BeginProlog\\n\", out);", " /*\n * Embed fonts?\n */", " for (i = 0; i < TYPE_MAX; i ++)\n {\n if (EmbedFonts || !_htmlStandardFonts[i])\n\tfor (j = 0; j < STYLE_MAX; j ++)\n if (fonts_used[i][j])\n\t write_type1(out, (typeface_t)i, (style_t)j);\n }", " /*\n * Procedures used throughout the document...\n */", " const char *version = SVERSION;", " fprintf(out, \"%%%%BeginResource: procset htmldoc-page 1.8 %s\\n\", version + 4);\n fputs(\"/BD{bind def}bind def\", out);\n fputs(\"/B{dup 0 exch rlineto exch 0 rlineto neg 0 exch rlineto\\n\"\n \"closepath stroke}BD\", out);\n fputs(\"/C{setrgbcolor}BD\\n\", out);\n fputs(\"/CM{concat}BD\", out);\n fputs(\"/DF{findfont dup length dict begin{1 index/FID ne{def}{pop pop}\\n\"\n \"ifelse}forall/Encoding fontencoding def currentdict end definefont pop}BD\\n\", out);\n fputs(\"/F{dup 0 exch rlineto exch 0 rlineto neg 0 exch rlineto closepath fill}BD\\n\", out);\n fputs(\"/FS{/hdFontSize exch def}BD\", out);\n fputs(\"/G{setgray}BD\\n\", out);\n fputs(\"/GS{gsave}BD\", out);\n fputs(\"/GR{grestore}BD\", out);\n fputs(\"/J{0 exch ashow}BD\\n\", out);\n fputs(\"/L{0 rlineto stroke}BD\", out);\n fputs(\"/M{moveto}BD\", out);\n fputs(\"/re{4 2 roll moveto 1 index 0 rlineto 0 exch rlineto neg 0 rlineto closepath}BD\\n\", out);\n fputs(\"/RO{rotate}BD\", out);\n fputs(\"/S{show}BD\", out);\n fputs(\"/SC{dup scale}BD\\n\", out);\n fputs(\"/SF{findfont hdFontSize scalefont setfont}BD\", out);\n fputs(\"/SP{showpage}BD\", out);\n fputs(\"/T{translate}BD\\n\", out);\n fputs(\"%%EndResource\\n\", out);", " /*\n * Output the font encoding for the current character set... For now we\n * just support 8-bit fonts since true Unicode support needs a very large\n * number of extra fonts that aren't normally available on a PS printer.\n */", " fputs(\"/fontencoding[\\n\", out);\n for (i = 0, j = 0; i < 256; i ++)\n {\n if (_htmlGlyphs[i])\n j += strlen(_htmlGlyphs[i]) + 1;\n else\n j += 8;", " if (j > 80)\n {\n\tif (_htmlGlyphs[i])\n j = strlen(_htmlGlyphs[i]) + 1;\n\telse\n j = 8;", " putc('\\n', out);\n }", " putc('/', out);\n if (_htmlGlyphs[i])\n fputs(_htmlGlyphs[i], out);\n else\n fputs(\".notdef\", out);\n }", " fputs(\"]def\\n\", out);", " /*\n * Fonts...\n */", " for (i = 0; i < TYPE_MAX; i ++)\n for (j = 0; j < STYLE_MAX; j ++)\n if (fonts_used[i][j])\n {\n\t if (i < TYPE_SYMBOL)\n\t fprintf(out, \"/F%x/%s DF\\n\", i * 4 + j, _htmlFonts[i][j]);\n\t else\n\t fprintf(out, \"/F%x/%s findfont definefont pop\\n\", i * 4 + j,\n\t _htmlFonts[i][j]);\n }", " if (PSCommands)\n {\n snprintf(temp, sizeof(temp), \"%s/data/prolog.ps\", _htmlData);\n if ((prolog = fopen(temp, \"rb\")) != NULL)\n {\n\twhile (fgets(temp, sizeof(temp), prolog) != NULL)\n fputs(temp, out);", "\tfclose(prolog);\n }\n else\n {\n\tprogress_error(HD_ERROR_FILE_NOT_FOUND,\n \"Unable to open data file \\\"%s\\\" - %s\", temp,\n strerror(errno));", "\tfprintf(out, \"%%%%BeginResource: procset htmldoc-device 1.8 %s\\n\", version + 4);\n\tfputs(\"languagelevel 1 eq{/setpagedevice{pop}BD}if\\n\", out);\n\tfputs(\"/SetDuplexMode{<</Duplex 3 index/Tumble 5 index>>setpagedevice \"\n \"pop pop}BD\\n\", out);\n\tfputs(\"/SetMediaColor{pop}BD\\n\", out);\n\tfputs(\"/SetMediaType{pop}BD\\n\", out);\n\tfputs(\"/SetMediaPosition{pop}BD\\n\", out);\n\tfputs(\"/SetPageSize{2 array astore<</PageSize 2 index/ImageableArea \"\n \"null>>setpagedevice pop}BD\\n\", out);\n\tfputs(\"%%EndResource\\n\", out);\n }\n }", " if (background_image != NULL)\n ps_write_background(out);", " fputs(\"%%EndProlog\\n\", out);\n }\n else\n {\n /*\n * Write PDF prolog stuff...\n */", " fprintf(out, \"%%PDF-%.1f\\n\", 0.1 * PDFVersion);\n fputs(\"%\\342\\343\\317\\323\\n\", out);\n num_objects = 0;", " /*\n * Compute the file ID...\n */", " md5_init(&md5);\n md5_append(&md5, (md5_byte_t *)OutputPath, sizeof(OutputPath));\n md5_append(&md5, (md5_byte_t *)&doc_time, sizeof(doc_time));\n md5_finish(&md5, file_id);", " /*\n * Setup encryption stuff as necessary...\n */", " if (Encryption)\n {\n /*\n * Copy and pad the user password...\n */", " strlcpy((char *)user_pad, UserPassword, sizeof(user_pad));", " if ((i = strlen(UserPassword)) < 32)\n\tmemcpy(user_pad + i, pad, (size_t)(32 - i));", " if (OwnerPassword[0])\n {\n /*\n * Copy and pad the owner password...\n\t*/", " strlcpy((char *)owner_pad, OwnerPassword, sizeof(owner_pad));", "\tif ((i = strlen(OwnerPassword)) < 32)\n\t memcpy(owner_pad + i, pad, (size_t)(32 - i));\n }\n else\n {\n /*\n * Generate a pseudo-random owner password...\n\t*/", "\tsrand(time(NULL));", "\tfor (i = 0; i < 32; i ++)\n\t owner_pad[i] = (uchar)rand();\n }", " /*\n * What is the key length?\n *\n * Acrobat 4.0 and earlier (PDF 1.3 and earlier) allow a maximum of\n * 40-bits. Acrobat 5.0 and newer support 128-bits.\n */", " if (PDFVersion > 13)\n encrypt_len = 16;\t// 128 bits\n else\n encrypt_len = 5;\t// 40 bits", " /*\n * Compute the owner key...\n */", " md5_init(&md5);\n md5_append(&md5, owner_pad, 32);\n md5_finish(&md5, digest);", " if (encrypt_len > 5)\n {\n // MD5 the result 50 more times...\n\tfor (i = 0; i < 50; i ++)\n\t{\n md5_init(&md5);\n md5_append(&md5, digest, 16);\n md5_finish(&md5, digest);\n\t}", " // Copy the padded user password...\n memcpy(owner_key, user_pad, 32);", " // Encrypt the result 20 times...\n\tfor (i = 0; i < 20; i ++)\n\t{\n\t // XOR each byte in the key with the loop counter...\n\t for (j = 0; j < encrypt_len; j ++)\n\t encrypt_key[j] = (uchar)(digest[j] ^ i);", " rc4_init(&rc4, encrypt_key, (size_t)encrypt_len);\n rc4_encrypt(&rc4, owner_key, owner_key, 32);\n\t}\n }\n else\n {\n rc4_init(&rc4, digest, (size_t)encrypt_len);\n rc4_encrypt(&rc4, user_pad, owner_key, 32);\n }", " /*\n * Figure out the permissions word; the new N-bit security\n * handler adds several new permission bits, which we must\n * simulate...\n */", " perm_value = (unsigned)Permissions;", " if (encrypt_len > 5)\n {\n // N-bit encryption...\n\tif (!(perm_value & PDF_PERM_COPY))\n\t perm_value &= (unsigned)~0x00240000;\t// Mask additional copy perms...\n }", " /*\n * Compute the encryption key...\n */", " md5_init(&md5);\n md5_append(&md5, user_pad, 32);\n md5_append(&md5, owner_key, 32);", " perm_bytes[0] = (uchar)perm_value;\n perm_bytes[1] = (uchar)(perm_value >> 8);\n perm_bytes[2] = (uchar)(perm_value >> 16);\n perm_bytes[3] = (uchar)(perm_value >> 24);", " md5_append(&md5, perm_bytes, 4);\n md5_append(&md5, file_id, 16);\n md5_finish(&md5, digest);", " if (encrypt_len > 5)\n {\n // MD5 the result 50 times..\n for (i = 0; i < 50; i ++)\n\t{\n\t md5_init(&md5);\n\t md5_append(&md5, digest, 16);\n\t md5_finish(&md5, digest);\n\t}\n }", " memcpy(encrypt_key, digest, (size_t)encrypt_len);", " /*\n * Compute the user key...\n */", " if (encrypt_len > 5)\n {\n md5_init(&md5);\n md5_append(&md5, pad, 32);\n md5_append(&md5, file_id, 16);\n md5_finish(&md5, user_key);", " memset(user_key + 16, 0, 16);", " // Encrypt the result 20 times...\n for (i = 0; i < 20; i ++)\n\t{\n\t // XOR each byte in the key with the loop counter...\n\t for (j = 0; j < encrypt_len; j ++)\n\t digest[j] = (uchar)(encrypt_key[j] ^ i);", " rc4_init(&rc4, digest, (size_t)encrypt_len);\n rc4_encrypt(&rc4, user_key, user_key, 16);\n\t}\n }\n else\n {\n rc4_init(&rc4, encrypt_key, (size_t)encrypt_len);\n rc4_encrypt(&rc4, pad, user_key, 32);\n }", " /*\n * Write the encryption dictionary...\n */", " encrypt_object = pdf_start_object(out);", " fputs(\"/Filter/Standard/O<\", out);\n for (i = 0; i < 32; i ++)\n fprintf(out, \"%02x\", owner_key[i]);\n fputs(\">/U<\", out);\n for (i = 0; i < 32; i ++)\n fprintf(out, \"%02x\", user_key[i]);\n fputs(\">\", out);", " if (encrypt_len > 5)\n {\n // N-bit encryption...\n fprintf(out, \"/P %d/V 2/R 3/Length %d\", (int)perm_value, encrypt_len * 8);\n }\n else\n fprintf(out, \"/P %d/V 1/R 2\", (int)perm_value);", " pdf_end_object(out);\n }\n else\n encrypt_object = 0;", " /*\n * Write info object...\n */", " info_object = pdf_start_object(out);", " fputs(\"/Producer\", out);\n write_string(out, (uchar *)HTMLDOC_PRODUCER, 0);\n fputs(\"/CreationDate\", out);\n snprintf(temp, sizeof(temp), \"D:%04d%02d%02d%02d%02d%02d+0000\",\n doc_date.tm_year + 1900, doc_date.tm_mon + 1, doc_date.tm_mday,\n doc_date.tm_hour, doc_date.tm_min, doc_date.tm_sec);\n write_string(out, (uchar *)temp, 0);", " if (doc_title != NULL)\n {\n fputs(\"/Title\", out);\n write_utf16(out, doc_title);\n }", " if (author != NULL || copyright != NULL)\n {\n if (author && copyright)\n snprintf(temp, sizeof(temp), \"%s, %s\", author, copyright);\n else if (author)\n strlcpy(temp, (const char *)author, sizeof(temp));\n else\n strlcpy(temp, (const char *)copyright, sizeof(temp));", " fputs(\"/Author\", out);\n write_utf16(out, (uchar *)temp);\n }", " if (creator != NULL)\n {\n fputs(\"/Creator\", out);\n write_utf16(out, creator);\n }", " if (keywords != NULL)\n {\n fputs(\"/Keywords\", out);\n write_utf16(out, keywords);\n }", " if (subject != NULL)\n {\n fputs(\"/Subject\", out);\n write_utf16(out, subject);\n }", " pdf_end_object(out);", " /*\n * Write the font encoding for the selected character set. Note that\n * we *should* be able to use the WinAnsiEncoding value for ISO-8859-1\n * to make smaller files, however Acrobat Exchange does not like it\n * despite the fact that it is defined in the PDF specification...\n */", " encoding_object = pdf_start_object(out);", " fputs(\"/Type/Encoding\", out);\n fputs(\"/Differences[\", out);\n for (i = 0, j = -1; i < 256; i ++)\n if (_htmlGlyphs[i])\n {\n /*\n * Output a character index if we had blank ones...\n\t*/", " if (j != (i - 1))\n\t fprintf(out, \" %d\", i);", " fprintf(out, \"/%s\", _htmlGlyphs[i]);\n\tj = i;\n }", " fputs(\"]\", out);\n pdf_end_object(out);", " memset(font_desc, 0, sizeof(font_desc));", " /*\n * Build font descriptors for the EmbedFonts fonts...\n */", " for (i = 0; i < TYPE_MAX; i ++)\n if (EmbedFonts || !_htmlStandardFonts[i])\n\tfor (j = 0; j < STYLE_MAX; j ++)\n if (fonts_used[i][j])\n\t font_desc[i][j] = write_type1(out, (typeface_t )i, (style_t)j);", " for (i = 0; i < TYPE_MAX; i ++)\n for (j = 0; j < STYLE_MAX; j ++)\n if (fonts_used[i][j])\n {\n\t font_objects[i * STYLE_MAX + j] = pdf_start_object(out);", "\t fputs(\"/Type/Font\", out);\n\t fputs(\"/Subtype/Type1\", out);\n\t fprintf(out, \"/BaseFont/%s\", _htmlFonts[i][j]);", " if (font_desc[i][j])\n\t {\n\t // Embed Type1 font...\n\t fputs(\"/FirstChar 0\", out);\n\t fputs(\"/LastChar 255\", out);\n\t fprintf(out, \"/Widths %d 0 R\", font_desc[i][j] + 1);\n\t fprintf(out, \"/FontDescriptor %d 0 R\", font_desc[i][j]);\n\t }", "\t if (i < TYPE_SYMBOL) /* Use native encoding for symbols */\n\t fprintf(out, \"/Encoding %d 0 R\", encoding_object);", " pdf_end_object(out);\n }\n }\n}", "\n/*\n * 'write_string()' - Write a text entity.\n */", "static void\nwrite_string(FILE *out,\t\t/* I - Output file */\n uchar *s,\t\t\t/* I - String */\n\t int compress)\t\t/* I - Compress output? */\n{\n int\ti;\t\t\t\t/* Looping var */", "\n if (Encryption && !compress && PSLevel == 0)\n {\n int\t\tlen,\t\t\t// Length of string\n\t\tbytes;\t\t\t// Current bytes encrypted\n uchar\tnews[1024];\t\t// New string", "\n /*\n * Write an encrypted string...\n */", " putc('<', out);\n encrypt_init();", " for (len = strlen((char *)s); len > 0; len -= bytes, s += bytes)\n {\n if (len > (int)sizeof(news))\n bytes = (int)sizeof(news);\n else\n bytes = len;", " rc4_encrypt(&encrypt_state, s, news, (size_t)bytes);", " for (i = 0; i < bytes; i ++)\n fprintf(out, \"%02x\", news[i]);\n }", " putc('>', out);\n }\n else\n {\n uchar nbsp = 160;\t\t\t// Non-breaking space char", " if (compress)\n flate_write(out, (uchar *)\"(\", 1);\n else\n putc('(', out);", " if (_htmlUTF8)\n nbsp = _htmlCharacters[160];", " while (*s != '\\0')\n {\n if (*s == nbsp)\n {\n /* &nbsp; */\n\tif (compress)\n\t flate_write(out, (uchar *)\" \", 1);\n\telse\n\t putc(' ', out);\n }\n else if (*s < 32 || *s > 126)\n {\n\tif (compress)\n\t flate_printf(out, \"\\\\%o\", *s);\n\telse\n\t fprintf(out, \"\\\\%o\", *s);\n }\n else if (compress)\n {\n\tif (*s == '(' || *s == ')' || *s == '\\\\')\n\t flate_write(out, (uchar *)\"\\\\\", 1);", "\tflate_write(out, s, 1);\n }\n else\n {\n\tif (*s == '(' || *s == ')' || *s == '\\\\')\n\t putc('\\\\', out);", "\tputc(*s, out);\n }", " s ++;\n }", " if (compress)\n flate_write(out, (uchar *)\")\", 1);\n else\n putc(')', out);\n }\n}", "\n/*\n * 'write_text()' - Write a text entity.\n */", "static void\nwrite_text(FILE *out,\t/* I - Output file */\n render_t *r)\t\t/* I - Text entity */\n{\n uchar\t*ptr;\t\t\t/* Pointer into text */", "\n // Quick optimization - don't output spaces...\n for (ptr = r->data.text.buffer; *ptr; ptr ++)\n if (!isspace(*ptr) && *ptr != 0xa0)\n break;", " if (!*ptr)\n return;", " // Not just whitespace - send it out...\n set_color(out, r->data.text.rgb);\n set_font(out, r->data.text.typeface, r->data.text.style, r->data.text.size);\n set_pos(out, r->x, r->y);", " if (PSLevel > 0)\n {\n if (r->data.text.spacing > 0.0f)\n fprintf(out, \" %.3f\", r->data.text.spacing);\n }\n else if (r->data.text.spacing != render_spacing)\n flate_printf(out, \" %.3f Tc\", render_spacing = r->data.text.spacing);", " write_string(out, r->data.text.buffer, PSLevel == 0);", " if (PSLevel > 0)\n {\n if (r->data.text.spacing > 0.0f)\n fputs(\"J\\n\", out);\n else\n fputs(\"S\\n\", out);\n }\n else\n flate_puts(\"Tj\\n\", out);", " render_x += r->width;\n}", "\n/*\n * 'write_trailer()' - Write the file trailer.\n */", "static void\nwrite_trailer(FILE *out,\t\t/* I - Output file */\n int num_file_pages,\t/* I - Number of pages in file */\n\t uchar *lang)\t\t/* I - Language */\n{\n int\t\ti, j, k,\t\t/* Looping vars */\n\t\ttype,\t\t\t/* Type of number */\n\t\toffset,\t\t\t/* Offset to xref table in PDF file */\n\t\tstart;\t\t\t/* Start page number */\n page_t\t*page;\t\t\t/* Start page of chapter */\n char\t\tprefix[64],\t\t/* Prefix string */\n\t\t*prefptr;\t\t/* Pointer into prefix string */\n static const char *modes[] =\t\t/* Page modes */\n\t\t{\n\t\t \"UseNone\",\n\t\t \"UseOutlines\",\n\t\t \"FullScreen\"\n\t\t};\n static const char *layouts[] =\t/* Page layouts */\n\t\t{\n\t\t \"SinglePage\",\n\t\t \"OneColumn\",\n\t\t \"TwoColumnLeft\",\n\t\t \"TwoColumnRight\"\n\t\t};", "\n if (PSLevel > 0)\n {\n /*\n * PostScript...\n */", " fputs(\"%%Trailer\\n\", out);\n if (num_file_pages > 0)\n fprintf(out, \"%%%%Pages: %d\\n\", num_file_pages);", " fputs(\"%%EOF\\n\", out);\n }\n else\n {\n /*\n * PDF...\n */", " root_object = pdf_start_object(out);", " fputs(\"/Type/Catalog\", out);\n fprintf(out, \"/Pages %d 0 R\", pages_object);", " if (PDFVersion >= 12)\n {\n if (names_object)\n fprintf(out, \"/Names %d 0 R\", names_object);", " fprintf(out, \"/PageLayout/%s\", layouts[PDFPageLayout]);\n }", " if (lang)\n fprintf(out, \"/Lang(%s)\", (char *)lang);", " if (outline_object > 0)\n fprintf(out, \"/Outlines %d 0 R\", outline_object);", " switch (PDFFirstPage)\n {\n case PDF_PAGE_1 :\n if (TitlePage)\n\t {\n fprintf(out, \"/OpenAction[%d 0 R/XYZ null null 0]\",\n pages_object + 1);\n break;\n\t }\n break;\n case PDF_TOC :\n if (TocLevels > 0)\n\t {\n fprintf(out, \"/OpenAction[%d 0 R/XYZ null null 0]\",\n pages_object + 2 * chapter_outstarts[0] + 1);\n\t break;\n\t }\n break;\n case PDF_CHAPTER_1 :\n fprintf(out, \"/OpenAction[%d 0 R/XYZ null null 0]\",\n pages_object + 2 * chapter_outstarts[1] + 1);\n break;\n }", " fprintf(out, \"/PageMode/%s\", modes[PDFPageMode]);", " if (PDFVersion > 12 && NumberUp == 1)\n {\n // Output the PageLabels tree...\n fputs(\"/PageLabels<</Nums[\", out);", " for (i = 0; i < chapter_starts[1]; i ++)\n {\n fprintf(out, \"%d<</P\", i);\n if (i & 1)\n\t write_string(out, (uchar *)\"eltit\", 0);\n\telse\n\t write_string(out, (uchar *)\"title\", 0);\n\tfputs(\">>\", out);\n }", " if (TocLevels > 0 && OutputType == OUTPUT_BOOK)\n {\n type = 'r';", " for (j = 0; j < 3; j ++)\n\t if ((TocHeader[j] && strstr(TocHeader[j], \"$PAGE(1)\")) ||\n\t (TocFooter[j] && strstr(TocFooter[j], \"$PAGE(1)\")))\n\t type = 'D';\n\t else if ((TocHeader[j] && strstr(TocHeader[j], \"$PAGE(I)\")) ||\n\t (TocFooter[j] && strstr(TocFooter[j], \"$PAGE(I)\")))\n\t type = 'R';\n\t else if ((TocHeader[j] && strstr(TocHeader[j], \"$PAGE(a)\")) ||\n\t (TocFooter[j] && strstr(TocFooter[j], \"$PAGE(a)\")))\n\t type = 'a';\n\t else if ((TocHeader[j] && strstr(TocHeader[j], \"$PAGE(A)\")) ||\n\t (TocFooter[j] && strstr(TocFooter[j], \"$PAGE(A)\")))\n\t type = 'A';", " fprintf(out, \"%d<</S/%c>>\", i, type);", " i += chapter_ends[0] - chapter_starts[0] + 1;\n }", " for (j = 1; j <= TocDocCount; j ++)\n {\n if (chapter_starts[j] < 0)\n continue;", " page = pages + chapter_starts[j];\n\tstart = chapter_starts[j] - chapter_starts[1] + 1;\n\ttype = 'D';", " prefix[0] = '\\0';", "\tfor (k = 0; k < 3; k ++)\n\t{\n\t if (page->header[k] && strstr((char *)page->header[k], \"PAGE\"))\n\t strlcpy(prefix, (char *)page->header[k], sizeof(prefix));\n\t else if (page->footer[k] && strstr((char *)page->footer[k], \"PAGE\"))\n\t strlcpy(prefix, (char *)page->footer[k], sizeof(prefix));", "\t if ((page->header[k] && strstr((char *)page->header[k], \"PAGE(i)\")) ||\n\t (page->footer[k] && strstr((char *)page->footer[k], \"PAGE(i)\")))\n\t type = 'r';\n\t else if ((page->header[k] && strstr((char *)page->header[k], \"PAGE(I)\")) ||\n\t (page->footer[k] && strstr((char *)page->footer[k], \"PAGE(I)\")))\n\t type = 'R';\n\t else if ((page->header[k] && strstr((char *)page->header[k], \"PAGE(a)\")) ||\n\t (page->footer[k] && strstr((char *)page->footer[k], \"PAGE(a)\")))\n\t type = 'a';\n\t else if ((page->header[k] && strstr((char *)page->header[k], \"PAGE(A)\")) ||\n\t (page->footer[k] && strstr((char *)page->footer[k], \"PAGE(A)\")))\n\t type = 'A';", "\t if ((page->header[k] && strstr((char *)page->header[k], \"$CHAPTERPAGE\")) ||\n\t (page->footer[k] && strstr((char *)page->footer[k], \"$CHAPTERPAGE\")))\n\t start = 1;\n }", " if ((prefptr = strstr(prefix, \"$PAGE\")) == NULL)\n\t prefptr = strstr(prefix, \"$CHAPTERPAGE\");\n\tfprintf(out, \"%d<</S/%c/St %d\", i, type, start);\n\tif (prefptr)\n\t{\n\t *prefptr = '\\0';\n\t fputs(\"/P\", out);\n\t write_string(out, (uchar *)prefix, 0);\n\t}\n\tfputs(\">>\", out);", " i += chapter_ends[j] - chapter_starts[j] + 1;\n }", " fputs(\"]>>\", out);\n }", " pdf_end_object(out);", " offset = ftell(out);", " fputs(\"xref\\n\", out);\n fprintf(out, \"0 %d \\n\", (int)num_objects + 1);\n fputs(\"0000000000 65535 f \\n\", out);\n for (i = 1; i <= (int)num_objects; i ++)\n fprintf(out, \"%010d 00000 n \\n\", objects[i]);", " fputs(\"trailer\\n\", out);\n fputs(\"<<\", out);\n fprintf(out, \"/Size %d\", (int)num_objects + 1);\n fprintf(out, \"/Root %d 0 R\", root_object);\n fprintf(out, \"/Info %d 0 R\", info_object);\n fputs(\"/ID[<\", out);\n for (i = 0; i < 16; i ++)\n fprintf(out, \"%02x\", file_id[i]);\n fputs(\"><\", out);\n for (i = 0; i < 16; i ++)\n fprintf(out, \"%02x\", file_id[i]);\n fputs(\">]\", out);", " if (Encryption)\n fprintf(out, \"/Encrypt %d 0 R\", encrypt_object);", " fputs(\">>\\n\", out);\n fputs(\"startxref\\n\", out);\n fprintf(out, \"%d\\n\", offset);\n fputs(\"%%EOF\\n\", out);\n }\n}", "\n/*\n * 'write_type1()' - Write an embedded Type 1 font.\n */", "static int\t\t\t\t/* O - Object number */\nwrite_type1(FILE *out,\t\t/* I - File to write to */\n typeface_t typeface,\t/* I - Typeface */\n\t style_t style)\t\t/* I - Style */\n{\n char\t\tfilename[1024];\t\t/* PFA filename */\n FILE\t\t*fp;\t\t\t/* PFA file */\n int\t\tch;\t\t\t/* Character value */\n int\t\twidth;\t\t\t/* Width value */\n char\t\tglyph[64],\t\t/* Glyph name */\n\t\tline[1024],\t\t/* Line from AFM file */\n\t\t*lineptr,\t\t/* Pointer into line */\n\t\t*dataptr;\t\t/* Pointer for data */\n int\t\tascent,\t\t\t/* Ascent above baseline */\n\t\tcap_height,\t\t/* Ascent of CAPITALS */\n\t\tx_height,\t\t/* Ascent of lowercase */\n\t\tdescent,\t\t/* Decent below baseline */\n\t\tbbox[4],\t\t/* Bounding box */\n\t\titalic_angle;\t\t/* Angle for italics */\n int\t\twidths[256];\t\t/* Character widths */\n int\t\tlength1,\t\t/* Length1 value for font */\n\t\tlength2,\t\t/* Length2 value for font */\n\t\tlength3;\t\t/* Length3 value for font */\n static int\ttflags[] =\t\t/* PDF typeface flags */\n\t\t{\n\t\t 33,\t\t\t/* Courier */\n\t\t 34,\t\t\t/* Times-Roman */\n\t\t 32,\t\t\t/* Helvetica */\n\t\t 33,\t\t\t/* Monospace */\n\t\t 34,\t\t\t/* Serif */\n\t\t 32,\t\t\t/* Sans */\n\t\t 4,\t\t\t/* Symbol */\n\t\t 4\t\t\t/* Dingbats */\n\t\t};\n static int\tsflags[] =\t\t/* PDF style flags */\n\t\t{\n\t\t 0,\t\t\t/* Normal */\n\t\t 0,\t\t\t/* Bold */\n\t\t 64,\t\t\t/* Italic */\n\t\t 64\t\t\t/* Bold-Italic */\n\t\t};", "\n /*\n * This function writes a Type1 font, either as an object for PDF\n * output or as an in-line font in PostScript output. This is useful\n * because the Type1 fonts that Adobe ships typically do not include\n * the full set of characters required by some of the ISO character\n * sets.\n */", " /*\n * Try to open the PFA file for the Type1 font...\n */", " snprintf(filename, sizeof(filename), \"%s/fonts/%s.pfa\", _htmlData,\n _htmlFonts[typeface][style]);\n if ((fp = fopen(filename, \"r\")) == NULL)\n {\n#ifndef DEBUG\n progress_error(HD_ERROR_FILE_NOT_FOUND,\n \"Unable to open font file %s!\", filename);\n#endif /* !DEBUG */\n return (0);\n }", " /*\n * Write the font (object)...\n */", " if (PSLevel)\n {\n /*\n * Embed a Type1 font in the PostScript output...\n */", " fprintf(out, \"%%%%BeginResource: font %s\\n\", _htmlFonts[typeface][style]);", " line[0] = '\\0';", " while (fgets(line, sizeof(line), fp) != NULL)\n fputs(line, out);", " if (line[strlen(line) - 1] != '\\n')\n fputs(\"\\n\", out);", " fputs(\"%%EndResource\\n\", out);", " fclose(fp);\n }\n else\n {\n /*\n * Embed a Type1 font object in the PDF output...\n */", " length1 = 0;\n length2 = 0;\n length3 = 0;", " while (fgets(line, sizeof(line), fp) != NULL)\n {\n length1 += strlen(line);\n if (strstr(line, \"currentfile eexec\") != NULL)\n break;\n }", " while (fgets(line, sizeof(line), fp) != NULL)\n {\n if (!strcmp(line, \"00000000000000000000000000000000\"\n \"00000000000000000000000000000000\\n\"))\n break;", " length2 += (strlen(line) - 1) / 2;\n }", " length3 = strlen(line);\n while (fgets(line, sizeof(line), fp) != NULL)\n length3 += strlen(line);", " rewind(fp);", " pdf_start_object(out);\n fprintf(out, \"/Length1 %d\", length1);\n fprintf(out, \"/Length2 %d\", length2);\n fprintf(out, \"/Length3 %d\", length3);\n if (Compression)\n fputs(\"/Filter/FlateDecode\", out);\n pdf_start_stream(out);\n flate_open_stream(out);", " while (fgets(line, sizeof(line), fp) != NULL)\n {\n flate_puts(line, out);", " if (strstr(line, \"currentfile eexec\") != NULL)\n break;\n }", " while (fgets(line, sizeof(line), fp) != NULL)\n {\n if (!strcmp(line, \"00000000000000000000000000000000\"\n \"00000000000000000000000000000000\\n\"))\n break;", " for (lineptr = line, dataptr = line; isxdigit(*lineptr); lineptr += 2)\n {\n if (isdigit(lineptr[0]))\n\t ch = (lineptr[0] - '0') << 4;\n\telse\n\t ch = (tolower(lineptr[0] & 255) - 'a' + 10) << 4;", " if (isdigit(lineptr[1]))\n\t ch |= lineptr[1] - '0';\n\telse\n\t ch |= tolower(lineptr[1] & 255) - 'a' + 10;", " *dataptr++ = (char)ch;\n }", " flate_write(out, (uchar *)line, dataptr - line);\n }", " flate_puts(line, out);\n while (fgets(line, sizeof(line), fp) != NULL)\n flate_puts(line, out);", " flate_close_stream(out);", " pdf_end_object(out);", " fclose(fp);", " /*\n * Try to open the AFM file for the Type1 font...\n */", " snprintf(filename, sizeof(filename), \"%s/fonts/%s.afm\", _htmlData,\n _htmlFonts[typeface][style]);\n if ((fp = fopen(filename, \"r\")) == NULL)\n {\n#ifndef DEBUG\n progress_error(HD_ERROR_FILE_NOT_FOUND,\n \"Unable to open font width file %s!\", filename);\n#endif /* !DEBUG */\n return (0);\n }", " /*\n * Set the default values (Courier)...\n */", " for (ch = 0; ch < 256; ch ++)\n widths[ch] = 600;", " ascent = 629;\n cap_height = 562;\n x_height = 426;\n descent = -157;\n bbox[0] = -28;\n bbox[1] = -250;\n bbox[2] = 628;\n bbox[3] = 805;\n italic_angle = 0;", " /*\n * Read the AFM file...\n */", " while (fgets(line, sizeof(line), fp) != NULL)\n {\n if (strncmp(line, \"ItalicAngle \", 12) == 0)\n\titalic_angle = atoi(line + 12);\n else if (strncmp(line, \"FontBBox \", 9) == 0)\n\tsscanf(line + 9, \"%d%d%d%d\", bbox + 0, bbox + 1, bbox + 2, bbox + 3);\n else if (strncmp(line, \"CapHeight \", 10) == 0)\n\tcap_height = atoi(line + 10);\n else if (strncmp(line, \"XHeight \", 8) == 0)\n\tx_height = atoi(line + 8);\n else if (strncmp(line, \"Ascender \", 9) == 0)\n\tascent = atoi(line + 9);\n else if (strncmp(line, \"Descender \", 10) == 0)\n\tdescent = atoi(line + 10);\n else if (strncmp(line, \"C \", 2) == 0)\n {\n\tif (typeface < TYPE_SYMBOL)\n\t{\n\t /*\n\t * Handle encoding of Courier, Times, and Helvetica using\n\t * assigned charset...\n\t */", "\t if (sscanf(line, \"%*s%*s%*s%*s%d%*s%*s%63s\", &width, glyph) != 2)\n\t continue;", "\t for (ch = 0; ch < 256; ch ++)\n\t if (_htmlGlyphs[ch] && strcmp(_htmlGlyphs[ch], glyph) == 0)\n\t break;", "\t if (ch < 256)\n\t widths[ch] = width;\n\t}\n\telse\n\t{\n\t /*\n\t * Symbol font uses its own encoding...\n\t */", "\t if (sscanf(line, \"%*s%d%*s%*s%d\", &ch, &width) != 2)\n\t continue;", "\t if (ch >= 0 && ch < 256)\n\t widths[ch] = width;\n\t}\n }\n }", " fclose(fp);", " /*\n * Write the font descriptor...\n */", " pdf_start_object(out);\n fputs(\"/Type/FontDescriptor\", out);\n fprintf(out, \"/Ascent %d\", ascent);\n fprintf(out, \"/Descent %d\", descent);\n fprintf(out, \"/CapHeight %d\", cap_height);\n fprintf(out, \"/XHeight %d\", x_height);\n fprintf(out, \"/FontBBox[%d %d %d %d]\", bbox[0], bbox[1], bbox[2], bbox[3]);\n fprintf(out, \"/ItalicAngle %d\", italic_angle);\n fprintf(out, \"/StemV %d\", widths['v']);\n fprintf(out, \"/Flags %d\", tflags[typeface] | sflags[style]);\n fprintf(out, \"/FontName/%s\", _htmlFonts[typeface][style]);\n fprintf(out, \"/FontFile %d 0 R\", (int)num_objects - 1);\n pdf_end_object(out);", " /*\n * Write the character widths...\n */", " pdf_start_object(out, 1);\n fprintf(out, \"%d\", widths[0]);\n for (ch = 1; ch < 256; ch ++)\n fprintf(out, \" %d\", widths[ch]);\n pdf_end_object(out);\n }", " /*\n * Return the font descriptor...\n */", " return (num_objects - 1);\n}", "\n/*\n * 'write_utf16()' - Write a UTF-16 string...\n */", "static void\nwrite_utf16(FILE *out,\t\t\t// I - File to write to\n uchar *s)\t\t\t// I - String to write\n{\n uchar *sptr;\t\t\t\t// Pointer into string", "\n /*\n * We start by checking to see if the string is composed only of\n * ASCII characters; if so, we can just write a normal string...\n */", " for (sptr = s; *sptr && !(*sptr & 0x80); sptr ++);\n if (!*sptr)\n {\n /*\n * Write an ASCII string...\n */", " write_string(out, s, 0);\n }\n else if (Encryption)\n {\n /*\n * Convert the string to Unicode and encrypt...\n */", " int\t\tch;\t\t\t// Character value\n uchar\tunicode[2],\t\t// Unicode character\n\t\tenicode[2];\t\t// Encrypted unicode character", "\n putc('<', out);\n encrypt_init();", " unicode[0] = 0xfe;\t\t\t// Start with BOM\n unicode[1] = 0xff;", " rc4_encrypt(&encrypt_state, unicode, enicode, 2);", " fprintf(out, \"%02x%02x\", enicode[0], enicode[1]);", " for (sptr = s; *sptr; sptr ++)\n {\n ch = _htmlUnicode[*sptr];\n unicode[0] = (uchar)(ch >> 8);\n unicode[1] = (uchar)ch;", " rc4_encrypt(&encrypt_state, unicode, enicode, 2);", " fprintf(out, \"%02x%02x\", enicode[0], enicode[1]);\n }", " putc('>', out);\n }\n else\n {\n /*\n * Convert the string to Unicode...\n */", " fputs(\"<feff\", out);\t\t// Start with BOM\n for (sptr = s; *sptr; sptr ++)\n fprintf(out, \"%04x\", _htmlUnicode[*sptr]);\n putc('>', out);\n }\n}", "\n/*\n * 'encrypt_init()' - Initialize the RC4 encryption context for the current\n * object.\n */", "static void\nencrypt_init(void)\n{\n int\t\ti;\t\t\t/* Looping var */\n uchar\t\tdata[21],\t\t/* Key data */\n\t\t*dataptr;\t\t/* Pointer to key data */\n md5_state_t\tmd5;\t\t\t/* MD5 state */\n md5_byte_t\tdigest[16];\t\t/* MD5 digest value */", "\n /*\n * Compute the key data for the MD5 hash.\n */", " for (i = 0, dataptr = data; i < encrypt_len; i ++)\n *dataptr++ = encrypt_key[i];", " *dataptr++ = (uchar)num_objects;\n *dataptr++ = (uchar)(num_objects >> 8);\n *dataptr++ = (uchar)(num_objects >> 16);\n *dataptr++ = 0;\n *dataptr++ = 0;", " /*\n * Hash it...\n */", " md5_init(&md5);\n md5_append(&md5, data, encrypt_len + 5);\n md5_finish(&md5, digest);", " /*\n * Initialize the RC4 context using the first N+5 bytes of the digest...\n */", " if (encrypt_len > 11)\n rc4_init(&encrypt_state, digest, 16);\n else\n rc4_init(&encrypt_state, digest, (size_t)(encrypt_len + 5));\n}", "\n/*\n * 'flate_open_stream()' - Open a deflated output stream.\n */", "static void\nflate_open_stream(FILE *out)\t\t/* I - Output file */\n{\n if (Encryption && !PSLevel)\n encrypt_init();", " if (!Compression)\n return;", " compressor_active = 1;\n compressor.zalloc = (alloc_func)0;\n compressor.zfree = (free_func)0;\n compressor.opaque = (voidpf)0;", " deflateInit(&compressor, Compression);", " compressor.next_out = (Bytef *)comp_buffer;\n compressor.avail_out = sizeof(comp_buffer);\n}", "\n/*\n * 'flate_close_stream()' - Close a deflated output stream.\n */", "static void\nflate_close_stream(FILE *out)\t\t/* I - Output file */\n{\n int\tstatus;\t\t\t\t/* Deflate status */", "\n if (!Compression)\n {\n#ifdef HTMLDOC_ASCII85\n if (PSLevel)\n ps_ascii85(out, (uchar *)\"\", 0, 1);\n#endif // HTMLDOC_ASCII85", " return;\n }", " while ((status = deflate(&compressor, Z_FINISH)) != Z_STREAM_END)\n {\n if (status < Z_OK && status != Z_BUF_ERROR)\n {\n progress_error(HD_ERROR_OUT_OF_MEMORY, \"deflate() failed (%d)\", status);\n return;\n }", " if (PSLevel)\n#ifdef HTMLDOC_ASCII85\n ps_ascii85(out, comp_buffer,\n (uchar *)compressor.next_out - (uchar *)comp_buffer);\n#else\n ps_hex(out, comp_buffer,\n (uchar *)compressor.next_out - (uchar *)comp_buffer);\n#endif // HTMLDOC_ASCII85\n else\n {\n if (Encryption)\n rc4_encrypt(&encrypt_state, comp_buffer, comp_buffer,\n\t (uchar *)compressor.next_out - (uchar *)comp_buffer);", " fwrite(comp_buffer, (size_t)((uchar *)compressor.next_out - (uchar *)comp_buffer), 1, out);\n }", " compressor.next_out = (Bytef *)comp_buffer;\n compressor.avail_out = sizeof(comp_buffer);\n }", " if ((uchar *)compressor.next_out > (uchar *)comp_buffer)\n {\n if (PSLevel)\n#ifdef HTMLDOC_ASCII85\n ps_ascii85(out, comp_buffer,\n (uchar *)compressor.next_out - (uchar *)comp_buffer);\n#else\n ps_hex(out, comp_buffer,\n (uchar *)compressor.next_out - (uchar *)comp_buffer);\n#endif // HTMLDOC_ASCII85\n else\n {\n if (Encryption)\n rc4_encrypt(&encrypt_state, comp_buffer, comp_buffer,\n\t (uchar *)compressor.next_out - (uchar *)comp_buffer);", " fwrite(comp_buffer, (size_t)((uchar *)compressor.next_out - (uchar *)comp_buffer), 1, out);\n }", " }", " deflateEnd(&compressor);", " compressor_active = 0;", "#ifdef HTMLDOC_ASCII85\n if (PSLevel)\n ps_ascii85(out, (uchar *)\"\", 0, 1);\n#else\n if (PSLevel)\n {\n // End of data marker...\n fputs(\">\\n\", out);\n }\n#endif // HTMLDOC_ASCII85\n}", "\n/*\n * 'flate_puts()' - Write a character string to a compressed stream.\n */", "static void\nflate_puts(const char *s,\t\t/* I - String to write */\n FILE *out)\t\t/* I - Output file */\n{\n flate_write(out, (uchar *)s, strlen(s));\n}", "\n/*\n * 'flate_printf()' - Write a formatted character string to a compressed stream.\n */", "static void\nflate_printf(FILE *out,\t\t/* I - Output file */\n const char *format,\t/* I - Format string */\n ...)\t\t\t/* I - Additional args as necessary */\n{\n int\t\tlength;\t\t\t/* Length of output string */\n char\t\tbuf[10240];\t\t/* Output buffer */\n va_list\tap;\t\t\t/* Argument pointer */", "\n va_start(ap, format);\n length = vsnprintf(buf, sizeof(buf), format, ap);\n va_end(ap);", " flate_write(out, (uchar *)buf, length);\n}", "\n/*\n * 'flate_write()' - Write data to a compressed stream.\n */", "static void\nflate_write(FILE *out,\t\t\t/* I - Output file */\n uchar *buf,\t\t\t/* I - Buffer */\n int length,\t\t/* I - Number of bytes to write */\n\t int flush)\t\t/* I - Flush when writing data? */\n{\n int\tstatus;\t\t\t\t/* Deflate status */", "\n if (compressor_active)\n {\n compressor.next_in = buf;\n compressor.avail_in = (unsigned)length;", " while (compressor.avail_in > 0)\n {\n if (compressor.avail_out < (int)(sizeof(comp_buffer) / 8))\n {\n\tif (PSLevel)\n#ifdef HTMLDOC_ASCII85\n\t ps_ascii85(out, comp_buffer,\n (uchar *)compressor.next_out - (uchar *)comp_buffer);\n#else\n\t ps_hex(out, comp_buffer,\n (uchar *)compressor.next_out - (uchar *)comp_buffer);\n#endif // HTMLDOC_ASCII85\n\telse\n\t{\n\t if (Encryption)\n rc4_encrypt(&encrypt_state, comp_buffer, comp_buffer,\n\t \t(uchar *)compressor.next_out - (uchar *)comp_buffer);", "\t fwrite(comp_buffer, (size_t)((uchar *)compressor.next_out - (uchar *)comp_buffer), 1, out);\n\t}", "\tcompressor.next_out = (Bytef *)comp_buffer;\n\tcompressor.avail_out = sizeof(comp_buffer);\n }", " status = deflate(&compressor, flush ? Z_FULL_FLUSH : Z_NO_FLUSH);", " if (status < Z_OK && status != Z_BUF_ERROR)\n {\n\tprogress_error(HD_ERROR_OUT_OF_MEMORY, \"deflate() failed (%d)\", status);\n\treturn;\n }", " flush = 0;\n }\n }\n else if (Encryption && !PSLevel)\n {\n int\t\ti,\t\t// Looping var\n\t\tbytes;\t\t// Number of bytes to encrypt/write\n uchar\tnewbuf[1024];\t// New encrypted data buffer", "\n for (i = 0; i < length; i += sizeof(newbuf))\n {\n if ((bytes = length - i) > (int)sizeof(newbuf))\n bytes = sizeof(newbuf);", " rc4_encrypt(&encrypt_state, buf + i, newbuf, (size_t)bytes);\n fwrite(newbuf, (size_t)bytes, 1, out);\n }\n }\n else if (PSLevel)\n#ifdef HTMLDOC_ASCII85\n ps_ascii85(out, buf, length);\n#else\n ps_hex(out, buf, length);\n#endif // HTMLDOC_ASCII85\n else\n fwrite(buf, (size_t)length, 1, out);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [5, 1322], "buggy_code_start_loc": [4, 1321], "filenames": ["CHANGES.md", "htmldoc/ps-pdf.cxx"], "fixing_code_end_loc": [6, 1322], "fixing_code_start_loc": [4, 1321], "message": "A flaw was found in htmldoc before v1.9.12. Heap buffer overflow in pspdf_prepare_outpages(), in ps-pdf.cxx may lead to execute arbitrary code and denial of service.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:htmldoc_project:htmldoc:*:*:*:*:*:*:*:*", "matchCriteriaId": "8D1CE1F4-17A1-430E-9C8B-0CE88A07514B", "versionEndExcluding": "1.9.12", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:htmldoc_project:htmldoc:1.9.12:*:*:*:*:*:*:*", "matchCriteriaId": "645554AD-DA7C-4B11-864A-89F423B08291", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A flaw was found in htmldoc before v1.9.12. Heap buffer overflow in pspdf_prepare_outpages(), in ps-pdf.cxx may lead to execute arbitrary code and denial of service."}, {"lang": "es", "value": "Se ha encontrado un fallo en htmldoc versiones anteriores av1.9.12. Un desbordamiento del b\u00fafer de la pila en la funci\u00f3n pspdf_prepare_outpages(), en el archivo ps-pdf.cxx puede conllevar a una ejecuci\u00f3n de c\u00f3digo arbitrario y a una denegaci\u00f3n de servicio"}], "evaluatorComment": null, "id": "CVE-2021-23165", "lastModified": "2022-03-22T17:01:58.600", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 10.0, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-03-16T15:15:10.157", "references": [{"source": "secalert@redhat.com", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1967014"}, {"source": "secalert@redhat.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/michaelrsweet/htmldoc/commit/6e8a95561988500b5b5ae4861b3b0cbf4fba517f"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://github.com/michaelrsweet/htmldoc/commit/6e8a95561988500b5b5ae4861b3b0cbf4fba517f.patch"}, {"source": "secalert@redhat.com", "tags": ["Exploit", "Issue Tracking", "Third Party Advisory"], "url": "https://github.com/michaelrsweet/htmldoc/issues/413"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-787"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-122"}], "source": "secalert@redhat.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/michaelrsweet/htmldoc/commit/6e8a95561988500b5b5ae4861b3b0cbf4fba517f"}, "type": "CWE-787"}
201
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * PostScript + PDF output routines for HTMLDOC, a HTML document processing\n * program.\n *\n * Just in case you didn't notice it, this file is too big; it will be\n * broken into more manageable pieces once we make all of the output\n * \"drivers\" into classes...\n *\n * Copyright © 2011-2021 by Michael R Sweet.\n * Copyright © 1997-2010 by Easy Software Products. All rights reserved.\n *\n * This program is free software. Distribution and use rights are outlined in\n * the file \"COPYING\".\n */", "/*\n * Include necessary headers.\n */", "/*\n * The GCC compiler on HP-UX has a nasty habit of incorrectly \"fixing\"\n * the vmtypes.h header file provided with HP-UX. The following\n * conditional magic makes sure that \"page_t\" (which we use in our\n * code) is not defined...\n */", "#ifdef __hpux\n# define page_t\thpux_page_t\n#endif // __hpux", "/*#define DEBUG*/\n#include \"htmldoc.h\"\n#include \"markdown.h\"\n#include \"md5-private.h\"\n#define md5_append _cupsMD5Append\n#define md5_finish _cupsMD5Finish\n#define md5_init _cupsMD5Init\ntypedef unsigned char md5_byte_t;\n#define md5_state_t _cups_md5_state_t\n#include \"rc4.h\"\n#include <stdarg.h>\n#include <ctype.h>\n#include <time.h>\n#include <math.h>", "#ifdef WIN32\n# include <io.h>\n#else\n# include <unistd.h>\n#endif // WIN32", "#include <fcntl.h>", "#include <zlib.h>", "extern \"C\" {\t\t/* Workaround for JPEG header problems... */\n#include <jpeglib.h>\t/* JPEG/JFIF image definitions */\n}", "#ifdef __hpux\n# undef page_t\n#endif // __hpux", "\n/*\n * Output options...\n */", "#define HTMLDOC_ASCII85\n//#define HTMLDOC_INTERPOLATION\n#define HTMLDOC_PRODUCER \"htmldoc \" SVERSION \" Copyright 2011-2019 by Michael R Sweet\"", "\n/*\n * Constants...\n */", "#define RENDER_TEXT\t0\t\t/* Text fragment */\n#define RENDER_IMAGE\t1\t\t/* Image */\n#define RENDER_BOX\t2\t\t/* Box */\n#define RENDER_LINK\t3\t\t/* Hyperlink */\n#define RENDER_BG\t4\t\t/* Background image */", "\n/*\n * Structures...\n */", "typedef struct render_str\t\t/**** Render entity structure ****/\n{\n struct render_str\t*prev;\t\t/* Previous rendering entity */\n struct render_str\t*next;\t\t/* Next rendering entity */\n int\ttype;\t\t\t\t/* Type of entity */\n float\tx,\t\t\t\t/* Position in points */\n\ty,\t\t\t\t/* ... */\n\twidth,\t\t\t\t/* Size in points */\n\theight;\t\t\t\t/* ... */\n union\n {\n struct\n {\n int\ttypeface,\t\t/* Typeface for text */\n\t\tstyle;\t\t\t/* Style of text */\n float\tsize;\t\t\t/* Size of text in points */\n float\tspacing;\t\t/* Inter-character spacing */\n float\trgb[3];\t\t\t/* Color of text */\n uchar\tbuffer[1];\t\t/* String buffer */\n } \ttext;\n image_t\t*image;\t\t\t/* Image pointer */\n float\tbox[3];\t\t\t/* Box color */\n uchar\tlink[1];\t\t/* Link URL */\n }\tdata;\n} render_t;", "typedef struct\t\t\t\t/**** Named link position structure */\n{\n short\t\tpage,\t\t\t/* Page # */\n\t\ttop;\t\t\t/* Top position */\n uchar\t\tname[124];\t\t/* Reference name */\n} link_t;", "typedef struct\t\t\t\t//// Page information\n{\n int\t\twidth,\t\t\t// Width of page in points\n\t\tlength,\t\t\t// Length of page in points\n\t\tleft,\t\t\t// Left margin in points\n\t\tright,\t\t\t// Right margin in points\n\t\ttop,\t\t\t// Top margin in points\n\t\tbottom,\t\t\t// Bottom margin in points\n\t\tduplex,\t\t\t// Duplex this page?\n\t\tlandscape;\t\t// Landscape orientation?\n render_t\t*start,\t\t\t// First render element\n\t\t*end;\t\t\t// Last render element\n uchar\t\t*url, // URL/file\n *chapter,\t\t// Chapter text\n\t\t*heading;\t\t// Heading text\n tree_t\t*headnode;\t\t// Heading node\n uchar\t\t*header[3],\t\t// Headers for regular pages\n\t\t*header1[3],\t\t// Headers for first pages\n\t\t*footer[3];\t\t// Footers for all pages\n char\t\tmedia_color[64],\t// Media color\n\t\tmedia_type[64];\t\t// Media type\n int\t\tmedia_position;\t\t// Media position\n char\t\tpage_text[64];\t\t// Page number for TOC\n image_t\t*background_image;\t// Background image\n float\t\tbackground_color[3];\t// Background color", " // Number-up support\n int\t\tnup;\t\t\t// Number up pages\n int\t\toutpage;\t\t// Output page #\n float\t\toutmatrix[2][3];\t// Transform matrix\n} page_t;", "typedef struct\t\t\t\t//// Output page info\n{\n int\t\tnup;\t\t\t// Number up pages\n int\t\tpages[16];\t\t// Pages on this output page\n int\t\tannot_object;\t\t// Annotation object\n} outpage_t;", "\n/*\n * Local globals...\n */", "static time_t\tdoc_time;\t\t// Current time\nstatic struct tm doc_date;\t\t// Current date", "static uchar *current_url = NULL;\nstatic int\ttitle_page;\nstatic int\tchapter,\n\t\tchapter_outstarts[MAX_CHAPTERS],\n\t\tchapter_outends[MAX_CHAPTERS],\n\t\tchapter_starts[MAX_CHAPTERS],\n\t\tchapter_ends[MAX_CHAPTERS];", "static size_t\tnum_headings = 0,\n\t\talloc_headings = 0;\nstatic int\t*heading_pages = NULL,\n\t\t*heading_tops = NULL;", "static size_t\tnum_pages = 0,\n\t\talloc_pages = 0;\nstatic page_t\t*pages = NULL;\nstatic tree_t\t*current_heading;", "static size_t\tnum_outpages = 0;\nstatic outpage_t *outpages = NULL;", "static size_t\tnum_links = 0,\n\t\talloc_links = 0;\nstatic link_t\t*links = NULL;", "static uchar\tlist_types[16];\nstatic int\tlist_values[16];", "static char\tstdout_filename[256];\nstatic size_t\tnum_objects = 0,\n\t\talloc_objects = 0;\nstatic int\t*objects = NULL,\n\t\troot_object,\n\t\tinfo_object,\n\t\toutline_object,\n\t\tpages_object,\n\t\tnames_object,\n\t\tencrypt_object,\n\t\tfont_objects[TYPE_MAX * STYLE_MAX];", "static uchar\t*doc_title = NULL;\nstatic image_t\t*logo_image = NULL;\nstatic float\tlogo_width,\n\t\tlogo_height;\nstatic image_t\t*lh_image = NULL;\nstatic float\tlh_width,\n\t\tlh_height;", "static image_t\t*hfimage[MAX_HF_IMAGES];\nstatic float\thfimage_width[MAX_HF_IMAGES],\n\t\thfimage_height[MAX_HF_IMAGES];\nstatic float maxhfheight;", "static image_t\t*background_image = NULL;\nstatic float\tbackground_color[3] = { 1.0, 1.0, 1.0 },\n\t\tlink_color[3] = { 0.0, 0.0, 1.0 };", "static int\trender_typeface,\n\t\trender_style;\nstatic float\trender_size,\n\t\trender_rgb[3],\n\t\trender_x,\n\t\trender_y,\n\t\trender_startx,\n\t\trender_spacing;", "static int\t\tcompressor_active = 0;\nstatic z_stream\t\tcompressor;\nstatic uchar\t\tcomp_buffer[8192];\nstatic uchar\t\tencrypt_key[16];\nstatic int\t\tencrypt_len;\nstatic rc4_context_t\tencrypt_state;\nstatic md5_byte_t\tfile_id[16];", "\n/*\n * Local functions...\n */", "extern \"C\" {\ntypedef int\t(*compare_func_t)(const void *, const void *);\n}", "static void\tpspdf_debug_stats();", "static void\tpspdf_transform_coords(page_t *p, float &x, float &y);\nstatic void\tpspdf_transform_page(int outpage, int pos, int page);", "static void\tpspdf_prepare_outpages();\nstatic void\tpspdf_prepare_page(int page);\nstatic void\tpspdf_prepare_heading(int page, int print_page, uchar **format,\n\t\t int y, char *page_text, int page_len);\nstatic void\tps_write_document(uchar *author, uchar *creator,\n\t\t uchar *copyright, uchar *keywords,\n\t\t\t\t uchar *subject, uchar *lang);\nstatic void\tps_write_outpage(FILE *out, int outpage);\nstatic void\tps_write_page(FILE *out, int page);\nstatic void\tps_write_background(FILE *out);\nstatic void\tpdf_write_document(uchar *author, uchar *creator,\n\t\t uchar *copyright, uchar *keywords,\n\t\t\t\t uchar *subject, uchar *lang, tree_t *doc, tree_t *toc);\nstatic void\tpdf_write_outpage(FILE *out, int outpage);\nstatic void\tpdf_write_page(FILE *out, int page);\nstatic void\tpdf_write_resources(FILE *out, int page);\n#ifdef DEBUG_TOC\nstatic void\tpdf_text_contents(FILE *out, tree_t *toc, int indent = 0);\n#endif // DEBUG_TOC\nstatic void\tpdf_write_contents(FILE *out, tree_t *toc, int parent,\n\t\t int prev, int next, int *heading);\nstatic void\tpdf_write_files(FILE *out, tree_t *doc);\nstatic void\tpdf_write_links(FILE *out);\nstatic void\tpdf_write_names(FILE *out);\nstatic int\tpdf_count_headings(tree_t *toc);", "static int\tpdf_start_object(FILE *out, int array = 0);\nstatic void\tpdf_start_stream(FILE *out);\nstatic void\tpdf_end_object(FILE *out);", "static void\tencrypt_init(void);\nstatic void\tflate_open_stream(FILE *out);\nstatic void\tflate_close_stream(FILE *out);\nstatic void\tflate_puts(const char *s, FILE *out);\nstatic void\tflate_printf(FILE *out, const char *format, ...);\nstatic void\tflate_write(FILE *out, uchar *inbuf, int length, int flush=0);", "static void\tparse_contents(tree_t *t, float left, float width, float bottom,\n\t\t float length, float *y, int *page, int *heading,\n\t\t\t tree_t *chap);\nstatic void\tparse_doc(tree_t *t, float *left, float *right, float *bottom,\n\t\t float *top, float *x, float *y, int *page,\n\t\t\t tree_t *cpara, int *needspace);\nstatic void\tparse_heading(tree_t *t, float left, float width, float bottom,\n\t\t float length, float *x, float *y, int *page,\n\t\t\t int needspace);\nstatic void\tparse_paragraph(tree_t *t, float left, float width, float bottom,\n\t\t float length, float *x, float *y, int *page,\n\t\t\t int needspace);\nstatic void\tparse_pre(tree_t *t, float left, float width, float bottom,\n\t\t float length, float *x, float *y, int *page,\n\t\t\t int needspace);\nstatic void\tparse_table(tree_t *t, float left, float width, float bottom,\n\t\t float length, float *x, float *y, int *page,\n\t\t\t int needspace);\nstatic void\tparse_list(tree_t *t, float *left, float *width, float *bottom,\n\t\t float *length, float *x, float *y, int *page,\n\t\t\t int needspace);\nstatic void\tinit_list(tree_t *t);\nstatic void\tparse_comment(tree_t *t, float *left, float *width, float *bottom,\n\t\t float *length, float *x, float *y, int *page,\n\t\t\t tree_t *para, int needspace);", "static void\tcheck_pages(int page);", "static void\tadd_link(uchar *name, int page, int top);\nstatic link_t\t*find_link(uchar *name);\nstatic int\tcompare_links(link_t *n1, link_t *n2);", "static void\tfind_background(tree_t *t);\nstatic void\twrite_background(int page, FILE *out);", "static render_t\t*new_render(int page, int type, double x, double y,\n\t\t double width, double height, void *data,\n\t\t\t render_t *insert = 0);\nstatic float\tget_cell_size(tree_t *t, float left, float right,\n\t\t float *minwidth, float *prefwidth,\n\t\t\t float *minheight);\nstatic float\tget_table_size(tree_t *t, float left, float right,\n\t\t float *minwidth, float *prefwidth,\n\t\t\t float *minheight);\nstatic tree_t\t*flatten_tree(tree_t *t);\nstatic float\tget_width(uchar *s, int typeface, int style, int size);\nstatic void\tupdate_image_size(tree_t *t);\nstatic uchar\t*get_title(tree_t *doc);\nstatic FILE\t*open_file(void);\nstatic void\tset_color(FILE *out, float *rgb);\nstatic void\tset_font(FILE *out, int typeface, int style, float size);\nstatic void\tset_pos(FILE *out, float x, float y);\nstatic void\twrite_prolog(FILE *out, int pages, uchar *author,\n\t\t uchar *creator, uchar *copyright,\n\t\t\t uchar *keywords, uchar *subject);\nstatic void\tps_hex(FILE *out, uchar *data, int length);\n#ifdef HTMLDOC_ASCII85\nstatic void\tps_ascii85(FILE *out, uchar *data, int length, int eod = 0);\n#endif // HTMLDOC_ASCII85\nstatic void\tjpg_init(j_compress_ptr cinfo);\nstatic boolean\tjpg_empty(j_compress_ptr cinfo);\nstatic void\tjpg_term(j_compress_ptr cinfo);\nstatic void\tjpg_setup(FILE *out, image_t *img, j_compress_ptr cinfo);\nstatic int\tcompare_rgb(unsigned *rgb1, unsigned *rgb2);\nstatic void\twrite_image(FILE *out, render_t *r, int write_obj = 0);\nstatic void\twrite_imagemask(FILE *out, render_t *r);\nstatic void\twrite_string(FILE *out, uchar *s, int compress);\nstatic void\twrite_text(FILE *out, render_t *r);\nstatic void\twrite_trailer(FILE *out, int pages, uchar *lang);\nstatic int\twrite_type1(FILE *out, typeface_t typeface,\n\t\t\t style_t style);\nstatic void\twrite_utf16(FILE *out, uchar *s);", "\n/*\n * 'pspdf_export()' - Export PostScript/PDF file(s)...\n */", "int\npspdf_export(tree_t *document,\t/* I - Document to export */\n tree_t *toc)\t/* I - Table of contents for document */\n{\n int\t\ti, j;\t\t/* Looping vars */\n const char\t*title_file;\t/* Location of title image/file */\n uchar\t\t*author,\t/* Author of document */\n\t\t*creator,\t/* HTML file creator (Netscape, etc) */\n\t\t*copyright,\t/* File copyright */\n\t\t*docnumber,\t/* Document number */\n\t\t*keywords,\t/* Search keywords */\n\t\t*subject,\t/* Subject */\n\t\t*lang;\t\t/* Language */\n tree_t\t*t;\t\t/* Title page document tree */\n FILE\t\t*fp;\t\t/* Title page file */\n float\t\tx, y,\t\t/* Current page position */\n\t\tleft, right,\t/* Left and right margins */\n\t\tbottom, top,\t/* Bottom and top margins */\n\t\twidth,\t\t/* Width of , author, etc */\n\t\theight;\t\t/* Height of area */\n int\t\tpage,\t\t/* Current page # */\n\t\tpos,\t\t/* Current header/footer position */\n\t\theading,\t/* Current heading # */\n\t\ttoc_duplex,\t/* Duplex TOC pages? */\n\t\ttoc_landscape,\t/* Do TOC in landscape? */\n\t\ttoc_width,\t/* Width of TOC pages */\n\t\ttoc_length,\t/* Length of TOC pages */\n\t\ttoc_left,\t/* TOC page margins */\n\t\ttoc_right,\n\t\ttoc_bottom,\n\t\ttoc_top;\n image_t\t*timage;\t/* Title image */\n float\t\ttimage_width,\t/* Title image width */\n\t\ttimage_height;\t/* Title image height */\n render_t\t*r;\t\t/* Rendering structure... */\n float\t\trgb[3];\t\t/* Text color */\n int\t\tneedspace;\t/* Need whitespace */", "\n /*\n * Figure out the printable area of the output page...\n */", " if (Landscape)\n {\n PagePrintWidth = PageLength - PageLeft - PageRight;\n PagePrintLength = PageWidth - PageTop - PageBottom;\n }\n else\n {\n PagePrintWidth = PageWidth - PageLeft - PageRight;\n PagePrintLength = PageLength - PageTop - PageBottom;\n }", " toc_width = PageWidth;\n toc_length = PageLength;\n toc_left = PageLeft;\n toc_right = PageRight;\n toc_bottom = PageBottom;\n toc_top = PageTop;\n toc_landscape = Landscape;\n toc_duplex = PageDuplex;", " /*\n * Get the document title, author, etc...\n */", " doc_title = get_title(document);\n author = htmlGetMeta(document, (uchar *)\"author\");\n creator = htmlGetMeta(document, (uchar *)\"generator\");\n copyright = htmlGetMeta(document, (uchar *)\"copyright\");\n docnumber = htmlGetMeta(document, (uchar *)\"docnumber\");\n keywords = htmlGetMeta(document, (uchar *)\"keywords\");\n subject = htmlGetMeta(document, (uchar *)\"subject\");\n lang = htmlGetMeta(document, (uchar *)\"lang\");\n logo_image = image_load(LogoImage, !OutputColor);\n lh_image = image_load(Letterhead, !OutputColor);\n maxhfheight = 0.0f;", " if (docnumber == NULL)\n docnumber = htmlGetMeta(document, (uchar *)\"version\");", " if (lh_image != NULL)\n {\n lh_width = (float)(lh_image->width * PagePrintWidth / _htmlBrowserWidth);\n lh_height = (float)(lh_width * lh_image->height / lh_image->width);", " if (lh_height > maxhfheight)\n maxhfheight = lh_height;\n }\n else\n lh_width = lh_height = 0.0f;", " if (logo_image != NULL)\n {\n logo_width = (float)(logo_image->width * PagePrintWidth / _htmlBrowserWidth);\n logo_height = (float)(logo_width * logo_image->height / logo_image->width);", " if (logo_height > (2.0 * HeadFootSize))\n {\n // Issue #273: too large logo image will overlap the body text, so cap\n // the height of the logo image to the header/footer size...\n //\n // Issue #303: regression prevents using header/footer images for special\n // underlining/etc. effects.\n logo_height = (float)(2.0 * HeadFootSize);\n logo_width = logo_height * logo_image->width / logo_image->height;\n }", " if (logo_height > maxhfheight)\n maxhfheight = logo_height;\n }\n else\n logo_width = logo_height = 0.0f;", " for (int hfi = 0; hfi < MAX_HF_IMAGES; hfi ++)\n {\n hfimage[hfi] = image_load(HFImage[hfi], !OutputColor);", " if (hfimage[hfi])\n {\n hfimage_width[hfi] = (float)(hfimage[hfi]->width * PagePrintWidth / _htmlBrowserWidth);\n hfimage_height[hfi] = (float)(hfimage_width[hfi] * hfimage[hfi]->height / hfimage[hfi]->width);", " if (hfimage_height[hfi] > (2.0 * HeadFootSize))\n {\n // Issue #273: too large logo image will overlap the body text, so cap\n // the height of the logo image to the header/footer size...\n //\n // Issue #303: regression prevents using header/footer images for special\n // underlining/etc. effects.\n hfimage_height[hfi] = (float)(2.0 * HeadFootSize);\n hfimage_width[hfi] = hfimage_height[hfi] * hfimage[hfi]->width / hfimage[hfi]->height;\n }", " if (hfimage_height[hfi] > maxhfheight)\n maxhfheight = hfimage_height[hfi];\n }\n else\n hfimage_width[hfi] = hfimage_height[hfi] = 0.0f;\n }", " find_background(document);\n get_color((uchar *)LinkColor, link_color);", " /*\n * Initialize page rendering variables...\n */", " num_pages = 0;\n alloc_pages = 0;\n pages = NULL;", " memset(list_types, 0267, sizeof(list_types));\n memset(list_values, 0, sizeof(list_values));\n memset(chapter_starts, -1, sizeof(chapter_starts));\n memset(chapter_ends, -1, sizeof(chapter_starts));", " /*\n * Get the current date, using the SOURCE_DATE_EPOCH environment variable, if\n * present, for the number of seconds since the epoch - this enables\n * reproducible builds (Issue #310).\n */", " const char *source_date_epoch = getenv(\"SOURCE_DATE_EPOCH\");\n if (!source_date_epoch || (doc_time = (time_t)strtol(source_date_epoch, NULL, 10)) <= 0)\n doc_time = time(NULL);", " gmtime_r(&doc_time, &doc_date);", " num_headings = 0;\n alloc_headings = 0;\n heading_pages = NULL;\n heading_tops = NULL;\n num_links = 0;\n alloc_links = 0;\n links = NULL;\n num_pages = 0;", " DEBUG_printf((\"pspdf_export: TitlePage = %d, TitleImage = \\\"%s\\\"\\n\",\n TitlePage, TitleImage));", " if (TitlePage)\n {\n const char *title_ext = file_extension(TitleImage);", "#ifdef WIN32\n if (TitleImage[0] &&\n stricmp(title_ext, \"bmp\") != 0 &&\n\tstricmp(title_ext, \"gif\") != 0 &&\n\tstricmp(title_ext, \"jpg\") != 0 &&\n\tstricmp(title_ext, \"png\") != 0)\n#else\n if (TitleImage[0] &&\n strcmp(title_ext, \"bmp\") != 0 &&\n\tstrcmp(title_ext, \"gif\") != 0 &&\n\tstrcmp(title_ext, \"jpg\") != 0 &&\n\tstrcmp(title_ext, \"png\") != 0)\n#endif // WIN32\n {\n DEBUG_printf((\"pspdf_export: Generating a titlepage using \\\"%s\\\"\\n\",\n TitleImage));", " // Find the title file...\n if ((title_file = file_find(Path, TitleImage)) == NULL)\n {\n\tprogress_error(HD_ERROR_FILE_NOT_FOUND,\n\t \"Unable to find title file \\\"%s\\\"!\", TitleImage);\n\treturn (1);\n }", " // Write a title page from HTML source...\n if ((fp = fopen(title_file, \"rb\")) == NULL)\n {\n\tprogress_error(HD_ERROR_FILE_NOT_FOUND,\n\t \"Unable to open title file \\\"%s\\\" - %s!\",\n TitleImage, strerror(errno));\n\treturn (1);\n }", "#ifdef _WIN32\n if (!stricmp(title_ext, \"md\"))\n#else\n if (!strcmp(title_ext, \"md\"))\n#endif // _WIN32\n\tt = mdReadFile(NULL, fp, file_directory(TitleImage));\n else\n\tt = htmlReadFile(NULL, fp, file_directory(TitleImage));", " htmlFixLinks(t, t, (uchar *)file_directory(TitleImage));\n fclose(fp);", " page = 0;\n title_page = 1;\n current_heading = NULL;\n x = 0.0f;\n bottom = 0.0f;\n top = PagePrintLength;\n y = top;\n needspace = 0;\n left = 0.0f;\n right = PagePrintWidth;", " parse_doc(t, &left, &right, &bottom, &top, &x, &y, &page, NULL, &needspace);", " if (PageDuplex && (num_pages & 1))\n\tcheck_pages(num_pages);", " htmlDeleteTree(t);\n }\n else\n {\n /*\n * Create a standard title page...\n */", " if ((timage = image_load(TitleImage, !OutputColor)) != NULL)\n {\n\ttimage_width = (float)(timage->width * PagePrintWidth / _htmlBrowserWidth);\n\ttimage_height = (float)(timage_width * timage->height / timage->width);\n }\n else\n timage_width = timage_height = 0.0f;", " check_pages(0);\n if (PageDuplex)\n check_pages(1);", " height = 0.0;", " if (timage != NULL)\n\theight += timage_height + _htmlSpacings[SIZE_P];\n if (doc_title != NULL)\n\theight += _htmlSpacings[SIZE_H1] + _htmlSpacings[SIZE_P];\n if (author != NULL)\n\theight += _htmlSpacings[SIZE_P];\n if (docnumber != NULL)\n\theight += _htmlSpacings[SIZE_P];\n if (copyright != NULL)\n\theight += _htmlSpacings[SIZE_P];", " y = 0.5f * (PagePrintLength + height);", " if (timage != NULL)\n {\n\tnew_render(0, RENDER_IMAGE, 0.5f * (PagePrintWidth - timage_width),\n y - timage_height, timage_width, timage_height, timage);\n\ty -= timage_height + _htmlSpacings[SIZE_P];\n }", " get_color(_htmlTextColor, rgb);", " if (doc_title != NULL)\n {\n\twidth = get_width(doc_title, _htmlHeadingFont, STYLE_BOLD, SIZE_H1);\n\tr = new_render(0, RENDER_TEXT, (PagePrintWidth - width) * 0.5f,\n \t y - _htmlSpacings[SIZE_H1], width,\n\t\t\t _htmlSizes[SIZE_H1], doc_title);", "\tr->data.text.typeface = _htmlHeadingFont;\n\tr->data.text.style = STYLE_BOLD;\n\tr->data.text.size = (float)_htmlSizes[SIZE_H1];\n\tmemcpy(r->data.text.rgb, rgb, sizeof(rgb));", "\ty -= _htmlSpacings[SIZE_H1];", "\tif (docnumber != NULL)\n\t{\n\t width = get_width(docnumber, _htmlBodyFont, STYLE_NORMAL, SIZE_P);\n\t r = new_render(0, RENDER_TEXT, (PagePrintWidth - width) * 0.5f,\n y - _htmlSpacings[SIZE_P], width,\n\t\t\t _htmlSizes[SIZE_P], docnumber);", "\t r->data.text.typeface = _htmlBodyFont;\n\t r->data.text.style = STYLE_NORMAL;\n\t r->data.text.size = (float)_htmlSizes[SIZE_P];\n memcpy(r->data.text.rgb, rgb, sizeof(rgb));", "\t y -= _htmlSpacings[SIZE_P];\n\t}", "\ty -= _htmlSpacings[SIZE_P];\n }", " if (author != NULL)\n {\n\twidth = get_width(author, _htmlBodyFont, STYLE_NORMAL, SIZE_P);\n\tr = new_render(0, RENDER_TEXT, (PagePrintWidth - width) * 0.5f,\n \t y - _htmlSpacings[SIZE_P], width, _htmlSizes[SIZE_P],\n\t\t\t author);", "\tr->data.text.typeface = _htmlBodyFont;\n\tr->data.text.style = STYLE_NORMAL;\n\tr->data.text.size = (float)_htmlSizes[SIZE_P];\n\tmemcpy(r->data.text.rgb, rgb, sizeof(rgb));", "\ty -= _htmlSpacings[SIZE_P];\n }", " if (copyright != NULL)\n {\n\twidth = get_width(copyright, _htmlBodyFont, STYLE_NORMAL, SIZE_P);\n\tr = new_render(0, RENDER_TEXT, (PagePrintWidth - width) * 0.5f,\n \t y - _htmlSpacings[SIZE_P], width, _htmlSizes[SIZE_P],\n\t\t\t copyright);", "\tr->data.text.typeface = _htmlBodyFont;\n\tr->data.text.style = STYLE_NORMAL;\n\tr->data.text.size = (float)_htmlSizes[SIZE_P];\n\tmemcpy(r->data.text.rgb, rgb, sizeof(rgb));\n }\n }", " for (page = 0; page < (int)num_pages; page ++)\n strlcpy((char *)pages[page].page_text, (page & 1) ? \"eltit\" : \"title\", sizeof(pages[page].page_text));\n }\n else\n page = 0;", " /*\n * Parse the document...\n */", " if (OutputType == OUTPUT_BOOK)\n chapter = 0;\n else\n {\n chapter = 1;\n TocDocCount = 1;\n chapter_starts[1] = num_pages;\n }", " title_page = 0;\n current_heading = NULL;\n x = 0.0f;\n needspace = 0;\n left = 0.0f;\n right = PagePrintWidth;", " // Adjust top margin as needed...\n float adjust, image_adjust, temp_adjust;", " if (maxhfheight > HeadFootSize)\n image_adjust = (float)(maxhfheight + HeadFootSize);\n else\n image_adjust = (float)(2 * HeadFootSize);", " for (adjust = 0.0, pos = 0; pos < 3; pos ++)\n {\n if (Header[pos] &&\n (strstr(Header[pos], \"$IMAGE\") != NULL ||\n\t strstr(Header[pos], \"$HFIMAGE\") != NULL ||\n\t strstr(Header[pos], \"$LETTERHEAD\") != NULL))\n temp_adjust = image_adjust;\n else if (Header1[pos] &&\n\t (strstr(Header1[pos], \"$IMAGE\") != NULL ||\n\t strstr(Header1[pos], \"$HFIMAGE\") != NULL ||\n\t strstr(Header1[pos], \"$LETTERHEAD\") != NULL))\n temp_adjust = image_adjust;\n else if (Header[pos] || Header1[pos])\n temp_adjust = (float)(2 * HeadFootSize);\n else\n temp_adjust = 0.0;", " if (temp_adjust > adjust)\n adjust = temp_adjust;\n }", " top = PagePrintLength - adjust;", " // Adjust bottom margin as needed...\n for (adjust = 0.0, pos = 0; pos < 3; pos ++)\n {\n if (Footer[pos] &&\n (strstr(Footer[pos], \"$IMAGE\") != NULL ||\n\t strstr(Footer[pos], \"$HFIMAGE\") != NULL ||\n\t strstr(Footer[pos], \"$LETTERHEAD\") != NULL))\n temp_adjust = image_adjust;\n else if (Footer[pos])\n temp_adjust = (float)(2 * HeadFootSize);\n else\n temp_adjust = 0.0;", " if (temp_adjust > adjust)\n adjust = temp_adjust;\n }", " bottom = adjust;", " y = top;", " parse_doc(document, &left, &right, &bottom, &top, &x, &y, &page, NULL, &needspace);", " if (PageDuplex && (num_pages & 1))\n {\n if (PSLevel == 0)\n chapter_ends[chapter] = num_pages - 1;", " check_pages(num_pages);", " if (PSLevel > 0)\n chapter_ends[chapter] = num_pages - 1;\n }\n else\n chapter_ends[chapter] = num_pages - 1;", " for (chapter = 1; chapter <= TocDocCount; chapter ++)\n for (page = chapter_starts[chapter]; page <= chapter_ends[chapter]; page ++)\n pspdf_prepare_page(page);", " /*\n * Parse the table-of-contents if necessary...\n */", " if (TocLevels > 0 && num_headings > 0)\n {\n // Restore default page size, etc...\n PageWidth = toc_width;\n PageLength = toc_length;\n PageLeft = toc_left;\n PageRight = toc_right;\n PageBottom = toc_bottom;\n PageTop = toc_top;\n Landscape = toc_landscape;\n PageDuplex = toc_duplex;", " if (Landscape)\n {\n PagePrintWidth = PageLength - PageLeft - PageRight;\n PagePrintLength = PageWidth - PageTop - PageBottom;\n }\n else\n {\n PagePrintWidth = PageWidth - PageLeft - PageRight;\n PagePrintLength = PageLength - PageTop - PageBottom;\n }", " // Adjust top margin as needed...\n for (pos = 0; pos < 3; pos ++)\n if (TocHeader[pos])\n\tbreak;", " if (pos == 3)\n top = PagePrintLength;\n else if (maxhfheight > HeadFootSize)\n top = (float)(PagePrintLength - maxhfheight - HeadFootSize);\n else\n top = (float)(PagePrintLength - 2 * HeadFootSize);", " // Adjust bottom margin as needed...\n for (pos = 0; pos < 3; pos ++)\n if (TocFooter[pos])\n\tbreak;", " if (pos == 3)\n bottom = 0.0f;\n else if (maxhfheight > HeadFootSize)\n bottom = (float)(maxhfheight + HeadFootSize);\n else\n bottom = (float)(2 * HeadFootSize);", " y = 0.0;\n page = num_pages - 1;\n heading = 0;\n chapter_starts[0] = num_pages;\n chapter = 0;", " parse_contents(toc, 0, PagePrintWidth, bottom, top, &y, &page, &heading, 0);\n if (PageDuplex && (num_pages & 1))\n check_pages(num_pages);\n chapter_ends[0] = num_pages - 1;", " for (page = chapter_starts[0]; page <= chapter_ends[0]; page ++)\n pspdf_prepare_page(page);\n }", " if (TocDocCount > MAX_CHAPTERS)\n TocDocCount = MAX_CHAPTERS;", " /*\n * Do we have any pages?\n */", " if (num_pages > 0 && TocDocCount > 0)\n {\n /*\n * Yes, write the document to disk...\n */", " pspdf_prepare_outpages();", " pspdf_debug_stats();", " progress_error(HD_ERROR_NONE, \"PAGES: %d\", (int)num_outpages);", " if (PSLevel > 0)\n ps_write_document(author, creator, copyright, keywords, subject, lang);\n else\n pdf_write_document(author, creator, copyright, keywords, subject, lang,\n document, toc);\n }\n else\n {\n /*\n * No, show an error...\n */", " pspdf_debug_stats();", " progress_error(HD_ERROR_NO_PAGES,\n \"Error: no pages generated! (did you remember to use webpage mode?\");\n }", " /*\n * Free memory...\n */", " if (doc_title != NULL)\n free(doc_title);", " if (alloc_links)\n {\n free(links);", " num_links = 0;\n alloc_links = 0;\n links = NULL;\n }", " for (i = 0; i < (int)num_pages; i ++)\n {\n if ((i == 0 || pages[i].chapter != pages[i - 1].chapter) &&\n pages[i].chapter)\n free(pages[i].chapter);", " if ((i == 0 || pages[i].heading != pages[i - 1].heading) &&\n pages[i].heading)\n free(pages[i].heading);", " if (!pages[i].heading)\n continue;", " for (j = 0; j < 3; j ++)\n {\n if (!pages[i].header[j])\n continue;", " if (i == 0 || pages[i].header[j] != pages[i - 1].header[j])\n free(pages[i].header[j]);\n }", " for (j = 0; j < 3; j ++)\n {\n if (!pages[i].header1[j])\n continue;", " if (i == 0 || pages[i].header1[j] != pages[i - 1].header1[j])\n free(pages[i].header1[j]);\n }", " for (j = 0; j < 3; j ++)\n {\n if (!pages[i].footer[j])\n continue;", " if (i == 0 || pages[i].footer[j] != pages[i - 1].footer[j])\n free(pages[i].footer[j]);\n }\n }", " for (i = 0; i < 3; i ++)\n {\n Header[i] = NULL;\n Header1[i] = NULL;\n Footer[i] = NULL;\n TocHeader[i] = NULL;\n TocFooter[i] = NULL;\n }", " if (alloc_pages)\n {\n free(pages);\n free(outpages);", " num_pages = 0;\n alloc_pages = 0;\n pages = NULL;\n }", " if (alloc_headings)\n {\n free(heading_pages);\n free(heading_tops);", " num_headings = 0;\n alloc_headings = 0;\n heading_pages = NULL;\n heading_tops = NULL;\n }", " return (0);\n}", "", "//\n// 'pspdf_debug_stats()' - Display debug statistics for render memory use.\n//", "static void\npspdf_debug_stats()\n{\n const char\t*debug;\t\t\t// HTMLDOC_DEBUG env var\n int\t\ti;\t\t\t// Looping var\n render_t\t*r;\t\t\t// Render node\n int\t\tbytes;\t\t\t// Number of bytes", "\n if ((debug = getenv(\"HTMLDOC_DEBUG\")) == NULL ||\n (strstr(debug, \"all\") == NULL && strstr(debug, \"memory\") == NULL))\n return;", " bytes = alloc_headings * sizeof(int) * 2;", " bytes += alloc_pages * sizeof(page_t);\n for (i = 0; i < (int)num_pages; i ++)\n {\n for (r = pages[i].start; r != NULL; r = r->next)\n {\n bytes += sizeof(render_t);", " if (r->type == RENDER_TEXT)\n bytes += strlen((char *)r->data.text.buffer);\n }\n }", " bytes += num_outpages * sizeof(outpage_t);\n bytes += alloc_links * sizeof(link_t);\n bytes += alloc_objects * sizeof(int);", " progress_error(HD_ERROR_NONE, \"DEBUG: Render Data = %d kbytes\",\n (bytes + 1023) / 1024);\n}", "\n/*\n * 'pspdf_transform_coords()' - Transform page coordinates.\n */", "static void\npspdf_transform_coords(page_t *p,\t// I - Page\n float &x,\t// IO - X coordinate\n\t\t float &y)\t// IO - Y coordinate\n{\n float tx, ty;\t\t\t\t// Temporary X and Y", "\n tx = x;\n ty = y;\n x = tx * p->outmatrix[0][0] + ty * p->outmatrix[0][1] + p->outmatrix[0][2];\n y = tx * p->outmatrix[1][0] + ty * p->outmatrix[1][1] + p->outmatrix[1][2];\n}", "\n/*\n * 'pspdf_transform_page()' - Transform a page.\n */", "static void\npspdf_transform_page(int outpage,\t// I - Output page\n int pos,\t\t// I - Position on page\n int page)\t\t// I - Input page\n{\n outpage_t\t*op;\t\t\t// Current output page\n page_t\t*bp;\t\t\t// Current base page\n page_t\t*p;\t\t\t// Current input page\n int\t\tx, y;\t\t\t// Position on output page\n double\tw, l,\t\t\t// Width and length of subpage\n\t\ttx, ty;\t\t\t// Translation values for subpage\n double\tpw, pl;\t\t\t// Printable width and length of full page", "\n DEBUG_printf((\"pspdf_transform_page(outpage = %d, pos = %d, page = %d)\\n\",\n outpage, pos, page));", " if (pos > 15)\n progress_error(HD_ERROR_INTERNAL_ERROR, \"Internal error: pos = %d\", pos);", " op = outpages + outpage;\n op->pages[pos] = page;\n bp = pages + op->pages[0];\n p = pages + page;\n p->outpage = outpage;\n pw = bp->width;\n pl = bp->length;", " DEBUG_printf((\" width = %d, length = %d\\n\", p->width, p->length));", " switch (op->nup)\n {\n default :\n case 1 :\n p->outmatrix[0][0] = 1.0f;\n p->outmatrix[1][0] = 0.0f;\n p->outmatrix[0][1] = 0.0f;\n p->outmatrix[1][1] = 1.0f;\n p->outmatrix[0][2] = 0.0f;\n p->outmatrix[1][2] = 0.0f;\n\tbreak;", " case 2 :\n\tx = pos & 1;", " l = pw;\n w = l * p->width / p->length;", " if (w > (pl * 0.5f))\n {\n w = pl * 0.5f;\n l = w * p->length / p->width;\n }", " tx = 0.5 * (pl * 0.5 - w);\n ty = 0.5 * (pw - l);", " p->outmatrix[0][0] = 0.0f;\n p->outmatrix[1][0] = (float)(w / p->width);\n p->outmatrix[0][1] = (float)(-w / p->width);\n p->outmatrix[1][1] = 0.0f;\n p->outmatrix[0][2] = (float)(ty + pl * w / p->width);\n p->outmatrix[1][2] = (float)(tx + x * pl / 2);\n\tbreak;", " case 4 :\n x = pos & 1;\n\ty = 1 - pos / 2;", " w = pw * 0.5;\n\tl = w * p->length / p->width;", "\tif (l > (pl * 0.5))\n\t{\n\t l = pl * 0.5;\n\t w = l * p->width / p->length;\n\t}", " tx = 0.5 * (pw * 0.5 - w);\n ty = 0.5 * (pl * 0.5 - l);", " p->outmatrix[0][0] = (float)(w / p->width);\n p->outmatrix[1][0] = 0.0f;\n p->outmatrix[0][1] = 0.0f;\n p->outmatrix[1][1] = (float)(w / p->width);\n p->outmatrix[0][2] = (float)(tx + x * pw / 2);\n p->outmatrix[1][2] = (float)(ty + y * pl / 2);\n\tbreak;", " case 6 :\n x = pos % 3;\n\ty = pos / 3;", " l = pw * 0.5;\n w = l * p->width / p->length;", " if (w > (pl * 0.333f))\n {\n w = pl * 0.333f;\n l = w * p->length / p->width;\n }", " tx = 0.5 * (pl * 0.333 - w);\n ty = 0.5 * (pw * 0.5 - l);", " p->outmatrix[0][0] = 0.0f;\n p->outmatrix[1][0] = (float)(w / p->width);\n p->outmatrix[0][1] = (float)(-w / p->width);\n p->outmatrix[1][1] = 0.0f;\n p->outmatrix[0][2] = (float)(ty + y * pw / 2 + pl * w / p->width);\n p->outmatrix[1][2] = (float)(tx + x * pl / 3);\n\tbreak;", " case 9 :\n x = pos % 3;\n\ty = 2 - pos / 3;", " w = pw * 0.333;\n\tl = w * p->length / p->width;", "\tif (l > (pl * 0.333))\n\t{\n\t l = pl * 0.333;\n\t w = l * p->width / p->length;\n\t}", " tx = 0.5 * (pw * 0.333 - w);\n ty = 0.5 * (pl * 0.333 - l);", " p->outmatrix[0][0] = (float)(w / p->width);\n p->outmatrix[1][0] = 0.0f;\n p->outmatrix[0][1] = 0.0f;\n p->outmatrix[1][1] = (float)(w / p->width);\n p->outmatrix[0][2] = (float)(tx + x * pw / 3);\n p->outmatrix[1][2] = (float)(ty + y * pl / 3);\n\tbreak;", " case 16 :\n x = pos & 3;\n\ty = 3 - pos / 4;", " w = pw * 0.25;\n\tl = w * p->length / p->width;", "\tif (l > (pl * 0.25))\n\t{\n\t l = pl * 0.25;\n\t w = l * p->width / p->length;\n\t}", " tx = 0.5 * (pw * 0.25 - w);\n ty = 0.5 * (pl * 0.25 - l);", " p->outmatrix[0][0] = (float)(w / p->width);\n p->outmatrix[1][0] = 0.0f;\n p->outmatrix[0][1] = 0.0f;\n p->outmatrix[1][1] = (float)(w / p->width);\n p->outmatrix[0][2] = (float)(tx + x * pw / 4);\n p->outmatrix[1][2] = (float)(ty + y * pl / 4);\n\tbreak;\n }\n}", "\n/*\n * 'pspdf_prepare_outpages()' - Prepare output pages...\n */", "static void\npspdf_prepare_outpages()\n{\n int\t\tc, i, j;\t/* Looping vars */\n int\t\tnup;\t\t/* Current number-up value */\n page_t\t*page;\t\t/* Current page */\n outpage_t\t*outpage;\t/* Current output page */", "\n // Allocate an output page array...\n outpages = (outpage_t *)malloc(sizeof(outpage_t) * num_pages);", " memset(outpages, -1, sizeof(outpage_t) * num_pages);", " num_outpages = 0;\n outpage = outpages;", " // Handle the title page, as needed...\n if (TitlePage)\n {\n for (i = 0, j = 0, nup = -1, page = pages;\n i < chapter_starts[1];\n\t i ++, page ++)\n {\n if (nup != page->nup)\n {\n if (j)\n\t{\n\t // Break the current output page...\n\t outpage ++;\n\t num_outpages ++;\n\t}", "\tnup = page->nup;\n\tj = 0;\n }", " if (!j)\n\toutpage->nup = nup;", " pspdf_transform_page(num_outpages, j, i);\n j ++;", " if (j >= nup)\n {\n j = 0;\n\toutpage ++;\n\tnum_outpages ++;\n }\n }", " if (j)\n {\n // Break the current output page...\n outpage ++;\n num_outpages ++;\n }\n }", " // Loop through each chapter, adding pages as needed...\n if (OutputType == OUTPUT_BOOK && TocLevels > 0)\n c = 0;\n else\n c = 1;", " for (; c <= TocDocCount; c ++)\n {\n if (chapter_starts[c] < 0)\n continue;", " chapter_outstarts[c] = num_outpages;", " for (i = chapter_starts[c], j = 0, nup = -1, page = pages + i;", " i <= chapter_ends[c] && num_outpages < num_pages;", "\t i ++, page ++)\n {\n if (nup != page->nup)\n {\n if (j)\n\t{\n\t // Break the current output page...\n\t outpage ++;\n\t num_outpages ++;\n\t}", "\tnup = page->nup;\n\tj = 0;\n }", " if (!j)\n\toutpage->nup = nup;", " pspdf_transform_page(num_outpages, j, i);\n j ++;", " if (j >= nup)\n {\n j = 0;\n\toutpage ++;\n\tnum_outpages ++;\n }\n }", " if (j)\n {\n // Break the current output page...\n outpage ++;\n num_outpages ++;\n }", " chapter_outends[c] = num_outpages;\n }", "#ifdef DEBUG\n for (c = 0; c <= TocDocCount; c ++)\n printf(\"chapter_outstarts[%d] = %d, chapter_outends[%d] = %d\\n\",\n c, chapter_outstarts[c], c, chapter_outends[c]);", " printf(\"num_outpages = %d\\n\", (int)num_outpages);\n for (i = 0, outpage = outpages; i < (int)num_outpages; i ++, outpage ++)\n {\n printf(\"outpage[%d]:\\tnup=%d, pages=[\", i, outpage->nup);\n for (j = 0; j < outpage->nup; j ++)\n printf(\" %d\", outpage->pages[j]);\n puts(\" ]\");\n page = pages + outpage->pages[0];\n printf(\"\\t\\twidth = %d, length = %d\\n\", page->width, page->length);\n }", " for (c = 0; c <= TocDocCount; c ++)\n printf(\"chapter_starts[%d] = %d, chapter_ends[%d] = %d\\n\",\n c, chapter_starts[c], c, chapter_ends[c]);", " for (i = 0; i < (int)num_pages; i ++)\n printf(\"pages[%d]->outpage = %d\\n\", i, pages[i].outpage);", " for (i = 0; i < (int)num_headings; i ++)\n printf(\"heading_pages[%d] = %d\\n\", i, heading_pages[i]);", " for (i = 0; i < (int)num_links; i ++)\n printf(\"links[%d].name = \\\"%s\\\", page = %d\\n\", i,\n links[i].name, links[i].page);\n#endif // DEBUG\n}", "\n/*\n * 'pspdf_prepare_page()' - Add headers/footers to page before writing...\n */", "static void\npspdf_prepare_page(int page)\t\t/* I - Page number */\n{\n int\tprint_page;\t\t\t/* Printed page # */\n char\tpage_text[64];\t\t\t/* Page number text */\n int\ttop;\t\t\t\t/* Top of page */", "\n DEBUG_printf((\"pspdf_prepare_page(%d)\\n\", page));\n if (page < 0 || page >= num_pages)\n return;", " /*\n * Make a page number; use roman numerals for the table of contents\n * and arabic numbers for all others...\n */", " if (chapter == 0 && OutputType == OUTPUT_BOOK)\n {\n print_page = page - chapter_starts[0] + 1;\n strlcpy(page_text, format_number(print_page, 'i'), sizeof(page_text));\n }\n else if (chapter < 0)\n {\n print_page = 0;\n // Safe because page_text is more than 6 chars\n strlcpy(page_text, (page & 1) ? (char *)\"eltit\" : (char *)\"title\", sizeof(page_text));\n }\n else\n {\n print_page = page - chapter_starts[1] + 1;\n strlcpy(page_text, format_number(print_page, '1'), sizeof(page_text));\n }", " DEBUG_printf((\"BEFORE page %d page_text is \\\"%s\\\"...\\n\", page, page_text));", " DEBUG_printf((\" header[0] = \\\"%s\\\"\\n\", pages[page].header[0]));\n DEBUG_printf((\" header[1] = \\\"%s\\\"\\n\", pages[page].header[1]));\n DEBUG_printf((\" header[2] = \\\"%s\\\"\\n\", pages[page].header[2]));", " /*\n * Add page headings...\n */", " if (pages[page].landscape)\n {\n PagePrintWidth = pages[page].length - pages[page].right - pages[page].left;\n PagePrintLength = pages[page].width - pages[page].top - pages[page].bottom;\n }\n else\n {\n PagePrintWidth = pages[page].width - pages[page].right - pages[page].left;\n PagePrintLength = pages[page].length - pages[page].top - pages[page].bottom;\n }", " top = (int)(PagePrintLength - HeadFootSize);", " if (chapter == 0)\n {\n /*\n * Add table-of-contents header & footer...\n */", " pspdf_prepare_heading(page, print_page, pages[page].header, top,\n page_text, sizeof(page_text));\n pspdf_prepare_heading(page, print_page, pages[page].footer, 0,\n page_text, sizeof(page_text));\n }\n else if (chapter > 0 && !title_page)\n {\n /*\n * Add chapter header & footer...\n */", " if (page > chapter_starts[chapter] || OutputType != OUTPUT_BOOK)\n pspdf_prepare_heading(page, print_page, pages[page].header, top,\n page_text, sizeof(page_text));\n else\n pspdf_prepare_heading(page, print_page, pages[page].header1, top,\n page_text, sizeof(page_text));\n pspdf_prepare_heading(page, print_page, pages[page].footer, 0,\n page_text, sizeof(page_text));\n }", " /*\n * Copy the page number for the TOC...\n */", " strlcpy(pages[page].page_text, page_text, sizeof(pages[page].page_text));", " DEBUG_printf((\"AFTER page %d page_text is \\\"%s\\\"...\\n\", page, page_text));\n}", "\n/*\n * 'pspdf_prepare_heading()' - Add headers/footers to page before writing...\n */", "static void\npspdf_prepare_heading(int page,\t// I - Page number\n int print_page,\t// I - Printed page number\n\t\t uchar **format,\t// I - Page headings\n\t\t int y,\t\t// I - Baseline of heading\n\t\t char *page_text,\t// O - Page number text\n\t\t int page_len)\t// I - Size of page text\n{\n int\t\tpos,\t\t\t// Position in heading\n\t\tdir;\t\t\t// Direction of page\n char\t\t*number;\t\t// Page number\n char\t\tbuffer[1024],\t\t// String buffer\n\t\t*bufptr,\t\t// Pointer into buffer\n\t\t*formatptr;\t\t// Pointer into format string\n int\t\tformatlen;\t\t// Length of format command string\n render_t\t*temp;\t\t\t// Render structure for titles, etc.", "\n DEBUG_printf((\"pspdf_prepare_heading(%d, %d, [\\\"%s\\\",\\\"%s\\\",\\\"%s\\\"], %d, %p, %d)\\n\",\n page, print_page, format[0], format[1], format[2], y,\n\t\t(void *)page_text, page_len));", " /*\n * Add page headings...\n */", " if (PageDuplex && (page & 1))\n {\n dir = -1;\n format += 2;\n }\n else\n dir = 1;", " for (pos = 0; pos < 3; pos ++, format += dir)\n {\n /*\n * Add the appropriate object...\n */", " if (!*format)\n continue;", " temp = NULL;", " if (strncasecmp((char *)*format, \"$LOGOIMAGE\", 10) == 0 && logo_image)\n {\n // Insert the logo image...\n if (y < (PagePrintLength / 2))\n\ttemp = new_render(page, RENDER_IMAGE, 0, y, logo_width,\n\t logo_height, logo_image);\n else // Offset from top\n\ttemp = new_render(page, RENDER_IMAGE, 0,\n\t y + HeadFootSize - logo_height,\n\t logo_width, logo_height, logo_image);\n }\n else if (strncasecmp((char *)*format, \"$LETTERHEAD\", 11) == 0 && lh_image)\n {\n // Insert the logo image as a letterhead...\n if (y < (PagePrintLength / 2))\n\ttemp = new_render(page, RENDER_IMAGE, 0, y, lh_width, lh_height, lh_image);\n else // Offset from top\n\ttemp = new_render(page, RENDER_IMAGE, 0, y + HeadFootSize - lh_height, lh_width, lh_height, lh_image);\n }\n else if (strncasecmp((char *)*format, \"$HFIMAGE\", 8) == 0)\n {\n int\thfi;\t\t\t// Header/footer image index\n char\t*hfp;\t\t\t// Pointer into $HFIMAGE", "\n hfi = strtol((char*)((*format) + 8), &hfp, 10);", " if (hfi < 0 || hfi >= MAX_HF_IMAGES || !(isspace(*hfp) || !*hfp))\n progress_error(HD_ERROR_BAD_HF_STRING,\n\t \"Bad $HFIMAGE... substitution on page %d.\", page + 1);\n else\n {\n if (y < (PagePrintLength / 2))\n temp = new_render(page, RENDER_IMAGE, 0, y, hfimage_width[hfi],\n hfimage_height[hfi], hfimage[hfi]);\n else\n temp = new_render(page, RENDER_IMAGE, 0,\n y + HeadFootSize - hfimage_height[hfi],\n hfimage_width[hfi], hfimage_height[hfi],\n\t\t\t hfimage[hfi]);\n }\n }\n else\n {\n // Otherwise format the text...\n buffer[sizeof(buffer) - 1] = '\\0';", " for (bufptr = buffer, formatptr = (char *)*format; *formatptr;)\n {\n if (*formatptr == '$')\n\t{\n\t if (formatptr[1] == '$')\n\t {\n\t if (bufptr < (buffer + sizeof(buffer) - 1))\n\t *bufptr++ = '$';", "\t formatptr += 2;\n\t continue;\n\t }\n\t else if (!formatptr[1])\n\t break;", " formatptr ++;\n\t for (formatlen = 1; isalpha(formatptr[formatlen]); formatlen ++);", "\t if (formatlen == 4 && strncasecmp(formatptr, \"PAGE\", 4) == 0)\n\t {\n\t if (formatptr[4] == '(' && formatptr[5] && formatptr[6] == ')')\n {\n\t number = format_number(print_page, formatptr[5]);\n\t formatptr += 7;\n\t }\n\t else\n\t {\n\t number = format_number(print_page, '1');\n\t formatptr += 4;\n\t }", " strlcpy(bufptr, number, sizeof(buffer) - (size_t)(bufptr - buffer));\n\t bufptr += strlen(bufptr);\n\t }\n\t else if (formatlen == 5 && strncasecmp(formatptr, \"PAGES\", 5) == 0)\n\t {\n\t if (formatptr[5] == '(' && formatptr[6] && formatptr[7] == ')')\n {\n\t number = format_number(chapter_ends[TocDocCount] -\n\t chapter_starts[1] + 1, formatptr[6]);\n\t formatptr += 8;\n\t }\n\t else\n\t {\n\t number = format_number(chapter_ends[TocDocCount] -\n\t chapter_starts[1] + 1, '1');\n\t formatptr += 5;\n\t }", " strlcpy(bufptr, number, sizeof(buffer) - (size_t)(bufptr - buffer));\n\t bufptr += strlen(bufptr);\n\t }\n\t else if (formatlen == 11 && strncasecmp(formatptr, \"CHAPTERPAGE\", 11) == 0)\n\t {\n\t int chapter_page;", "\t chapter_page = print_page - chapter_starts[::chapter] +\n\t chapter_starts[1];", "\t if (formatptr[11] == '(' && formatptr[12] && formatptr[13] == ')')\n {\n\t number = format_number(chapter_page, formatptr[12]);\n\t formatptr += 14;\n\t }\n\t else\n\t {\n\t number = format_number(chapter_page, '1');\n\t formatptr += 11;\n\t }", " strlcpy(bufptr, number, sizeof(buffer) - (size_t)(bufptr - buffer));\n\t bufptr += strlen(bufptr);\n\t }\n\t else if (formatlen == 12 && strncasecmp(formatptr, \"CHAPTERPAGES\", 12) == 0)\n\t {\n\t if (formatptr[12] == '(' && formatptr[13] && formatptr[14] == ')')\n {\n\t number = format_number(chapter_ends[::chapter] -\n\t chapter_starts[::chapter] + 1,\n\t\t\t\t formatptr[13]);\n\t formatptr += 15;\n\t }\n\t else\n\t {\n\t number = format_number(chapter_ends[::chapter] -\n\t chapter_starts[::chapter] + 1, '1');\n\t formatptr += 12;\n\t }", " strlcpy(bufptr, number, sizeof(buffer) - (size_t)(bufptr - buffer));\n\t bufptr += strlen(bufptr);\n\t }\n\t else if (formatlen == 5 && strncasecmp(formatptr, \"TITLE\", 5) == 0)\n\t {\n formatptr += 5;\n\t if (doc_title)\n\t {\n strlcpy(bufptr, (char *)doc_title, sizeof(buffer) - (size_t)(bufptr - buffer));\n\t bufptr += strlen(bufptr);\n\t }\n\t }\n\t else if (formatlen == 7 && strncasecmp(formatptr, \"CHAPTER\", 7) == 0)\n\t {\n formatptr += 7;\n\t if (pages[page].chapter)\n\t {\n strlcpy(bufptr, (char *)(pages[page].chapter), sizeof(buffer) - (size_t)(bufptr - buffer));\n\t bufptr += strlen(bufptr);\n\t }\n\t }\n\t else if (formatlen == 7 && strncasecmp(formatptr, \"HEADING\", 7) == 0)\n\t {\n formatptr += 7;\n\t if (pages[page].heading)\n\t {\n strlcpy(bufptr, (char *)(pages[page].heading), sizeof(buffer) - (size_t)(bufptr - buffer));\n\t bufptr += strlen(bufptr);\n\t }\n\t }\n\t else if (formatlen == 4 && strncasecmp(formatptr, \"TIME\", 4) == 0)\n\t {\n formatptr += 4;\n strftime(bufptr, sizeof(buffer) - 1 - (size_t)(bufptr - buffer), \"%X\", &doc_date);\n\t bufptr += strlen(bufptr);\n\t }\n\t else if (formatlen == 4 && strncasecmp(formatptr, \"DATE\", 4) == 0)\n\t {\n formatptr += 4;\n strftime(bufptr, sizeof(buffer) - 1 - (size_t)(bufptr - buffer), \"%x\", &doc_date);\n\t bufptr += strlen(bufptr);\n\t }\n\t else if (formatlen == 3 && strncasecmp(formatptr, \"URL\", 3) == 0)\n\t {\n uchar *url = pages[page].url ? pages[page].url : (uchar *)\"Unknown\";", " formatptr += 3;\n strlcpy(bufptr, (char *)url, sizeof(buffer) - (size_t)(bufptr - buffer));\n\t bufptr += strlen(bufptr);\n\t }\n\t else\n\t {\n progress_error(HD_ERROR_BAD_HF_STRING, \"Bad header/footer $ command on page %d.\", page + 1);", " strlcpy(bufptr, formatptr - 1, sizeof(buffer) - (size_t)(bufptr - buffer));\n\t bufptr += strlen(bufptr);\n\t formatptr += formatlen;\n\t }\n\t}\n\telse if (bufptr < (buffer + sizeof(buffer) - 1))\n\t *bufptr++ = *formatptr++;\n\telse\n\t break;\n }", " *bufptr = '\\0';", " temp = new_render(page, RENDER_TEXT, 0, y,\n \tget_width((uchar *)buffer, HeadFootType,\n\t\t\t HeadFootStyle, SIZE_P) * HeadFootSize /\n\t\t\t _htmlSizes[SIZE_P],\n\t \tHeadFootSize, (uchar *)buffer);", " if (strstr((char *)*format, \"$PAGE\") ||\n strstr((char *)*format, \"$CHAPTERPAGE\"))\n strlcpy(page_text, buffer, (size_t)page_len);\n }", " if (temp == NULL)\n continue;", " /*\n * Justify the object...\n */", " switch (pos)\n {\n case 0 : /* Left justified */\n break;\n case 1 : /* Centered */\n temp->x = (float)((PagePrintWidth - temp->width) * 0.5);\n break;\n case 2 : /* Right justified */\n temp->x = PagePrintWidth - temp->width;\n break;\n }", " /*\n * Set the text font and color...\n */", " if (temp->type == RENDER_TEXT)\n {\n temp->data.text.typeface = HeadFootType;\n temp->data.text.style = HeadFootStyle;\n temp->data.text.size = (float)HeadFootSize;", " get_color(_htmlTextColor, temp->data.text.rgb);\n }\n }\n}", "\n/*\n * 'ps_write_document()' - Write all render entities to PostScript file(s).\n */", "static void\nps_write_document(uchar *author,\t/* I - Author of document */\n \t uchar *creator,\t/* I - Application that generated the HTML file */\n \t uchar *copyright,\t/* I - Copyright (if any) on the document */\n uchar *keywords,\t/* I - Search keywords */\n\t\t uchar *subject,\t/* I - Subject */\n\t\t uchar *lang)\t\t/* I - Language */\n{\n FILE\t\t*out;\t\t\t/* Output file */\n int\t\tpage;\t\t\t/* Current page # */\n int\t\tfirst;\t\t\t/* First chapter */", "\n /*\n * Write the title page(s)...\n */", " chapter = -1;\n out = NULL;", " if (!OutputFiles)\n {\n out = open_file();", " if (out == NULL)\n {\n progress_error(HD_ERROR_WRITE_ERROR,\n \"Unable to open output file - %s\\n\", strerror(errno));\n return;\n }", " write_prolog(out, num_outpages, author, creator, copyright, keywords, subject);\n }", " if (OutputType == OUTPUT_BOOK && TocLevels > 0)\n first = 0;\n else\n first = 1;", " if (TitlePage)\n {\n if (OutputFiles)\n {\n out = open_file();\n write_prolog(out, chapter_outstarts[first], author, creator, copyright,\n keywords, subject);\n }", " for (page = 0; page < chapter_outstarts[first]; page ++)\n ps_write_outpage(out, page);", " if (OutputFiles)\n {\n write_trailer(out, 0, lang);", " progress_error(HD_ERROR_NONE, \"BYTES: %ld\", ftell(out));", " fclose(out);\n }\n }", " for (chapter = first; chapter <= TocDocCount; chapter ++)\n {\n if (chapter_starts[chapter] < 0)\n continue;", " if (OutputFiles)\n {\n out = open_file();\n if (out == NULL)\n {\n progress_error(HD_ERROR_WRITE_ERROR,\n\t \"Unable to create output file - %s\\n\", strerror(errno));\n return;\n }", " write_prolog(out, chapter_outends[chapter] - chapter_outstarts[chapter],\n author, creator, copyright, keywords, subject);\n }", " for (page = chapter_outstarts[chapter];\n page < chapter_outends[chapter];\n page ++)\n ps_write_outpage(out, page);", " /*\n * Close the output file as necessary...\n */", " if (OutputFiles)\n {\n write_trailer(out, 0, lang);", " progress_error(HD_ERROR_NONE, \"BYTES: %ld\", ftell(out));", " fclose(out);\n }\n }", " /*\n * Close the output file as necessary...\n */", " if (!OutputFiles)\n {\n write_trailer(out, 0, lang);", " progress_error(HD_ERROR_NONE, \"BYTES: %ld\", ftell(out));", " if (out != stdout)\n fclose(out);\n }", " if (Verbosity)\n progress_hide();\n}", "\n/*\n * 'ps_write_outpage()' - Write an output page.\n */", "static void\nps_write_outpage(FILE *out,\t/* I - Output file */\n int outpage)\t/* I - Output page number */\n{\n int\t\tfile_page;\t/* Current page # in document */\n page_t\t*p;\t\t/* Current page */\n outpage_t\t*op;\t\t/* Current output page */\n int\t\ti;\t\t/* Looping var */", "\n if (outpage < 0 || outpage >= (int)num_outpages)\n return;", " op = outpages + outpage;\n p = pages + op->pages[0];", " DEBUG_printf((\"ps_write_outpage(%p, %d)\\n\", (void *)out, outpage));", " /*\n * Let the user know which page we are writing...\n */", " if (Verbosity)\n {\n progress_show(\"Writing page %s...\", p->page_text);\n progress_update(100 * outpage / (int)num_outpages);\n }", " /*\n * Figure out the page number in the file...\n */", " if (OutputFiles && chapter >= 0)\n file_page = outpage - chapter_outstarts[chapter] + 1;\n else if (chapter < 0)\n file_page = outpage + 1;\n else if (chapter == 0)\n {\n if (TitlePage)\n file_page = outpage + 1;\n else\n file_page = outpage - chapter_outstarts[0] + 1;\n }\n else\n {\n if (TitlePage)\n file_page = outpage + 1;\n else\n file_page = outpage - chapter_outstarts[1] + 1;\n }", " /*\n * Output the page prolog...\n */", " fprintf(out, \"%%%%Page: (%s) %d\\n\", p->page_text, file_page);\n if (op->nup == 1)\n {\n if (p->duplex && !(file_page & 1))\n fprintf(out, \"%%%%PageBoundingBox: %d %d %d %d\\n\",\n p->right, p->bottom, p->width - p->left, p->length - p->top);\n else\n fprintf(out, \"%%%%PageBoundingBox: %d %d %d %d\\n\",\n p->left, p->bottom, p->width - p->right, p->length - p->top);\n }\n else\n fprintf(out, \"%%%%PageBoundingBox: 0 0 %d %d\\n\", p->width, p->length);", " if (PSLevel > 1 && PSCommands)\n {\n fputs(\"%%BeginPageSetup\\n\", out);", " if (p->width == 612 && p->length == 792)\n fputs(\"%%BeginFeature: *PageSize Letter\\n\", out);\n else if (p->width == 612 && p->length == 1008)\n fputs(\"%%BeginFeature: *PageSize Legal\\n\", out);\n else if (p->width == 792 && p->length == 1224)\n fputs(\"%%BeginFeature: *PageSize Tabloid\\n\", out);\n else if (p->width == 842 && p->length == 1190)\n fputs(\"%%BeginFeature: *PageSize A3\\n\", out);\n else if (p->width == 595 && p->length == 842)\n fputs(\"%%BeginFeature: *PageSize A4\\n\", out);\n else\n fprintf(out, \"%%%%BeginFeature: *PageSize w%dh%d\\n\", p->width,\n\t p->length);", " fprintf(out, \"%d %d SetPageSize\\n\", p->width, p->length);\n fputs(\"%%EndFeature\\n\", out);", " if (p->duplex)\n {\n if (p->landscape)\n {\n\tfputs(\"%%BeginFeature: *Duplex DuplexTumble\\n\", out);\n\tfputs(\"true true SetDuplexMode\\n\", out);\n fputs(\"%%EndFeature\\n\", out);\n }\n else\n {\n\tfputs(\"%%BeginFeature: *Duplex DuplexNoTumble\\n\", out);\n\tfputs(\"true false SetDuplexMode\\n\", out);\n fputs(\"%%EndFeature\\n\", out);\n }\n }\n else\n {\n fputs(\"%%BeginFeature: *Duplex None\\n\", out);\n fputs(\"false false SetDuplexMode\\n\", out);\n fputs(\"%%EndFeature\\n\", out);\n }", " if (p->media_color[0])\n {\n fprintf(out, \"%%%%BeginFeature: *MediaColor %s\\n\", p->media_color);\n fprintf(out, \"(%s) SetMediaColor\\n\", p->media_color);\n fputs(\"%%EndFeature\\n\", out);\n }", " if (p->media_position)\n {\n fprintf(out, \"%%%%BeginFeature: *InputSlot Tray%d\\n\",\n p->media_position);\n fprintf(out, \"%d SetMediaPosition\\n\", p->media_position);\n fputs(\"%%EndFeature\\n\", out);\n }", " if (p->media_type[0])\n {\n fprintf(out, \"%%%%BeginFeature: *MediaType %s\\n\", p->media_type);\n fprintf(out, \"(%s) SetMediaType\\n\", p->media_type);\n fputs(\"%%EndFeature\\n\", out);\n }", " fputs(\"%%EndPageSetup\\n\", out);\n }", " /*\n * Render all of the pages...\n */", " switch (op->nup)\n {\n case 1 :\n ps_write_page(out, op->pages[0]);\n\tbreak;", " default :\n for (i = 0; i < op->nup; i ++)\n\t{\n\t if (op->pages[i] < 0)\n\t break;", " p = pages + op->pages[i];", " fprintf(out, \"GS[%.3f %.3f %.3f %.3f %.3f %.3f]CM\\n\",\n\t p->outmatrix[0][0], p->outmatrix[1][0],\n\t p->outmatrix[0][1], p->outmatrix[1][1],\n\t p->outmatrix[0][2], p->outmatrix[1][2]);\n ps_write_page(out, op->pages[i]);\n\t fputs(\"GR\\n\", out);\n\t}\n\tbreak;\n }", " /*\n * Output the page trailer...\n */", " fputs(\"SP\\n\", out);\n fflush(out);\n}", "\n/*\n * 'ps_write_page()' - Write all render entities on a page to a PostScript file.\n */", "static void\nps_write_page(FILE *out,\t/* I - Output file */\n int page)\t/* I - Page number */\n{\n render_t\t*r,\t\t/* Render pointer */\n\t\t*next;\t\t/* Next render */\n page_t\t*p;\t\t/* Current page */\n const char\t*debug;\t\t/* HTMLDOC_DEBUG environment variable */", "\n if (page < 0 || page >= (int)alloc_pages)\n return;", " p = pages + page;", " DEBUG_printf((\"ps_write_page(%p, %d)\\n\", (void *)out, page));", " /*\n * Clear the render cache...\n */", " render_typeface = -1;\n render_style = -1;\n render_size = -1;\n render_rgb[0] = -1.0f;\n render_rgb[1] = -1.0f;\n render_rgb[2] = -1.0f;\n render_x = -1.0f;\n render_y = -1.0f;\n render_spacing = -1.0f;", " /*\n * Setup the page...\n */", " fputs(\"GS\\n\", out);", " if (p->landscape)\n {\n if (p->duplex && (page & 1))\n fprintf(out, \"0 %d T -90 RO\\n\", p->length);\n else\n fprintf(out, \"%d 0 T 90 RO\\n\", p->width);\n }", " write_background(page, out);", " if (p->duplex && (page & 1))\n fprintf(out, \"%d %d T\\n\", p->right, p->bottom);\n else\n fprintf(out, \"%d %d T\\n\", p->left, p->bottom);", " /*\n * Render all graphics elements...\n */", " for (r = p->start; r != NULL; r = r->next)\n switch (r->type)\n {\n case RENDER_BOX :\n\t set_color(out, r->data.box);\n\t set_pos(out, r->x, r->y);\n\t if (r->height > 0.0f)\n fprintf(out, \" %.1f %.1f F\\n\", r->width, r->height);\n\t else\n fprintf(out, \" %.1f L\\n\", r->width);", "\t render_x = -1.0f;\n\t break;", " case RENDER_IMAGE :\n if (r->width > 0.01f && r->height > 0.01f)\n write_image(out, r);\n break;\n }", " /*\n * Render all text elements, freeing used memory as we go...\n */", " for (r = p->start, next = NULL; r != NULL; r = next)\n {\n if (r->type == RENDER_TEXT)\n write_text(out, r);", " next = r->next;\n free(r);\n }", " p->start = NULL;", " if ((debug = getenv(\"HTMLDOC_DEBUG\")) != NULL && strstr(debug, \"margin\"))\n {\n // Show printable area...\n fprintf(out, \"1 0 1 C 0 0 %d %d B\\n\", p->width - p->right - p->left,\n \t p->length - p->top - p->bottom);\n }", " /*\n * Output the page trailer...\n */", " fputs(\"GR\\n\", out);\n}", "\n/*\n * 'ps_write_background()' - Write a background image...\n */", "static void\nps_write_background(FILE *out)\t\t/* I - Output file */\n{\n int\ty,\t\t\t\t/* Current line */\n\tpwidth;\t\t\t\t/* Pixel width */", "\n if (!background_image->pixels)\n image_load(background_image->filename, !OutputColor, 1);", " pwidth = background_image->width * background_image->depth;", " fputs(\"/BG[\", out);\n for (y = 0; y < background_image->height; y ++)\n {\n putc('<', out);\n ps_hex(out, background_image->pixels + y * pwidth, pwidth);\n putc('>', out);\n }\n fputs(\"]def\", out);", " image_unload(background_image);\n}", "\n/*\n * 'pdf_write_document()' - Write all render entities to a PDF file.\n */", "static void\npdf_write_document(uchar *author,\t// I - Author of document\n \t uchar *creator,\t// I - Application that generated the HTML file\n \t uchar *copyright,\t// I - Copyright (if any) on the document\n uchar *keywords,\t// I - Search keywords\n\t\t uchar *subject,\t// I - Subject\n\t\t uchar *lang,\t// I - Language\n\t\t tree_t *doc,\t\t// I - Document\n tree_t *toc)\t\t// I - Table of contents tree\n{\n int\t\ti;\t\t\t// Looping variable\n FILE\t\t*out;\t\t\t// Output file\n int\t\toutpage,\t\t// Current page #\n\t\theading;\t\t// Current heading #\n int\t\tbytes;\t\t\t// Number of bytes\n char\t\tbuffer[8192];\t\t// Copy buffer\n int\t\tnum_images;\t\t// Number of images in document\n image_t\t**images;\t\t// Pointers to images\n render_t\ttemp;\t\t\t// Dummy rendering data...", "\n // Open the output file...\n out = open_file();\n if (out == NULL)\n {\n progress_error(HD_ERROR_WRITE_ERROR,\n \"Unable to write document file - %s\\n\", strerror(errno));\n return;\n }", " // Clear the objects array...\n num_objects = 0;\n alloc_objects = 0;\n objects = NULL;", " // Write the prolog...\n write_prolog(out, num_outpages, author, creator, copyright, keywords, subject);", " // Write images as needed...\n num_images = image_getlist(&images);", " for (i = 0; i < num_images; i ++)\n {\n int\thfi;\t\t\t\t// Header/footer image index", "\n for (hfi = 0; hfi < MAX_HF_IMAGES; hfi ++)\n if (images[i] == hfimage[hfi])\n break;", " if (images[i]->use > 1 || images[i]->mask ||\n (images[i]->width * images[i]->height * images[i]->depth) > 65536 ||\n\timages[i] == background_image ||\n\timages[i] == logo_image ||\n\thfi < MAX_HF_IMAGES)\n {\n progress_show(\"Writing image %d (%s)...\", i + 1, images[i]->filename);\n progress_update(100 * i / num_images);", " temp.data.image = images[i];\n write_image(out, &temp, 1);\n }\n }", " // Write links and target names...\n pdf_write_links(out);\n if (PDFVersion >= 12)\n pdf_write_names(out);", " // Verify that everything is working so far...\n pdf_start_object(out);", " if (pages_object != (int)num_objects)\n progress_error(HD_ERROR_INTERNAL_ERROR,\n \"Internal error: pages_object != num_objects\");", " fputs(\"/Type/Pages\", out);\n fprintf(out, \"/Count %d\", (int)num_outpages);\n fputs(\"/Kids[\", out);", " for (outpage = 0; outpage < (int)num_outpages; outpage ++)\n fprintf(out, \"%d 0 R\\n\", pages_object + outpage * 2 + 1);", " fputs(\"]\", out);\n pdf_end_object(out);", " for (outpage = 0; outpage < (int)num_outpages; outpage ++)\n pdf_write_outpage(out, outpage);", " if (OutputType == OUTPUT_BOOK && TocLevels > 0)\n {\n /*\n * Write the outline tree using the table-of-contents...\n */", " heading = 0;\n#ifdef DEBUG_TOC\n pdf_text_contents(out, toc);\n#endif // DEBUG_TOC\n pdf_write_contents(out, toc, 0, 0, 0, &heading);\n }\n else\n {\n /*\n * Write the outline tree using the HTML files.\n */", " pdf_write_files(out, doc);\n }", " /*\n * Write the trailer and close the output file...\n */", " write_trailer(out, 0, lang);", " progress_error(HD_ERROR_NONE, \"BYTES: %ld\", ftell(out));", " if (CGIMode)\n {\n const char\t*meta_filename = (const char *)htmlGetMeta(doc, (uchar *)\"HTMLDOC.filename\");\n const char\t*filename;", " if (meta_filename)\n {\n if ((filename = strrchr(meta_filename, '/')) != NULL)\n filename ++;\n else\n filename = meta_filename;\n }\n else\n filename = \"htmldoc.pdf\";", " // In CGI mode, we only produce PDF output to stdout...\n printf(\"Content-Type: application/pdf\\r\\n\"\n\t \"Content-Length: %ld\\r\\n\"\n\t \"Content-Disposition: inline; filename=\\\"%s\\\"\\r\\n\"\n\t \"Accept-Ranges: none\\r\\n\"\n\t \"X-Creator: HTMLDOC \" SVERSION \"\\r\\n\"\n\t \"\\r\\n\", ftell(out), filename);\n }", " fclose(out);", " //\n // If we are sending the output to stdout, copy the temp file now...\n //", " if (!OutputPath[0])\n {\n#ifdef WIN32\n // Make sure we are in binary mode... stupid Microsoft!\n setmode(1, O_BINARY);\n#elif defined(__EMX__)\n // OS/2 has a setmode for FILE's...\n fflush(stdout);\n _fsetmode(stdout, \"b\");\n#endif // WIN32 || __EMX__", " // Open the temporary file and copy it to stdout...\n out = fopen(stdout_filename, \"rb\");", " while ((bytes = fread(buffer, 1, sizeof(buffer), out)) > 0)\n fwrite(buffer, 1, (size_t)bytes, stdout);", " // Close the temporary file (it is removed when the program exits...)\n fclose(out);\n }", " // Clear the objects array...\n if (alloc_objects)\n {\n free(objects);", " num_objects = 0;\n alloc_objects = 0;\n objects = NULL;\n }", " if (Verbosity)\n progress_hide();\n}", "\n/*\n * 'pdf_write_resources()' - Write the resources dictionary for a page.\n */", "static void\npdf_write_resources(FILE *out,\t\t/* I - Output file */\n int outpage)\t/* I - Output page for resources */\n{\n int\t\ti;\t\t\t/* Looping var */\n outpage_t\t*op;\t\t\t/* Current output page */\n page_t\t*p;\t\t\t/* Current page */\n render_t\t*r;\t\t\t/* Render pointer */\n int\t\tfonts_used[TYPE_MAX * STYLE_MAX];\n\t\t\t\t\t/* Non-zero if the page uses a font */\n int\t\timages_used;\t\t/* Non-zero if the page uses an image */\n int\t\ttext_used;\t\t/* Non-zero if the page uses text */\n static const char *effects[] =\t/* Effects and their commands */\n\t\t{\n\t\t \"\",\n\t\t \"/S/Box/M/I\",\n\t\t \"/S/Box/M/O\",\n\t\t \"/S/Dissolve\",\n\t\t \"/S/Glitter/Di 270\",\n\t\t \"/S/Glitter/Di 315\",\n\t\t \"/S/Glitter/Di 0\",\n\t\t \"/S/Blinds/Dm/H\",\n\t\t \"/S/Split/Dm/H/M/I\",\n\t\t \"/S/Split/Dm/H/M/O\",\n\t\t \"/S/Blinds/Dm/V\",\n\t\t \"/S/Split/Dm/V/M/I\",\n\t\t \"/S/Split/Dm/V/M/O\",\n\t\t \"/S/Wipe/Di 270\",\n\t\t \"/S/Wipe/Di 180\",\n\t\t \"/S/Wipe/Di 0\",\n\t\t \"/S/Wipe/Di 90\"\n\t\t};", "\n memset(fonts_used, 0, sizeof(fonts_used));\n images_used = background_image != NULL;\n text_used = 0;", " op = outpages + outpage;\n for (i = 0; i < op->nup; i ++)\n {\n if (op->pages[i] < 0)\n break;", " p = pages + op->pages[i];", " for (r = p->start; r != NULL; r = r->next)\n if (r->type == RENDER_IMAGE)\n\timages_used = 1;\n else if (r->type == RENDER_TEXT)\n {\n\ttext_used = 1;\n\tfonts_used[r->data.text.typeface * 4 + r->data.text.style] = 1;\n }\n }", " fputs(\"/Resources<<\", out);", " if (!images_used)\n fputs(\"/ProcSet[/PDF/Text]\", out);\n else if (PDFVersion >= 12)\n {\n if (OutputColor)\n fputs(\"/ProcSet[/PDF/Text/ImageB/ImageC/ImageI]\", out);\n else\n fputs(\"/ProcSet[/PDF/Text/ImageB/ImageI]\", out);\n }\n else\n {\n if (OutputColor)\n fputs(\"/ProcSet[/PDF/Text/ImageB/ImageC]\", out);\n else\n fputs(\"/ProcSet[/PDF/Text/ImageB]\", out);\n }", " if (text_used)\n {\n fputs(\"/Font<<\", out);\n for (i = 0; i < (TYPE_MAX * STYLE_MAX); i ++)\n if (fonts_used[i])\n\tfprintf(out, \"/F%x %d 0 R\", i, font_objects[i]);\n fputs(\">>\", out);\n }", " fputs(\"/XObject<<\", out);", " for (i = 0; i < op->nup; i ++)\n {\n if (op->pages[i] < 0)\n break;", " p = pages + op->pages[i];", " for (r = p->start; r != NULL; r = r->next)\n if (r->type == RENDER_IMAGE && r->data.image->obj)\n\tfprintf(out, \"/I%d %d 0 R\", r->data.image->obj, r->data.image->obj);\n }", " if (background_image)\n fprintf(out, \"/I%d %d 0 R\", background_image->obj,\n background_image->obj);", " fputs(\">>>>\", out);", " if (PDFEffect)\n fprintf(out, \"/Dur %.0f/Trans<</Type/Trans/D %.1f%s>>\", PDFPageDuration,\n PDFEffectDuration, effects[PDFEffect]);\n}", "\n/*\n * 'pdf_write_outpage()' - Write an output page.\n */", "static void\npdf_write_outpage(FILE *out,\t/* I - Output file */\n int outpage)\t/* I - Output page number */\n{\n int\t\ti;\t\t/* Looping var */\n page_t\t*p;\t\t/* Current page */\n outpage_t\t*op;\t\t/* Output page */", "\n DEBUG_printf((\"pdf_write_outpage(out = %p, outpage = %d)\\n\", (void *)out, outpage));", " if (outpage < 0 || outpage >= (int)num_outpages)\n return;", " op = outpages + outpage;\n p = pages + op->pages[0];", " DEBUG_printf((\"op->pages[0] = %d (%dx%d)\\n\", op->pages[0], p->width,\n p->length));", " /*\n * Let the user know which page we are writing...\n */", " if (Verbosity)\n {\n progress_show(\"Writing page %s...\", p->page_text);\n progress_update(100 * outpage / (int)num_outpages);\n }", " /*\n * Output the page prolog...\n */", " pdf_start_object(out);", " fputs(\"/Type/Page\", out);\n fprintf(out, \"/Parent %d 0 R\", pages_object);\n fprintf(out, \"/Contents %d 0 R\", (int)num_objects + 1);\n if (p->landscape)\n fprintf(out, \"/MediaBox[0 0 %d %d]\", p->length, p->width);\n else\n fprintf(out, \"/MediaBox[0 0 %d %d]\", p->width, p->length);", " pdf_write_resources(out, outpage);", " /*\n * Actions (links)...\n */", " if (op->annot_object > 0)\n fprintf(out, \"/Annots %d 0 R\", op->annot_object);", " pdf_end_object(out);", " pdf_start_object(out);", " if (Compression)\n fputs(\"/Filter/FlateDecode\", out);", " pdf_start_stream(out);", " flate_open_stream(out);", " /*\n * Render all of the pages...\n */", " switch (op->nup)\n {\n case 1 :\n pdf_write_page(out, op->pages[0]);\n\tbreak;", " default :\n for (i = 0; i < op->nup; i ++)\n\t{\n\t if (op->pages[i] < 0)\n\t break;", " p = pages + op->pages[i];", " flate_printf(out, \"q %.3f %.3f %.3f %.3f %.3f %.3f cm\\n\",\n\t p->outmatrix[0][0], p->outmatrix[1][0],\n\t p->outmatrix[0][1], p->outmatrix[1][1],\n\t p->outmatrix[0][2], p->outmatrix[1][2]);\n pdf_write_page(out, op->pages[i]);\n\t flate_puts(\"Q\\n\", out);\n\t}\n\tbreak;\n }", " /*\n * Close out the page...\n */", " flate_close_stream(out);", " pdf_end_object(out);\n}", "\n/*\n * 'pdf_write_page()' - Write a page to a PDF file.\n */", "static void\npdf_write_page(FILE *out,\t/* I - Output file */\n int page)\t/* I - Page number */\n{\n render_t\t*r,\t\t/* Render pointer */\n\t\t*next;\t\t/* Next render */\n float\t\tbox[3];\t\t/* RGB color for boxes */\n page_t\t*p;\t\t/* Current page */\n const char\t*debug;\t\t/* HTMLDOC_DEBUG environment variable */", "\n if (page < 0 || page >= (int)alloc_pages)\n return;", " p = pages + page;", " /*\n * Clear the render cache...\n */", " render_rgb[0] = -1.0f;\n render_rgb[1] = -1.0f;\n render_rgb[2] = -1.0f;\n render_x = -1.0f;\n render_y = -1.0f;", " /*\n * Output the page header...\n */", " flate_puts(\"q\\n\", out);\n write_background(page, out);", " if (p->duplex && (page & 1))\n flate_printf(out, \"1 0 0 1 %d %d cm\\n\", p->right,\n p->bottom);\n else\n flate_printf(out, \"1 0 0 1 %d %d cm\\n\", p->left,\n p->bottom);", " /*\n * Render all graphics elements...\n */", " box[0] = -1.0f;\n box[1] = -1.0f;\n box[2] = -1.0f;", " for (r = p->start; r != NULL; r = r->next)\n switch (r->type)\n {\n case RENDER_IMAGE :\n if (r->width > 0.01f && r->height > 0.01f)\n write_image(out, r);\n break;", " case RENDER_BOX :\n\t if (r->height == 0.0)\n\t {\n if (box[0] != r->data.box[0] ||\n\t\tbox[1] != r->data.box[1] ||\n\t\tbox[2] != r->data.box[2])\n {\n box[0] = r->data.box[0];\n\t box[1] = r->data.box[1];\n\t box[2] = r->data.box[2];", "\t if (OutputColor)\n \tflate_printf(out, \"%.2f %.2f %.2f RG\\n\", box[0], box[1], box[2]);\n else\n \tflate_printf(out, \"%.2f G\\n\",\n\t\t box[0] * 0.31f + box[1] * 0.61f + box[2] * 0.08f);\n }", " flate_printf(out, \"%.1f %.1f m %.1f %.1f l S\\n\",\n \t r->x, r->y, r->x + r->width, r->y);\n\t }\n\t else\n\t {\n set_color(out, r->data.box);\n flate_printf(out, \"%.1f %.1f %.1f %.1f re f\\n\",\n \t r->x, r->y, r->width, r->height);\n\t }\n\t break;\n }", " /*\n * Render all text elements, freeing used memory as we go...\n */", " flate_puts(\"BT\\n\", out);", " render_typeface = -1;\n render_style = -1;\n render_size = -1;\n render_x = -1.0f;\n render_y = -1.0f;\n render_spacing = -1.0f;", " for (r = p->start, next = NULL; r != NULL; r = next)\n {\n if (r->type == RENDER_TEXT)\n write_text(out, r);", " next = r->next;\n free(r);\n }", " p->start = NULL;", " flate_puts(\"ET\\n\", out);", " if ((debug = getenv(\"HTMLDOC_DEBUG\")) != NULL && strstr(debug, \"margin\"))\n {\n // Show printable area...\n flate_printf(out, \"1 0 1 RG 0 0 %d %d re S\\n\", p->width - p->right - p->left,\n \t p->length - p->top - p->bottom);\n }", " /*\n * Output the page trailer...\n */", " flate_puts(\"Q\\n\", out);\n}", "\n#ifdef DEBUG_TOC\nstatic void\npdf_text_contents(FILE *out, tree_t *toc, int indent)\n{\n static const char *spaces = \" \"\n \" \";", " if (indent > 16)\n indent = 16;", " while (toc)\n {\n fprintf(out, \"%% %s<%s>\", spaces + 64 - 4 * indent,\n _htmlMarkups[toc->markup]);", " switch (toc->markup)\n {\n case MARKUP_A :\n tree_t *temp;", " for (temp = toc->child; temp; temp = temp->next)\n\t fputs((char *)temp->data, out);\n break;", " default :\n fputs(\"\\n\", out);\n\t pdf_text_contents(out, toc->child, indent + 1);\n\t fprintf(out, \"%% %s\", spaces + 64 - 4 * indent);\n break;\n }", " fprintf(out, \"</%s>\\n\", _htmlMarkups[toc->markup]);", " toc = toc->next;\n }\n}\n#endif // DEBUG_TOC", "\n/*\n * 'pdf_write_contents()' - Write the table of contents as outline records to\n * a PDF file.\n */", "static void\npdf_write_contents(FILE *out,\t\t\t/* I - Output file */\n tree_t *toc,\t\t\t/* I - Table of contents tree */\n int parent,\t\t/* I - Parent outline object */\n int prev,\t\t\t/* I - Previous outline object */\n int next,\t\t\t/* I - Next outline object */\n int *heading)\t\t/* IO - Current heading # */\n{\n int\t\ti,\t\t\t\t/* Looping var */\n\t\tthisobj,\t\t\t/* This object */\n\t\tentry,\t\t\t\t/* TOC entry object */\n\t\tcount;\t\t\t\t/* Number of entries at this level */\n uchar\t\t*text;\t\t\t\t/* Entry text */\n tree_t\t*temp;\t\t\t\t/* Looping var */\n int\t\t*entry_counts,\t\t\t/* Number of sub-entries for this entry */\n\t\t*entry_objects;\t\t\t/* Objects for each entry */\n tree_t\t**entries;\t\t\t/* Pointers to each entry */\n float\t\tx, y;\t\t\t\t/* Position of link */", "\n /*\n * Make an object for this entry...\n */", " if (toc == NULL)\n {\n /*\n * This is for the Table of Contents page...\n */", " thisobj = pdf_start_object(out);", " fprintf(out, \"/Parent %d 0 R\", parent);", " fputs(\"/Title\", out);\n write_utf16(out, (uchar *)TocTitle);", " x = 0.0f;\n y = PagePrintLength + PageBottom;\n pspdf_transform_coords(pages + chapter_starts[0], x, y);", " fprintf(out, \"/Dest[%d 0 R/XYZ %.0f %.0f 0]\",\n pages_object + 2 * chapter_outstarts[0] + 1, x, y);", " if (prev > 0)\n fprintf(out, \"/Prev %d 0 R\", prev);", " if (next > 0)\n fprintf(out, \"/Next %d 0 R\", next);", " pdf_end_object(out);\n return;\n }", " /*\n * Allocate the arrays... Add 1 to hold the TOC at the top level...\n */", " if ((entry_counts = (int *)calloc(sizeof(int), num_headings + 1)) == NULL)\n {\n progress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory for %d headings - %s\",\n (int)num_headings, strerror(errno));\n return;\n }", " if ((entry_objects = (int *)calloc(sizeof(int), num_headings + 1)) == NULL)\n {\n progress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory for %d headings - %s\",\n (int)num_headings, strerror(errno));\n free(entry_counts);\n return;\n }", " if ((entries = (tree_t **)calloc(sizeof(tree_t *), num_headings + 1)) == NULL)\n {\n progress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory for %d headings - %s\",\n (int)num_headings, strerror(errno));\n free(entry_objects);\n free(entry_counts);\n return;\n }", " if (parent == 0 && TocLevels > 0)\n {\n /*\n * Add the table of contents to the top-level contents...\n */", " entries[0] = NULL;\n entry_objects[0] = num_objects + 2;\n entry = num_objects + 3;\n count = 1;\n }\n else\n {\n entry = num_objects + 2;\n count = 0;\n }", " /*\n * Find and count the children (entries)...\n */", " if (toc->markup == MARKUP_B && toc->next && toc->next->markup == MARKUP_UL)\n temp = toc->next->child;\n else if (toc->markup == MARKUP_LI && toc->last_child &&\n toc->last_child->markup == MARKUP_UL)\n temp = toc->last_child->child;\n else\n temp = toc->child;", " for (; temp && count <= (int)num_headings; temp = temp->next)\n {\n if (temp->markup == MARKUP_B)\n {\n entries[count] = temp;\n entry_objects[count] = entry;", " if (temp->next && temp->next->markup == MARKUP_UL)\n entry_counts[count] = pdf_count_headings(temp->next->child);\n else\n entry_counts[count] = 0;", " entry += entry_counts[count] + 1;\n count ++;\n }\n else if (temp->markup == MARKUP_LI)\n {\n entries[count] = temp;\n entry_objects[count] = entry;", " if (temp->last_child && temp->last_child->markup == MARKUP_UL)\n entry_counts[count] = pdf_count_headings(temp->last_child);\n else\n entry_counts[count] = 0;", " entry += entry_counts[count] + 1;\n count ++;\n }\n }", " /*\n * Output the top-level object...\n */", " thisobj = pdf_start_object(out);", " if (parent == 0)\n outline_object = thisobj;\n else\n fprintf(out, \"/Parent %d 0 R\", parent);", " if (count > 0)\n {\n fprintf(out, \"/Count %d\", parent == 0 ? count : -count);\n fprintf(out, \"/First %d 0 R\", entry_objects[0]);\n fprintf(out, \"/Last %d 0 R\", entry_objects[count - 1]);\n }", " if (parent > 0 && toc->child && toc->child->markup == MARKUP_A)\n {\n if ((text = htmlGetText(toc->child->child)) != NULL)\n {\n fputs(\"/Title\", out);\n write_utf16(out, text);\n free(text);\n }", " i = heading_pages[*heading];\n x = 0.0f;\n y = heading_tops[*heading] + pages[i].bottom;\n pspdf_transform_coords(pages + i, x, y);", " fprintf(out, \"/Dest[%d 0 R/XYZ %.0f %.0f 0]\",\n pages_object + 2 * pages[i].outpage + 1, x, y);", " (*heading) ++;\n }", " if (prev > 0)\n fprintf(out, \"/Prev %d 0 R\", prev);", " if (next > 0)\n fprintf(out, \"/Next %d 0 R\", next);", " pdf_end_object(out);", " for (i = 0; i < count ; i ++)\n pdf_write_contents(out, entries[i], thisobj, i > 0 ? entry_objects[i - 1] : 0,\n i < (count - 1) ? entry_objects[i + 1] : 0,\n heading);", " free(entry_objects);\n free(entry_counts);\n free(entries);\n}", "\n//\n// 'pdf_write_files()' - Write an outline of HTML files.\n//", "static void\npdf_write_files(FILE *out,\t\t// I - Output file\n tree_t *doc)\t\t// I - Document tree\n{\n int\t\ti,\t\t\t// Looping var\n\t\tnum_files,\t\t// Number of FILE elements\n\t\talloc_text;\t\t// Allocated text?\n uchar\t\t*text;\t\t\t// Entry text\n tree_t\t*temp;\t\t\t// Current node\n link_t\t*link;\t\t\t// Link to file...\n float\t\tx, y;\t\t\t// Position of link", "\n // Figure out the number of (top-level) files in the document...\n for (num_files = 0, temp = doc; temp; temp = temp->next)\n if (temp->markup == MARKUP_FILE)\n num_files ++;", " if (num_files < 2)\n {\n // No files to outline...\n outline_object = 0;", " return;\n }", " // Write the outline dictionary...\n outline_object = pdf_start_object(out);", " fprintf(out, \"/Count %d\", num_files);\n fprintf(out, \"/First %d 0 R\", outline_object + 1);\n fprintf(out, \"/Last %d 0 R\", outline_object + num_files);", " pdf_end_object(out);", " // Now write the outline items...\n for (i = 0, temp = doc; temp; temp = temp->next)\n if (temp->markup == MARKUP_FILE)\n {\n alloc_text = 0;", " if ((text = get_title(temp->child)) != NULL)\n alloc_text = 1;\n else if ((text = htmlGetVariable(temp, (uchar *)\"_HD_FILENAME\")) == NULL)\n text = (uchar *)\"Unknown\";", " pdf_start_object(out);", " fprintf(out, \"/Parent %d 0 R\", outline_object);", " fputs(\"/Title\", out);\n write_utf16(out, text);\n if (alloc_text)\n free(text);", " if ((link = find_link(htmlGetVariable(temp, (uchar *)\"_HD_FILENAME\"))) != NULL)\n {\n\tx = 0.0f;\n\ty = link->top + pages[link->page].bottom;\n\tpspdf_transform_coords(pages + link->page, x, y);", "\tfprintf(out, \"/Dest[%d 0 R/XYZ %.0f %.0f 0]\",\n \tpages_object + 2 * pages[link->page].outpage + 1, x, y);\n }", " if (i > 0)\n fprintf(out, \"/Prev %d 0 R\", outline_object + i);", " if (i < (num_files - 1))\n fprintf(out, \"/Next %d 0 R\", outline_object + i + 2);", " pdf_end_object(out);", " i ++;\n }\n}", "\n/*\n * 'pdf_count_headings()' - Count the number of headings under this TOC\n * entry.\n */", "static int\t\t\t/* O - Number of headings found */\npdf_count_headings(tree_t *toc)\t/* I - TOC entry */\n{\n int\theadings;\t\t/* Number of headings */", "\n for (headings = 0; toc != NULL; toc = toc->next)\n {\n if (toc->markup == MARKUP_A)\n headings ++;\n if (toc->child != NULL)\n headings += pdf_count_headings(toc->child);\n }", " return (headings);\n}", "\n/*\n * PDF object state variables...\n */", "static int\tpdf_stream_length = 0;\nstatic int\tpdf_stream_start = 0;\nstatic int\tpdf_object_type = 0;", "\n/*\n * 'pdf_start_object()' - Start a new PDF object...\n */", "static int\t\t\t// O - Object number\npdf_start_object(FILE *out,\t// I - File to write to\n int array)\t// I - 1 = array, 0 = dictionary\n{\n int\t*temp;\t\t\t// Temporary integer pointer", "\n num_objects ++;", " // Allocate memory as necessary...\n if (num_objects >= alloc_objects)\n {\n alloc_objects += ALLOC_OBJECTS;", " if (alloc_objects == ALLOC_OBJECTS)\n temp = (int *)malloc(sizeof(int) * alloc_objects);\n else\n temp = (int *)realloc(objects, sizeof(int) * alloc_objects);", " if (temp == NULL)\n {\n progress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory for %d objects - %s\",\n (int)alloc_objects, strerror(errno));\n alloc_objects -= ALLOC_OBJECTS;\n return (0);\n }", " objects = temp;\n }", " objects[num_objects] = ftell(out);\n fprintf(out, \"%d 0 obj\", (int)num_objects);", " pdf_object_type = array;", " fputs(pdf_object_type ? \"[\" : \"<<\", out);", " return (num_objects);\n}", "\n/*\n * 'pdf_start_stream()' - Start a new PDF stream...\n */", "static void\npdf_start_stream(FILE *out)\t// I - File to write to\n{\n // Write the \"/Length \" string, get the position, and then write 10\n // zeroes to cover the maximum size of a stream.", " fputs(\"/Length \", out);\n pdf_stream_length = ftell(out);\n fputs(\"0000000000>>stream\\n\", out);\n pdf_stream_start = ftell(out);\n}", "\n/*\n * 'pdf_end_object()' - End a PDF object...\n */", "static void\npdf_end_object(FILE *out)\t// I - File to write to\n{\n int\tlength;\t\t\t// Total length of stream", "\n if (pdf_stream_start)\n {\n // For streams, go back and update the length field in the\n // object dictionary...\n length = ftell(out) - pdf_stream_start;", " fseek(out, pdf_stream_length, SEEK_SET);\n fprintf(out, \"%-10d\", length);\n fseek(out, 0, SEEK_END);", " pdf_stream_start = 0;", " fputs(\"endstream\\n\", out);\n }\n else\n fputs(pdf_object_type ? \"]\" : \">>\", out);", " fputs(\"endobj\\n\", out);\n}", "\n/*\n * 'pdf_write_links()' - Write annotation link objects for each page in the\n * document.\n */", "static void\npdf_write_links(FILE *out)\t\t/* I - Output file */\n{\n int\t\ti,\t\t\t/* Looping var */\n\t\toutpage,\t\t/* Current page */\n\t\tlobj,\t\t\t/* Current link */\n\t\tnum_lobjs,\t\t/* Number of links on this page */\n\t\talloc_lobjs,\t\t/* Number of links to allocate */\n\t\t*lobjs;\t\t\t/* Link objects */\n float\t\tx, y;\t\t\t/* Position of last link */\n render_t\t*r,\t\t\t/* Current render primitive */\n\t\t*rlast,\t\t\t/* Last render link primitive */\n\t\t*rprev;\t\t\t/* Previous render primitive */\n link_t\t*link;\t\t\t/* Local link */\n page_t\t*p;\t\t\t/* Current page */\n outpage_t\t*op;\t\t\t/* Current output page */", "\n /*\n * First combine adjacent, identical links...\n */", " for (outpage = 0, op = outpages; outpage < (int)num_outpages; outpage ++, op ++)\n {\n for (i = 0; i < op->nup; i ++)\n {\n if (op->pages[i] < 0)\n break;", " p = pages + op->pages[i];", " for (r = p->start, x = 0.0f, y = 0.0f, rlast = NULL, rprev = NULL;\n r != NULL;\n\t rprev = r, r = r->next)\n\tif (r->type == RENDER_LINK)\n\t{\n if (fabs(r->x - x) < 0.1f && fabs(r->y - y) < 0.1f &&\n\t rlast != NULL && strcmp((const char *)rlast->data.link,\n\t (const char *)r->data.link) == 0)\n\t {\n\t // Combine this primitive with the previous one in rlast...\n\t rlast->width = r->x + r->width - rlast->x;\n\t x = rlast->x + rlast->width;", "\t // Delete this render primitive...\n\t rprev->next = r->next;\n\t free(r);\n\t r = rprev;\n\t }\n\t else\n\t {\n\t // Can't combine; just save this info for later use...\n\t rlast = r;\n\t x = r->x + r->width;\n\t y = r->y;\n\t }\n\t}\n }\n }", " /*\n * Setup the initial pages_object number...\n */", " pages_object = num_objects + 1;", " /*\n * Add space for named links in PDF 1.2 output...\n */", " if (PDFVersion >= 12)\n pages_object += num_links + 3;", " /*\n * Stop here if we won't be generating links in the output...\n */", " if (!Links)\n return;", " /*\n * Figure out how many link objects we'll have...\n */", " for (outpage = 0, op = outpages, alloc_lobjs = 0;\n outpage < (int)num_pages;\n outpage ++, op ++)\n {\n num_lobjs = 0;", " for (i = 0; i < op->nup; i ++)\n {\n if (op->pages[i] < 0)\n break;", " p = pages + op->pages[i];", " for (r = p->start; r != NULL; r = r->next)\n\tif (r->type == RENDER_LINK)\n\t{\n if (find_link(r->data.link) != NULL)\n num_lobjs ++;\n else\n num_lobjs += 2;\n\t}\n }", " if (num_lobjs > 0)\n pages_object += num_lobjs + 1;", " if (num_lobjs > alloc_lobjs)\n alloc_lobjs = num_lobjs;\n }", " if (alloc_lobjs == 0)\n return;", " /*\n * Allocate memory for the links...\n */", " if ((lobjs = (int *)malloc(sizeof(int) * (size_t)alloc_lobjs)) == NULL)\n {\n progress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory for %d link objects - %s\",\n alloc_lobjs, strerror(errno));\n return;\n }", " /*\n * Then generate annotation objects for all the links...\n */", " for (outpage = 0, op = outpages; outpage < (int)num_pages; outpage ++, op ++)\n {\n num_lobjs = 0;", " for (i = 0; i < op->nup; i ++)\n {\n if (op->pages[i] < 0)\n break;", " p = pages + op->pages[i];", " for (r = p->start; r != NULL; r = r->next)\n\tif (r->type == RENDER_LINK)\n\t{\n if ((link = find_link(r->data.link)) != NULL)\n\t {\n\t /*\n * Local link...\n */\n\t float x1, y1, x2, y2;", " lobjs[num_lobjs ++] = pdf_start_object(out);", " fputs(\"/Subtype/Link\", out);", " if (PageDuplex && (op->pages[i] & 1))\n\t {\n x1 = r->x + p->right;\n\t y1 = r->y + p->bottom - 2;\n x2 = r->x + r->width + p->right;\n\t y2 = r->y + r->height + p->bottom;\n\t }\n else\n\t {\n x1 = r->x + p->left;\n\t y1 = r->y + p->bottom - 2;\n x2 = r->x + r->width + p->left;\n\t y2 = r->y + r->height + p->bottom;\n\t }", " pspdf_transform_coords(p, x1, y1);\n pspdf_transform_coords(p, x2, y2);\n fprintf(out, \"/Rect[%.1f %.1f %.1f %.1f]\", x1, y1, x2, y2);", " fputs(\"/Border[0 0 0]\", out);", " x1 = 0.0f;\n\t y1 = link->top + pages[link->page].bottom;\n pspdf_transform_coords(pages + link->page, x1, y1);\n\t fprintf(out, \"/Dest[%d 0 R/XYZ %.0f %.0f 0]\",\n \t pages_object + 2 * pages[link->page].outpage + 1,\n \t x1, y1);\n\t pdf_end_object(out);\n\t }\n\t else\n\t {\n\t /*\n * Remote link...\n */", " pdf_start_object(out);", "\t if (PDFVersion >= 12 &&\n \tfile_method((char *)r->data.link) == NULL)\n\t {\n#ifdef WIN32\n if (strcasecmp(file_extension((char *)r->data.link), \"pdf\") == 0)\n#else\n if (strcmp(file_extension((char *)r->data.link), \"pdf\") == 0)\n#endif /* WIN32 */\n {\n\t /*\n\t\t* Link to external PDF file...\n\t\t*/", " const char *target = file_target((char *)r->data.link);", " \tfputs(\"/S/GoToR\", out);\n \tif (target)\n \t{\n \t char\turl[1024], *urlptr;", "\t\t fputs(\"/D\", out);\n\t\t write_string(out, (uchar *)target, 0);", " strlcpy(url, (char *)r->data.link, sizeof(url));\n if ((urlptr = strrchr(url, '#')) != NULL)\n *urlptr = '\\0';", "\t\t fputs(\"/F\", out);\n\t\t write_string(out, (uchar *)url, 0);\n \t}\n \telse\n \t{\n\t\t fputs(\"/D[0/XYZ null null 0]/F\", out);\n\t\t write_string(out, r->data.link, 0);\n\t\t}\n }\n\t else\n {\n\t /*\n\t\t* Link to external filename...\n\t\t*/", " \tfputs(\"/S/Launch\", out);\n \tfputs(\"/F\", out);\n\t\twrite_string(out, r->data.link, 0);", "\t\tif (StrictHTML)\n\t\t progress_error(HD_ERROR_UNRESOLVED_LINK,\n\t\t \"Unable to resolve link to \\\"%s\\\"!\",\n\t\t r->data.link);\n }\n\t }\n\t else\n\t {\n\t /*\n\t * Link to web file...\n\t */", " fputs(\"/S/URI\", out);\n fputs(\"/URI\", out);\n\t write_string(out, r->data.link, 0);\n\t }", " pdf_end_object(out);", " lobjs[num_lobjs ++] = pdf_start_object(out);", " fputs(\"/Subtype/Link\", out);\n if (PageDuplex && (outpage & 1))\n fprintf(out, \"/Rect[%.1f %.1f %.1f %.1f]\",\n r->x + PageRight, r->y + PageBottom,\n r->x + r->width + PageRight, r->y + r->height + PageBottom);\n else\n fprintf(out, \"/Rect[%.1f %.1f %.1f %.1f]\",\n r->x + PageLeft, r->y + PageBottom - 2,\n r->x + r->width + PageLeft, r->y + r->height + PageBottom);\n fputs(\"/Border[0 0 0]\", out);\n\t fprintf(out, \"/A %d 0 R\", (int)num_objects - 1);\n pdf_end_object(out);\n\t }\n\t}\n }", " if (num_lobjs > 0)\n {\n outpages[outpage].annot_object = pdf_start_object(out, 1);", " for (lobj = 0; lobj < num_lobjs; lobj ++)\n fprintf(out, \"%d 0 R%s\", lobjs[lobj],\n\t lobj < (num_lobjs - 1) ? \"\\n\" : \"\");", " pdf_end_object(out);\n }\n }", " free(lobjs);\n}", "\n/*\n * 'pdf_write_names()' - Write named destinations for each link.\n */", "static void\npdf_write_names(FILE *out)\t\t/* I - Output file */\n{\n int\t\ti;\t\t\t/* Looping var */\n uchar\t\t*s;\t\t\t/* Current character in name */\n link_t\t*link;\t\t\t/* Local link */", "\n /*\n * Convert all link names to lowercase...\n */", " for (i = num_links, link = links; i > 0; i --, link ++)\n for (s = link->name; *s != '\\0'; s ++)\n *s = (uchar)tolower(*s);", " /*\n * Write the root name tree entry...\n */", " names_object = pdf_start_object(out);\n fprintf(out, \"/Dests %d 0 R\", (int)num_objects + 1);\n pdf_end_object(out);", " /*\n * Write the name tree child list...\n */", " pdf_start_object(out);\n fprintf(out, \"/Kids[%d 0 R]\", (int)num_objects + 1);\n pdf_end_object(out);", " /*\n * Write the leaf node for the name tree...\n */", " pdf_start_object(out);", " fputs(\"/Limits[\", out);\n write_string(out, links[0].name, 0);\n write_string(out, links[num_links - 1].name, 0);\n fputs(\"]\", out);", " fputs(\"/Names[\", out);\n for (i = 1, link = links; i <= (int)num_links; i ++, link ++)\n {\n write_string(out, link->name, 0);\n fprintf(out, \"%d 0 R\", (int)num_objects + i);\n }\n fputs(\"]\", out);", " pdf_end_object(out);", " for (i = num_links, link = links; i > 0; i --, link ++)\n {\n pdf_start_object(out);\n float x, y;", " x = 0.0f;\n y = link->top + pages[link->page].bottom;\n pspdf_transform_coords(pages + link->page, x, y);\n fprintf(out, \"/D[%d 0 R/XYZ %.0f %.0f 0]\",\n pages_object + 2 * pages[link->page].outpage + 1, x, y);\n pdf_end_object(out);\n }\n}", "\n/*\n * 'render_contents()' - Render a single heading.\n */", "static void\nrender_contents(tree_t *t,\t\t/* I - Tree to parse */\n float left,\t\t/* I - Left margin */\n float right,\t\t/* I - Printable width */\n float bottom,\t\t/* I - Bottom margin */\n float top,\t\t/* I - Printable top */\n float *y,\t\t/* IO - Y position */\n int *page,\t\t/* IO - Page # */\n\t int heading,\t\t/* I - Heading # */\n\t tree_t *chap)\t\t/* I - Chapter heading */\n{\n float\t\tx,\n\t\twidth,\n\t\tnumberwidth,\n\t\theight,\n\t\trgb[3];\n int\t\thpage;\n uchar\t\tnumber[1024],\n\t\t*nptr,\n\t\t*link;\n tree_t\t*flat,\n\t\t*temp,\n\t\t*next;\n render_t\t*r;\n float\t\tdot_width;", "\n DEBUG_printf((\"render_contents(t=%p, left=%.1f, right=%.1f, bottom=%.1f, top=%.1f, y=%.1f, page=%d, heading=%d, chap=%p)\\n\",\n (void *)t, left, right, bottom, top, *y, *page, heading, (void *)chap));", " if (!t)\n return;", " dot_width = _htmlSizes[SIZE_P] * _htmlWidths[t->typeface][t->style]['.'] * 0.001f;", " /*\n * Put the text...\n */", " flat = flatten_tree(t->child->child);", " for (height = 0.0, temp = flat; temp != NULL; temp = temp->next)\n if (temp->height > height)\n height = temp->height;", " height *= _htmlSpacings[SIZE_P] / _htmlSizes[SIZE_P];", " if (t->indent)\n x = left + 18.0f + 18.0f * t->indent;\n else\n x = left;", " *y -= height;", " /*\n * Get the width of the page number, leave room for three dots...\n */", " if (heading >= 0 && heading < (int)num_headings)\n {\n hpage = heading_pages[heading];\n numberwidth = (float)(get_width((uchar *)pages[hpage].page_text, t->typeface, t->style, t->size) + 3.0f * dot_width);\n }\n else\n {\n hpage = 0;\n numberwidth = 0.0f;\n }", " for (temp = flat; temp != NULL; temp = next)\n {\n rgb[0] = temp->red / 255.0f;\n rgb[1] = temp->green / 255.0f;\n rgb[2] = temp->blue / 255.0f;", " if ((x + temp->width) >= (right - numberwidth))\n {\n /*\n * Too wide to fit, continue on the next line\n */", " *y -= _htmlSpacings[SIZE_P];\n x = left + 36.0f * t->indent;\n }", " if (*y < bottom)\n {\n (*page) ++;\n if (Verbosity)\n\tprogress_show(\"Formatting page %d\", *page);", " width = get_width((uchar *)TocTitle, _htmlHeadingFont, STYLE_BOLD, SIZE_H1);\n *y = (float)(top - _htmlSpacings[SIZE_H1]);\n x = (float)(left + 0.5f * (right - left - width));\n r = new_render(*page, RENDER_TEXT, x, *y, 0, 0, TocTitle);\n r->data.text.typeface = _htmlHeadingFont;\n r->data.text.style = STYLE_BOLD;\n r->data.text.size = (float)_htmlSizes[SIZE_H1];\n get_color(_htmlTextColor, r->data.text.rgb);", " *y -= _htmlSpacings[SIZE_H1];", " if (t->indent)\n\tx = left + 18.0f + 18.0f * t->indent;\n else\n\tx = left;", " if (chap != t)\n {\n *y += height;\n render_contents(chap, left, right, bottom, top, y, page, -1, 0);\n\t*y -= _htmlSpacings[SIZE_P];\n }\n }", " if (temp->link != NULL)\n {\n link = htmlGetVariable(temp->link, (uchar *)\"HREF\");", " /*\n * Add a page link...\n */", " new_render(*page, RENDER_LINK, x, *y, temp->width, temp->height, link);", " if (PSLevel == 0 && Links)\n {\n memcpy(rgb, link_color, sizeof(rgb));", "\ttemp->red = (uchar)(link_color[0] * 255.0);\n\ttemp->green = (uchar)(link_color[1] * 255.0);\n\ttemp->blue = (uchar)(link_color[2] * 255.0);", " if (LinkStyle)\n\t new_render(*page, RENDER_BOX, x, *y - 1, temp->width, 0,\n\t link_color);\n }\n }", " if ((link = htmlGetVariable(temp, (uchar *)\"ID\")) != NULL)\n {\n /*\n * Add a target link...\n */", " add_link(link, *page, (int)(*y + height));\n }", " switch (temp->markup)\n {\n case MARKUP_A :\n if ((link = htmlGetVariable(temp, (uchar *)\"NAME\")) != NULL)\n {\n /*\n * Add a target link...\n */", " add_link(link, *page, (int)(*y + height));\n }\n break;", " case MARKUP_NONE :\n if (temp->data == NULL)\n break;", "\t if (temp->underline)\n\t new_render(*page, RENDER_BOX, x, *y - 1, temp->width, 0, rgb);", "\t if (temp->strikethrough)\n\t new_render(*page, RENDER_BOX, x, *y + temp->height * 0.25f,\n\t\t temp->width, 0, rgb);", " r = new_render(*page, RENDER_TEXT, x, *y, 0, 0, temp->data);\n r->data.text.typeface = temp->typeface;\n r->data.text.style = temp->style;\n r->data.text.size = (float)_htmlSizes[temp->size];\n memcpy(r->data.text.rgb, rgb, sizeof(rgb));", " if (temp->superscript)\n r->y += height - temp->height;\n else if (temp->subscript)\n r->y -= height * _htmlSizes[0] / _htmlSpacings[0] -\n\t\t temp->height;\n\t break;", " case MARKUP_IMG :\n\t update_image_size(temp);\n\t new_render(*page, RENDER_IMAGE, x, *y, temp->width, temp->height,\n\t\t image_find((char *)htmlGetVariable(temp, (uchar *)\"REALSRC\")));\n\t break;", " default :\n\t break;\n }", " x += temp->width;\n next = temp->next;\n free(temp);\n }", " if (numberwidth > 0.0f)\n {\n /*\n * Draw dots leading up to the page number...\n */", " width = (float)(numberwidth - 3.0 * dot_width + x);", " for (nptr = number;\n nptr < (number + sizeof(number) - 1) && width < right;\n\t width += dot_width)\n *nptr++ = '.';", " if (nptr > number)\n nptr --;", " strlcpy((char *)nptr, pages[hpage].page_text, sizeof(number) - (size_t)(nptr - number));", " r = new_render(*page, RENDER_TEXT, right - width + x, *y, 0, 0, number);\n r->data.text.typeface = t->typeface;\n r->data.text.style = t->style;\n r->data.text.size = (float)_htmlSizes[t->size];\n memcpy(r->data.text.rgb, rgb, sizeof(rgb));\n }\n}", "\n/*\n * 'count_headings()' - Count the number of headings in the TOC.\n */", "static int\ncount_headings(tree_t *t)\t\t// I - Tree to count\n{\n int\tcount;\t\t\t\t// Number of headings...", "\n count = 0;", " while (t != NULL)\n {\n switch (t->markup)\n {\n case MARKUP_B :\n case MARKUP_LI :\n count ++;\n\t if (t->last_child && t->last_child->markup == MARKUP_UL)\n\t count += count_headings(t->last_child);\n\t break;", " default :\n count += count_headings(t->child);\n break;\n }", " t = t->next;\n }", " return (count);\n}", "\n/*\n * 'parse_contents()' - Parse the table of contents and produce a\n * rendering list...\n */", "static void\nparse_contents(tree_t *t,\t\t/* I - Tree to parse */\n float left,\t\t/* I - Left margin */\n float right,\t\t/* I - Printable width */\n float bottom,\t\t/* I - Bottom margin */\n float top,\t\t/* I - Printable top */\n float *y,\t\t/* IO - Y position */\n int *page,\t\t/* IO - Page # */\n int *heading,\t\t/* IO - Heading # */\n\t tree_t *chap)\t\t/* I - Chapter heading */\n{\n DEBUG_printf((\"parse_contents(t=%p, left=%.1f, right=%.1f, bottom=%.1f, top=%.1f, y=%.1f, page=%d, heading=%d, chap=%p)\\n\",\n (void *)t, left, right, bottom, top, *y, *page, *heading, (void *)chap));", " while (t != NULL)\n {\n switch (t->markup)\n {\n case MARKUP_B :\t/* Top-level TOC */\n if (t->prev != NULL)\t/* Advance one line prior to top-levels... */\n *y -= _htmlSpacings[SIZE_P];", " if (*y < (bottom + _htmlSpacings[SIZE_P] * 3))\n\t *y = 0; // Force page break", " chap = t;", " case MARKUP_LI :\t/* Lower-level TOC */\n DEBUG_printf((\"parse_contents: heading=%d, page = %d\\n\", *heading,\n heading_pages[*heading]));", " /*\n * Put the text unless the author has flagged it otherwise...\n */", " if (htmlGetVariable(t, (uchar *)\"_HD_OMIT_TOC\") == NULL)\n\t {\n render_contents(t, left, right, bottom, top, y, page,\n\t *heading, chap);", " /*\n\t * Update current headings for header/footer strings in TOC.\n\t */", "\t check_pages(*page);", "\t if (t->markup == MARKUP_B &&\n\t\tpages[*page].chapter == pages[*page - 1].chapter)\n\t pages[*page].chapter = htmlGetText(t->child->child);", "\t if (pages[*page].heading == pages[*page - 1].heading)\n\t pages[*page].heading = htmlGetText(t->child->child);", " /*\n * Next heading...\n */", " (*heading) ++;", " if (t->last_child->markup == MARKUP_UL)\n parse_contents(t->last_child, left, right, bottom, top, y,\n\t page, heading, chap);\n }\n\t else if (t->next != NULL && t->next->markup == MARKUP_UL)\n\t {\n\t /*\n\t * Skip children of omitted heading...\n\t */", "\t t = t->next;", "\t (*heading) += count_headings(t->child) + 1;\n\t }\n\t else\n\t (*heading) ++;\n break;", " default :\n parse_contents(t->child, left, right, bottom, top, y, page, heading,\n\t chap);\n break;\n }", " t = t->next;\n }\n}", "\n/*\n * 'parse_doc()' - Parse a document tree and produce rendering list output.\n */", "static void\nparse_doc(tree_t *t,\t\t/* I - Tree to parse */\n float *left,\t\t/* I - Left margin */\n float *right,\t/* I - Printable width */\n float *bottom,\t/* I - Bottom margin */\n float *top,\t\t/* I - Printable top */\n float *x,\t\t/* IO - X position */\n float *y,\t\t/* IO - Y position */\n int *page,\t\t/* IO - Page # */\n\t tree_t *cpara,\t/* I - Current paragraph */\n\t int *needspace)\t/* I - Need whitespace before this element */\n{\n int\t\ti;\t\t/* Looping var */\n tree_t\t*para,\t\t/* Phoney paragraph tree entry */\n\t\t*temp;\t\t/* Paragraph entry */\n var_t\t\t*var;\t\t/* Variable entry */\n uchar\t\t*name;\t\t/* ID name */\n uchar\t\t*style;\t\t/* STYLE attribute */\n float\t\twidth,\t\t/* Width of horizontal rule */\n\t\theight,\t\t/* Height of rule */\n\t\trgb[3];\t\t/* RGB color of rule */", "\n DEBUG_printf((\"parse_doc(t=%p, left=%.1f, right=%.1f, bottom=%.1f, top=%.1f, x=%.1f, y=%.1f, page=%d, cpara=%p, needspace=%d\\n\",\n (void *)t, *left, *right, *bottom, *top, *x, *y, *page, (void *)cpara,\n\t *needspace));\n DEBUG_printf((\" title_page = %d, chapter = %d\\n\", title_page, chapter));", " if (cpara == NULL)\n para = htmlNewTree(NULL, MARKUP_P, NULL);\n else\n para = cpara;", " while (t != NULL)\n {\n if (t->markup == MARKUP_FILE)\n current_url = htmlGetVariable(t, (uchar *)\"_HD_URL\");", " if (((t->markup == MARKUP_H1 && OutputType == OUTPUT_BOOK) ||\n (t->markup == MARKUP_FILE && OutputType == OUTPUT_WEBPAGES)) &&\n\t!title_page)\n {\n // New page on H1 in book mode or file in webpage mode...\n if (para->child != NULL && chapter > 0)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;\n }", " if ((chapter > 0 && OutputType == OUTPUT_BOOK) ||\n ((*page > 0 || *y < *top) && OutputType == OUTPUT_WEBPAGES))\n {\n if (*y < *top)\n (*page) ++;", " if (PageDuplex && (*page & 1))\n (*page) ++;", " if (Verbosity)\n progress_show(\"Formatting page %d\", *page);", " chapter_ends[chapter] = *page - 1;\n }", " // Make sure header and footer strings are correct...\n check_pages(*page);", " memcpy(pages[*page].header, Header, sizeof(pages[*page].header));\n memcpy(pages[*page].header1, Header1, sizeof(pages[*page].header1));\n memcpy(pages[*page].footer, Footer, sizeof(pages[*page].footer));", " // Bump the chapter/file count...\n chapter ++;\n if (chapter >= MAX_CHAPTERS)\n {\n\tprogress_error(HD_ERROR_TOO_MANY_CHAPTERS,\n\t \"Too many chapters/files in document (%d > %d)!\",\n\t chapter, MAX_CHAPTERS);\n chapter = MAX_CHAPTERS - 1;\n }\n else\n chapter_starts[chapter] = *page;", " if (chapter > TocDocCount)\n\tTocDocCount = chapter;", " *y = *top;\n *x = *left;\n *needspace = 0;\n }", " if ((name = htmlGetVariable(t, (uchar *)\"ID\")) != NULL)\n {\n /*\n * Add a link target using the ID=name variable...\n */", " add_link(name, *page, (int)*y);\n }\n else if (t->markup == MARKUP_FILE)\n {\n /*\n * Add a file link...\n */", " uchar\tnewname[256],\t/* New filename */\n\t\t*sep;\t\t/* \"?\" separator in links */", "\n // Strip any trailing HTTP GET data stuff...\n strlcpy((char *)newname, (char *)htmlGetVariable(t, (uchar *)\"_HD_FILENAME\"),\n sizeof(newname));", " if ((sep = (uchar *)strchr((char *)newname, '?')) != NULL)\n *sep = '\\0';", " // Add the link\n add_link(newname, *page, (int)*y);\n }", " if (chapter == 0 && !title_page)\n {\n // Need to handle page comments before the first heading...\n if (t->markup == MARKUP_COMMENT)\n parse_comment(t, left, right, bottom, top, x, y, page, para,\n\t *needspace);", " if (t->child != NULL)\n parse_doc(t->child, left, right, bottom, top, x, y, page, para,\n\t needspace);", " t = t->next;\n continue;\n }", " // Check for some basic stylesheet stuff...\n if ((style = htmlGetStyle(t, (uchar *)\"page-break-before:\")) != NULL &&\n\tstrcasecmp((char *)style, \"avoid\") != 0)\n {\n // Advance to the next page...\n (*page) ++;\n *x = *left;\n *y = *top;\n *needspace = 0;", " // See if we need to go to the next left/righthand page...\n if (PageDuplex && ((*page) & 1) &&\n strcasecmp((char *)style, \"right\") == 0)\n\t(*page) ++;\n else if (PageDuplex && !((*page) & 1) &&\n strcasecmp((char *)style, \"left\") == 0)\n\t(*page) ++;", " // Update the progress as necessary...\n if (Verbosity)\n\tprogress_show(\"Formatting page %d\", *page);\n }", " // Process the markup...\n switch (t->markup)\n {\n case MARKUP_IMG :\n update_image_size(t);\n case MARKUP_NONE :\n case MARKUP_BR :\n if (para->child == NULL)\n {\n\t if (t->parent == NULL)\n\t {\n para->halignment = ALIGN_LEFT;\n para->indent = 0;\n\t }\n\t else\n\t {\n para->halignment = t->parent->halignment;\n para->indent = t->parent->indent;\n\t }\n }", "\t // Skip heading whitespace...\n if (para->child == NULL && t->markup == MARKUP_NONE &&\n\t t->data != NULL && strcmp((char *)t->data, \" \") == 0)\n\t break;", " if ((temp = htmlAddTree(para, t->markup, t->data)) != NULL)\n {\n\t temp->link = t->link;\n temp->width = t->width;\n temp->height = t->height;\n temp->typeface = t->typeface;\n temp->style = t->style;\n temp->size = t->size;\n temp->underline = t->underline;\n temp->strikethrough = t->strikethrough;\n temp->superscript = t->superscript;\n temp->subscript = t->subscript;\n temp->halignment = t->halignment;\n temp->valignment = t->valignment;\n temp->red = t->red;\n temp->green = t->green;\n temp->blue = t->blue;\n for (i = 0, var = t->vars; i < t->nvars; i ++, var ++)\n htmlSetVariable(temp, var->name, var->value);\n }\n break;", " case MARKUP_TABLE :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;\n }", " parse_table(t, *left, *right, *bottom, *top, x, y, page, *needspace);\n\t *needspace = 0;\n break;", " case MARKUP_H1 :\n case MARKUP_H2 :\n case MARKUP_H3 :\n case MARKUP_H4 :\n case MARKUP_H5 :\n case MARKUP_H6 :\n case MARKUP_H7 :\n case MARKUP_H8 :\n case MARKUP_H9 :\n case MARKUP_H10 :\n case MARKUP_H11 :\n case MARKUP_H12 :\n case MARKUP_H13 :\n case MARKUP_H14 :\n case MARKUP_H15 :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;", "\t *needspace = 1;\n }", " parse_heading(t, *left, *right, *bottom, *top, x, y, page, *needspace);\n\t *needspace = 1;\n break;", " case MARKUP_BLOCKQUOTE :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;", "\t *needspace = 1;\n }", " *left += 36;\n\t *right -= 36;", " parse_doc(t->child, left, right, bottom, top, x, y, page, NULL,\n\t needspace);", " *left -= 36;\n\t *right += 36;", " *x = *left;\n *needspace = 1;\n break;", " case MARKUP_CENTER :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;", " *needspace = 1;\n }", " parse_doc(t->child, left, right, bottom, top, x, y, page, NULL,\n\t needspace);", " *x = *left;\n *needspace = 1;\n break;", " case MARKUP_P :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;", "\t *needspace = 1;\n }", " parse_doc(t->child, left, right, bottom, top, x, y, page, NULL,\n\t needspace);", " *x = *left;\n *needspace = 1;\n break;", " case MARKUP_DIV :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;\n }", " parse_doc(t->child, left, right, bottom, top, x, y, page, NULL,\n\t needspace);", " if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;\n }\n break;", " case MARKUP_PRE :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;", "\t *needspace = 1;\n }", " *left += 36.0f;\n *x = *left;", " parse_pre(t, *left, *right, *bottom, *top, x, y, page, *needspace);", " *left -= 36.0f;\n *x = *left;\n *needspace = 1;\n break;", " case MARKUP_DIR :\n case MARKUP_MENU :\n case MARKUP_UL :\n case MARKUP_OL :\n init_list(t);\n case MARKUP_DL :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;\n }", " if (t->indent == 1)\n\t *needspace = 1;", "\t *left += 36.0f;\n *x = *left;", " parse_doc(t->child, left, right, bottom, top, x, y, page, para,\n\t needspace);", " *left -= 36.0f;", " if (t->indent == 1)\n\t *needspace = 1;\n break;", " case MARKUP_LI :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;", "\t *needspace = 0;\n }", " parse_list(t, left, right, bottom, top, x, y, page, *needspace);", " *x = *left;\n *needspace = t->next && t->next->markup != MARKUP_LI &&\n\t t->next->markup != MARKUP_UL &&\n\t\t t->next->markup != MARKUP_OL;\n break;", " case MARKUP_DT :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;", "\t *needspace = 0;\n }", "\t *left -= 36.0f;\n *x = *left;", " parse_doc(t->child, left, right, bottom, top, x, y, page,\n\t NULL, needspace);", "\t *left += 36.0f;\n *x = *left;\n *needspace = 0;\n break;", " case MARKUP_DD :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;", "\t *needspace = 0;\n }", " parse_doc(t->child, left, right, bottom, top, x, y, page, NULL,\n\t needspace);", " *x = *left;\n *needspace = 0;\n break;", " case MARKUP_HR :\n if (para->child != NULL)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;\n }", " if (htmlGetVariable(t, (uchar *)\"BREAK\") == NULL)\n\t {\n\t /*\n\t * Generate a horizontal rule...\n\t */", " if ((name = htmlGetVariable(t, (uchar *)\"WIDTH\")) == NULL)\n\t width = *right - *left;\n\t else\n\t {\n\t if (strchr((char *)name, '%') != NULL)\n\t width = atoi((char *)name) * (*right - *left) / 100;\n\t else\n width = (float)(atoi((char *)name) * PagePrintWidth / _htmlBrowserWidth);\n }", " if ((name = htmlGetVariable(t, (uchar *)\"SIZE\")) == NULL)\n\t height = 2;\n\t else\n\t height = (float)(atoi((char *)name) * PagePrintWidth / _htmlBrowserWidth);", " switch (t->halignment)\n\t {\n\t case ALIGN_LEFT :\n\t *x = *left;\n\t\t break;\n\t case ALIGN_CENTER :\n\t *x = *left + (*right - *left - width) * 0.5f;\n\t\t break;\n\t case ALIGN_RIGHT :\n\t *x = *right - width;\n\t\t break;\n\t }", " if (*y < (*bottom + height + _htmlSpacings[SIZE_P]))\n\t {\n\t /*\n\t * Won't fit on this page...\n\t */", " (*page) ++;\n\t if (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n *y = *top;\n }", " (*y) -= height + _htmlSpacings[SIZE_P];\n rgb[0] = t->red / 255.0f;\n rgb[1] = t->green / 255.0f;\n rgb[2] = t->blue / 255.0f;", " new_render(*page, RENDER_BOX, *x, *y + _htmlSpacings[SIZE_P] * 0.5,\n\t width, height, rgb);\n\t }\n\t else\n\t {\n\t /*\n\t * <HR BREAK> generates a page break...\n\t */", " (*page) ++;\n\t if (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n *y = *top;\n\t }", " *x = *left;\n *needspace = 0;\n break;", " case MARKUP_COMMENT :\n // Check comments for commands...\n parse_comment(t, left, right, bottom, top, x, y, page, para,\n\t *needspace);\n break;", " case MARKUP_HEAD : // Ignore document HEAD section\n case MARKUP_TITLE : // Ignore title and meta stuff\n case MARKUP_META :\n case MARKUP_SCRIPT : // Ignore script stuff\n case MARKUP_INPUT : // Ignore form stuff\n case MARKUP_SELECT :\n case MARKUP_OPTION :\n case MARKUP_TEXTAREA :\n break;", " case MARKUP_STYLE :\n break;", " case MARKUP_A :\n if (htmlGetVariable(t, (uchar *)\"NAME\") != NULL)\n\t {\n\t /*\n\t * Add this named destination to the paragraph tree...\n\t */", " if (para->child == NULL)\n {\n para->halignment = t->halignment;\n para->indent = t->indent;\n }", " if ((temp = htmlAddTree(para, t->markup, t->data)) != NULL)\n {\n\t temp->link = t->link;\n temp->width = t->width;\n temp->height = t->height;\n temp->typeface = t->typeface;\n temp->style = t->style;\n temp->size = t->size;\n temp->underline = t->underline;\n temp->strikethrough = t->strikethrough;\n temp->superscript = t->superscript;\n temp->subscript = t->subscript;\n temp->halignment = t->halignment;\n temp->valignment = t->valignment;\n temp->red = t->red;\n temp->green = t->green;\n temp->blue = t->blue;\n for (i = 0, var = t->vars; i < t->nvars; i ++, var ++)\n \thtmlSetVariable(temp, var->name, var->value);\n }\n\t }", " default :\n\t if (t->child != NULL)\n parse_doc(t->child, left, right, bottom, top, x, y, page, para,\n\t needspace);\n break;\n }", "\n // Check for some basic stylesheet stuff...\n if ((style = htmlGetStyle(t, (uchar *)\"page-break-after:\")) != NULL &&\n\tstrcasecmp((char *)style, \"avoid\") != 0)\n {\n // Advance to the next page...\n (*page) ++;\n *x = *left;\n *y = *top;\n *needspace = 0;", " // See if we need to go to the next left/righthand page...\n if (PageDuplex && ((*page) & 1) &&\n strcasecmp((char *)style, \"right\") == 0)\n\t(*page) ++;\n else if (PageDuplex && !((*page) & 1) &&\n strcasecmp((char *)style, \"left\") == 0)\n\t(*page) ++;", " // Update the progress as necessary...\n if (Verbosity)\n\tprogress_show(\"Formatting page %d\", *page);\n }", " // Move to the next node...\n t = t->next;\n }", " if (para->child != NULL && cpara != para)\n {\n parse_paragraph(para, *left, *right, *bottom, *top, x, y, page, *needspace);\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;\n *needspace = 0;\n }", " if (cpara != para)\n htmlDeleteTree(para);", " DEBUG_printf((\"LEAVING parse_doc(), x = %.1f, y = %.1f, page = %d\\n\",\n *x, *y, *page));\n}", "\n/*\n * 'parse_heading()' - Parse a heading tree and produce rendering list output.\n */", "static void\nparse_heading(tree_t *t,\t/* I - Tree to parse */\n float left,\t/* I - Left margin */\n float right,\t/* I - Printable width */\n float bottom,\t/* I - Bottom margin */\n float top,\t/* I - Printable top */\n float *x,\t/* IO - X position */\n float *y,\t/* IO - Y position */\n int *page,\t/* IO - Page # */\n int needspace)\t/* I - Need whitespace? */\n{\n int\t*temp;\t\t\t// Temporary integer array pointer", "\n DEBUG_printf((\"parse_heading(t=%p, left=%.1f, right=%.1f, bottom=%.1f, top=%.1f, x=%.1f, y=%.1f, page=%d, needspace=%d\\n\",\n (void *)t, left, right, bottom, top, *x, *y, *page, needspace));", " if (((t->markup - MARKUP_H1) < TocLevels || TocLevels == 0) && !title_page)\n current_heading = t->child;", " if (*y < (5 * _htmlSpacings[SIZE_P] + bottom))\n {\n (*page) ++;\n *y = top;\n if (Verbosity)\n progress_show(\"Formatting page %d\", *page);\n }", " check_pages(*page);", " if (t->markup == MARKUP_H1 && !title_page)\n pages[*page].chapter = htmlGetText(current_heading);", " if ((pages[*page].heading == NULL || t->markup == MARKUP_H1 ||\n (*page > 0 && pages[*page].heading == pages[*page - 1].heading)) &&\n !title_page)\n {\n pages[*page].heading = htmlGetText(current_heading);\n pages[*page].headnode = current_heading;\n }", " if ((t->markup - MARKUP_H1) < TocLevels && !title_page)\n {\n DEBUG_printf((\"H%d: heading_pages[%d] = %d\\n\", t->markup - MARKUP_H1 + 1,\n (int)num_headings, *page - 1));", " // See if we need to resize the headings arrays...\n if (num_headings >= alloc_headings)\n {\n alloc_headings += ALLOC_HEADINGS;", " if (num_headings == 0)\n temp = (int *)malloc(sizeof(int) * alloc_headings);\n else\n temp = (int *)realloc(heading_pages, sizeof(int) * alloc_headings);", " if (temp == NULL)\n {\n progress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory for %d headings - %s\",\n\t (int)alloc_headings, strerror(errno));\n\talloc_headings -= ALLOC_HEADINGS;\n\treturn;\n }", " memset(temp + alloc_headings - ALLOC_HEADINGS, 0,\n sizeof(int) * ALLOC_HEADINGS);", " heading_pages = temp;", " if (num_headings == 0)\n temp = (int *)malloc(sizeof(int) * alloc_headings);\n else\n temp = (int *)realloc(heading_tops, sizeof(int) * alloc_headings);", " if (temp == NULL)\n {\n progress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory for %d headings - %s\",\n\t (int)alloc_headings, strerror(errno));\n\talloc_headings -= ALLOC_HEADINGS;\n\treturn;\n }", " memset(temp + alloc_headings - ALLOC_HEADINGS, 0,\n sizeof(int) * ALLOC_HEADINGS);", " heading_tops = temp;\n }", " heading_pages[num_headings] = *page;\n heading_tops[num_headings] = (int)(*y + 4 * _htmlSpacings[SIZE_P]);\n num_headings ++;\n }", " parse_paragraph(t, left, right, bottom, top, x, y, page, needspace);", " if (t->halignment == ALIGN_RIGHT && t->markup == MARKUP_H1 &&\n OutputType == OUTPUT_BOOK && !title_page)\n {\n /*\n * Special case - chapter heading for users manual...\n */", " *y = bottom + 0.5f * (top - bottom);\n }\n}", "#if defined(PARA_DEBUG) && !defined(DEBUG)\n# undef DEBUG_printf\n# undef DEBUG_puts\n# define DEBUG_printf(x) printf x\n# define DEBUG_puts(x) puts(x)\n#endif /* PARA_DEBUG && !defined(DEBUG) */", "\n/*\n * 'parse_paragraph()' - Parse a paragraph tree and produce rendering list\n * output.\n */", "static void\nparse_paragraph(tree_t *t,\t/* I - Tree to parse */\n \tfloat left,\t/* I - Left margin */\n \tfloat right,\t/* I - Printable width */\n \tfloat bottom,\t/* I - Bottom margin */\n \tfloat top,\t/* I - Printable top */\n \tfloat *x,\t/* IO - X position */\n \tfloat *y,\t/* IO - Y position */\n \tint *page,\t/* IO - Page # */\n \tint needspace)/* I - Need whitespace? */\n{\n int\t\twhitespace;\t/* Non-zero if a fragment ends in whitespace */\n tree_t\t*flat,\n\t\t*start,\n\t\t*end,\n\t\t*prev,\n\t\t*temp;\n float\t\twidth,\n\t\theight,\n\t\toffset,\n\t\tspacing,\n\t\tborderspace,\n\t\ttemp_y,\n\t\ttemp_width,\n\t\ttemp_height;\n float\t\tformat_width, image_y, image_left, image_right;\n int\t\timage_page = *page;\n float\t\tchar_spacing;\n int\t\tnum_chars;\n render_t\t*r;\n uchar\t\t*align,\n\t\t*hspace,\n\t\t*vspace,\n\t\t*link,\n\t\t*border;\n float\t\trgb[3];\n uchar\t\tline[10240],\n\t\t*lineptr,\n\t\t*dataptr;\n tree_t\t*linetype;\n float\t\tlinex,\n\t\tlinewidth;\n int\t\tfirstline;", "\n DEBUG_printf((\"parse_paragraph(t=%p, left=%.1f, right=%.1f, bottom=%.1f, top=%.1f, x=%.1f, y=%.1f, page=%d, needspace=%d\\n\",\n (void *)t, left, right, bottom, top, *x, *y, *page, needspace));", " flat = flatten_tree(t->child);\n image_left = left;\n image_right = right;\n image_y = 0;", " if (flat == NULL)\n DEBUG_puts(\"parse_paragraph: flat == NULL!\");", " // Add leading whitespace...\n if (*y < top && needspace)\n *y -= _htmlSpacings[SIZE_P];", " /*\n * First scan for images with left/right alignment tags...\n */", " for (temp = flat, prev = NULL; temp != NULL;)\n {\n if (temp->markup == MARKUP_IMG)\n update_image_size(temp);", " if (temp->markup == MARKUP_IMG &&\n (align = htmlGetVariable(temp, (uchar *)\"ALIGN\")))\n {\n if ((border = htmlGetVariable(temp, (uchar *)\"BORDER\")) != NULL)\n\tborderspace = (float)atof((char *)border);\n else if (temp->link)\n\tborderspace = 1;\n else\n\tborderspace = 0;", " borderspace *= PagePrintWidth / _htmlBrowserWidth;", " if (strcasecmp((char *)align, \"LEFT\") == 0)\n {\n if ((vspace = htmlGetVariable(temp, (uchar *)\"VSPACE\")) != NULL)\n\t *y -= atoi((char *)vspace);", " if (*y < (bottom + temp->height + 2 * borderspace))\n {\n\t (*page) ++;\n\t *y = top;", "\t if (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n }", " if (borderspace > 0.0f)\n\t{\n\t if (temp->link && PSLevel == 0)\n\t memcpy(rgb, link_color, sizeof(rgb));\n\t else\n\t {\n\t rgb[0] = temp->red / 255.0f;\n\t rgb[1] = temp->green / 255.0f;\n\t rgb[2] = temp->blue / 255.0f;\n\t }", "\t // Top\n new_render(*page, RENDER_BOX, image_left, *y - borderspace,\n\t\t temp->width + 2 * borderspace, borderspace, rgb);\n\t // Left\n new_render(*page, RENDER_BOX, image_left,\n\t *y - temp->height - 2 * borderspace,\n borderspace, temp->height + 2 * borderspace, rgb);\n\t // Right\n new_render(*page, RENDER_BOX, image_left + temp->width + borderspace,\n\t *y - temp->height - 2 * borderspace,\n borderspace, temp->height + 2 * borderspace, rgb);\n\t // Bottom\n new_render(*page, RENDER_BOX, image_left,\n\t *y - temp->height - 2 * borderspace,\n temp->width + 2 * borderspace, borderspace, rgb);\n\t}", " *y -= borderspace;", " new_render(*page, RENDER_IMAGE, image_left + borderspace,\n\t *y - temp->height, temp->width, temp->height,\n\t\t image_find((char *)htmlGetVariable(temp, (uchar *)\"REALSRC\")));", " if (temp->link &&\n\t (link = htmlGetVariable(temp->link, (uchar *)\"_HD_FULL_HREF\")) != NULL)\n {\n\t /*\n\t * Add a page link...\n\t */", "\t new_render(*page, RENDER_LINK, image_left + borderspace, *y - temp->height, temp->width, temp->height, link);\n }", " *y -= borderspace;", " if (vspace != NULL)\n\t *y -= atoi((char *)vspace);", " image_left += temp->width + 2 * borderspace;\n\ttemp_y = *y - temp->height;\n\timage_page = *page;", "\tif (temp_y < image_y || image_y == 0)\n\t image_y = temp_y;", " if ((hspace = htmlGetVariable(temp, (uchar *)\"HSPACE\")) != NULL)\n\t image_left += atoi((char *)hspace);", " if (prev != NULL)\n prev->next = temp->next;\n else\n flat = temp->next;", " free(temp);\n temp = prev;\n }\n else if (strcasecmp((char *)align, \"RIGHT\") == 0)\n {\n if ((vspace = htmlGetVariable(temp, (uchar *)\"VSPACE\")) != NULL)\n\t *y -= atoi((char *)vspace);", " if (*y < (bottom + temp->height + 2 * borderspace))\n {\n\t (*page) ++;\n\t *y = top;", "\t if (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n }", " image_right -= temp->width + 2 * borderspace;\n\timage_page = *page;", " if (borderspace > 0.0f)\n\t{\n\t if (temp->link && PSLevel == 0)\n\t memcpy(rgb, link_color, sizeof(rgb));\n\t else\n\t {\n\t rgb[0] = temp->red / 255.0f;\n\t rgb[1] = temp->green / 255.0f;\n\t rgb[2] = temp->blue / 255.0f;\n\t }", "\t // Top\n new_render(*page, RENDER_BOX, image_right, *y - borderspace,\n\t\t temp->width + 2 * borderspace, borderspace, rgb);\n\t // Left\n new_render(*page, RENDER_BOX, image_right,\n\t *y - temp->height - 2 * borderspace,\n borderspace, temp->height + 2 * borderspace, rgb);\n\t // Right\n new_render(*page, RENDER_BOX, image_right + temp->width + borderspace,\n\t *y - temp->height - 2 * borderspace,\n borderspace, temp->height + 2 * borderspace, rgb);\n\t // Bottom\n new_render(*page, RENDER_BOX, image_right, *y - temp->height - 2 * borderspace,\n temp->width + 2 * borderspace, borderspace, rgb);\n\t}", " *y -= borderspace;", " new_render(*page, RENDER_IMAGE, image_right + borderspace,\n\t *y - temp->height, temp->width, temp->height,\n\t\t image_find((char *)htmlGetVariable(temp, (uchar *)\"REALSRC\")));", " if (temp->link &&\n\t (link = htmlGetVariable(temp->link, (uchar *)\"_HD_FULL_HREF\")) != NULL)\n {\n\t /*\n\t * Add a page link...\n\t */", "\t new_render(*page, RENDER_LINK, image_right + borderspace, *y - temp->height, temp->width, temp->height, link);\n }", " *y -= borderspace;", " if (vspace != NULL)\n\t *y -= atoi((char *)vspace);", "\ttemp_y = *y - temp->height;", "\tif (temp_y < image_y || image_y == 0)\n\t image_y = temp_y;", " if ((hspace = htmlGetVariable(temp, (uchar *)\"HSPACE\")) != NULL)\n\t image_right -= atoi((char *)hspace);", " if (prev != NULL)\n prev->next = temp->next;\n else\n flat = temp->next;", " free(temp);\n temp = prev;\n }\n }", " if (temp != NULL)\n {\n prev = temp;\n temp = temp->next;\n }\n else\n temp = flat;\n }", " /*\n * Then format the text and inline images...\n */", " format_width = image_right - image_left;\n firstline = 1;", " DEBUG_printf((\"format_width = %.1f\\n\", format_width));", " // Make stupid compiler warnings go away (if you can't put\n // enough smarts in the compiler, don't add the warning!)\n offset = 0.0f;\n temp_width = 0.0f;\n temp_height = 0.0f;\n lineptr = NULL;\n linex = 0.0f;\n linewidth = 0.0f;", " while (flat != NULL)\n {\n start = flat;\n end = flat;\n width = 0.0;", " while (flat != NULL)\n {\n // Get fragments...\n temp_width = 0.0;\n temp = flat;\n whitespace = 0;", " while (temp != NULL && !whitespace)\n {\n if (temp->markup == MARKUP_NONE && temp->data[0] == ' ')\n\t{\n if (temp == start)\n temp_width -= _htmlWidths[temp->typeface][temp->style][' '] *\n _htmlSizes[temp->size] * 0.001f;\n else if (temp_width > 0.0f)\n\t whitespace = 1;\n\t}\n else\n whitespace = 0;", " if (whitespace)\n\t break;", " if (temp->markup == MARKUP_IMG)\n\t{\n\t if ((border = htmlGetVariable(temp, (uchar *)\"BORDER\")) != NULL)\n\t borderspace = (float)atof((char *)border);\n\t else if (temp->link)\n\t borderspace = 1;\n\t else\n\t borderspace = 0;", " borderspace *= PagePrintWidth / _htmlBrowserWidth;", " temp_width += 2 * borderspace;\n\t}", " prev = temp;\n temp = temp->next;\n temp_width += prev->width;", " if ((temp_width >= format_width && prev->markup == MARKUP_IMG) ||\n\t prev->markup == MARKUP_BR)\n\t{\n\t break;\n\t}\n\telse if (prev->markup == MARKUP_NONE)\n\t{\n\t int\tch = prev->data[strlen((char *)prev->data) - 1];", "\t if (_htmlUTF8)\n\t ch = _htmlUnicode[ch];", " if (ch == 173)\n break;\n\t}\n }", " if ((width + temp_width) <= format_width)\n {\n width += temp_width;\n end = temp;\n flat = temp;", " if (prev->markup == MARKUP_BR)\n break;\n }\n else if (width == 0.0)\n {\n width += temp_width;\n end = temp;\n flat = temp;\n break;\n }\n else\n break;\n }", " if (start == end)\n {\n end = start->next;\n flat = start->next;\n width = start->width;\n }", " for (height = 0.0, num_chars = 0, temp = prev = start;\n temp != end;\n\t temp = temp->next)\n {\n prev = temp;", " if (temp->markup == MARKUP_NONE)\n num_chars += strlen((char *)temp->data);", " if (temp->height > height)\n height = temp->height;\n }", " for (spacing = 0.0, temp = prev = start;\n temp != end;\n\t temp = temp->next)\n {\n prev = temp;", " if (temp->markup != MARKUP_IMG)\n temp_height = (float)(temp->height * _htmlSpacings[0] / _htmlSizes[0]);\n else\n {\n\tif ((border = htmlGetVariable(temp, (uchar *)\"BORDER\")) != NULL)\n\t borderspace = (float)atof((char *)border);\n\telse if (temp->link)\n\t borderspace = 1;\n\telse\n\t borderspace = 0;", " borderspace *= PagePrintWidth / _htmlBrowserWidth;", " temp_height = temp->height + 2 * borderspace;\n }", " if (temp_height > spacing)\n spacing = temp_height;\n }", " if (firstline && end != NULL && *y < (bottom + height + _htmlSpacings[t->size]))\n {\n // Go to next page since only 1 line will fit on this one...\n (*page) ++;\n *y = top;", " if (Verbosity)\n progress_show(\"Formatting page %d\", *page);\n }", " firstline = 0;", " if (height == 0.0f)\n height = spacing;", " for (temp = start; temp != end; temp = temp->next)\n if (temp->markup != MARKUP_A)\n break;", " if (temp != NULL && temp->markup == MARKUP_NONE && temp->data[0] == ' ')\n {\n // Drop leading space...\n for (dataptr = temp->data; *dataptr; dataptr ++)\n *dataptr = dataptr[1];\n *dataptr = '\\0';", " temp_width = _htmlWidths[temp->typeface][temp->style][' '] * _htmlSizes[temp->size] * 0.001f;\n temp->width -= temp_width;\n num_chars --;\n }", " if (end != NULL)\n temp = end->prev;\n else\n temp = NULL;", " DEBUG_printf((\" BEFORE page=%d, y=%.1f, height=%.1f, spacing=%.1f, bottom=%.1f\\n\", *page, *y, height, spacing, bottom));", " if (*y < (spacing + bottom))\n {\n (*page) ++;\n *y = top;", " if (Verbosity)\n progress_show(\"Formatting page %d\", *page);\n }", " *y -= height;", " DEBUG_printf((\" page=%d, y=%.1f, width=%.1f, height=%.1f\\n\", *page, *y, width, height));", " if (Verbosity)\n progress_update(100 - (int)(100 * (*y) / PagePrintLength));", " char_spacing = 0.0f;\n whitespace = 0;\n temp = start;\n linetype = NULL;", " rgb[0] = temp->red / 255.0f;\n rgb[1] = temp->green / 255.0f;\n rgb[2] = temp->blue / 255.0f;", " switch (t->halignment)\n {\n case ALIGN_LEFT :\n linex = image_left;\n\t break;", " case ALIGN_CENTER :\n linex = image_left + 0.5f * (format_width - width);\n\t break;", " case ALIGN_RIGHT :\n linex = image_right - width;\n\t break;", " case ALIGN_JUSTIFY :\n linex = image_left;\n\t if (flat != NULL && flat->prev->markup != MARKUP_BR && num_chars > 1)\n\t char_spacing = (format_width - width) / (num_chars - 1);\n\t break;\n }", " while (temp != end)\n {\n if (temp->link != NULL && PSLevel == 0 && Links &&\n temp->markup == MARKUP_NONE)\n {\n\ttemp->red = (uchar)(link_color[0] * 255.0);\n\ttemp->green = (uchar)(link_color[1] * 255.0);\n\ttemp->blue = (uchar)(link_color[2] * 255.0);\n }", " /*\n * See if we are doing a run of characters in a line and need to\n * output this run...\n */", " if (linetype != NULL &&\n\t (temp->markup != MARKUP_NONE ||\n\t temp->typeface != linetype->typeface ||\n\t temp->style != linetype->style ||\n\t temp->size != linetype->size ||\n\t temp->superscript != linetype->superscript ||\n\t temp->subscript != linetype->subscript ||\n\t temp->red != linetype->red ||\n\t temp->green != linetype->green ||\n\t temp->blue != linetype->blue))\n {\n r = new_render(*page, RENDER_TEXT, linex - linewidth, *y,\n\t linewidth, linetype->height, line);\n\tr->data.text.typeface = linetype->typeface;\n\tr->data.text.style = linetype->style;\n\tr->data.text.size = (float)_htmlSizes[linetype->size];\n\tr->data.text.spacing = char_spacing;\n memcpy(r->data.text.rgb, rgb, sizeof(rgb));", "\tif (linetype->superscript)\n r->y += height - linetype->height;\n else if (linetype->subscript)\n r->y -= height - linetype->height;", " free(linetype);\n linetype = NULL;\n }", " if ((link = htmlGetVariable(temp, (uchar *)\"ID\")) != NULL)\n {\n /*\n\t* Add a target link...\n\t*/", "\tadd_link(link, *page, (int)(*y + height));\n }", " switch (temp->markup)\n {\n case MARKUP_A :\n if ((link = htmlGetVariable(temp, (uchar *)\"NAME\")) != NULL)\n {\n /*\n * Add a target link...\n */", " add_link(link, *page, (int)(*y + height));\n }", "\tdefault :\n\t temp_width = temp->width;\n break;", " case MARKUP_NONE :\n if (temp->data == NULL)\n break;", "\t if (((temp->width - right + left) > 0.001 ||\n\t (temp->height - top + bottom) > 0.001) && OverflowErrors)\n\t progress_error(HD_ERROR_CONTENT_TOO_LARGE,\n\t \"Text on page %d too large - \"\n\t\t\t \"truncation or overlapping may occur!\", *page + 1);", " if (linetype == NULL)\n {\n\t linetype = temp;\n\t lineptr = line;\n\t linewidth = 0.0;", "\t rgb[0] = temp->red / 255.0f;\n\t rgb[1] = temp->green / 255.0f;\n\t rgb[2] = temp->blue / 255.0f;\n\t }", " strlcpy((char *)lineptr, (char *)temp->data, sizeof(line) - (size_t)(lineptr - line));", " temp_width = temp->width + char_spacing * strlen((char *)lineptr);", "\t if (temp->underline || (temp->link && LinkStyle && PSLevel == 0))\n\t new_render(*page, RENDER_BOX, linex, *y - 1, temp_width, 0, rgb);", "\t if (temp->strikethrough)\n\t new_render(*page, RENDER_BOX, linex, *y + temp->height * 0.25f,\n\t temp_width, 0, rgb);", " linewidth += temp_width;\n lineptr += strlen((char *)lineptr);", " if (lineptr > line && lineptr[-1] == ' ')\n whitespace = 1;\n else\n whitespace = 0;\n\t break;", "\tcase MARKUP_IMG :\n\t if (((temp->width - right + left) > 0.001 ||\n\t (temp->height - top + bottom) > 0.001) && OverflowErrors)\n\t {\n\t DEBUG_printf((\"IMAGE: %.3fx%.3f > %.3fx%.3f\\n\",\n\t temp->width, temp->height,\n\t\t\t right - left, top - bottom));", "\t progress_error(HD_ERROR_CONTENT_TOO_LARGE,\n\t \"Image on page %d too large - \"\n\t\t\t \"truncation or overlapping may occur!\", *page + 1);\n }", "\t if ((border = htmlGetVariable(temp, (uchar *)\"BORDER\")) != NULL)\n\t borderspace = (float)atof((char *)border);\n\t else if (temp->link)\n\t borderspace = 1;\n\t else\n\t borderspace = 0;", " borderspace *= PagePrintWidth / _htmlBrowserWidth;", " temp_width += 2 * borderspace;", "\t switch (temp->valignment)\n\t {\n\t case ALIGN_TOP :\n\t\t offset = height - temp->height - 2 * borderspace;\n\t\t break;\n\t case ALIGN_MIDDLE :\n\t\t offset = 0.5f * (height - temp->height) - borderspace;\n\t\t break;\n\t case ALIGN_BOTTOM :\n\t\t offset = 0.0f;\n\t }", " if (borderspace > 0.0f)\n\t {\n\t // Top\n new_render(*page, RENDER_BOX, linex,\n\t *y + offset + temp->height + borderspace,\n\t\t\t temp->width + 2 * borderspace, borderspace, rgb);\n\t // Left\n new_render(*page, RENDER_BOX, linex, *y + offset,\n \t borderspace, temp->height + 2 * borderspace, rgb);\n\t // Right\n new_render(*page, RENDER_BOX, linex + temp->width + borderspace,\n\t *y + offset, borderspace,\n\t\t\t temp->height + 2 * borderspace, rgb);\n\t // Bottom\n new_render(*page, RENDER_BOX, linex, *y + offset,\n \t temp->width + 2 * borderspace, borderspace, rgb);\n\t }", "\t new_render(*page, RENDER_IMAGE, linex + borderspace,\n\t *y + offset + borderspace, temp->width, temp->height,\n\t\t image_find((char *)htmlGetVariable(temp, (uchar *)\"REALSRC\")));\n whitespace = 0;\n\t temp_width = temp->width + 2 * borderspace;\n\t break;\n }", " if (temp->link != NULL &&\n (link = htmlGetVariable(temp->link, (uchar *)\"_HD_FULL_HREF\")) != NULL)\n {\n /*\n\t* Add a page link...\n\t*/", "\tnew_render(*page, RENDER_LINK, linex, *y + offset, temp->width, temp->height, link);\n }", " linex += temp_width;\n prev = temp;\n temp = temp->next;\n if (prev != linetype)\n free(prev);\n }", " /*\n * See if we have a run of characters that hasn't been output...\n */", " if (linetype != NULL)\n {\n r = new_render(*page, RENDER_TEXT, linex - linewidth, *y,\n linewidth, linetype->height, line);\n r->data.text.typeface = linetype->typeface;\n r->data.text.style = linetype->style;\n r->data.text.spacing = char_spacing;\n r->data.text.size = (float)_htmlSizes[linetype->size];\n memcpy(r->data.text.rgb, rgb, sizeof(rgb));", " if (linetype->superscript)\n r->y += height - linetype->height;\n else if (linetype->subscript)\n r->y -= height - linetype->height;", " free(linetype);\n }", " /*\n * Update the margins after we pass below the images...\n */", " *y -= spacing - height;", " DEBUG_printf((\" AFTER y=%.1f, bottom=%.1f\\n\", *y, bottom));", " if (*y < bottom)\n {\n (*page) ++;\n *y = top;", " if (Verbosity)\n progress_show(\"Formatting page %d\", *page);\n }", " if (*y < image_y || *page > image_page)\n {\n image_y = 0.0f;\n image_left = left;\n image_right = right;\n format_width = image_right - image_left;\n }\n }", " *x = left;\n if (*y > image_y && image_y > 0.0f && image_page == *page)\n *y = image_y;", " DEBUG_printf((\"LEAVING parse_paragraph(), x = %.1f, y = %.1f, page = %d, image_y = %.1f\\n\", *x, *y, *page, image_y));\n}", "\n#if defined(PARA_DEBUG) && !defined(DEBUG)\n# undef DEBUG_printf\n# undef DEBUG_puts\n# define DEBUG_printf(x)\n# define DEBUG_puts(x)\n#endif /* PARA_DEBUG && !DEBUG */", "\n/*\n * 'parse_pre()' - Parse preformatted text and produce rendering list output.\n */", "static void\nparse_pre(tree_t *t,\t\t/* I - Tree to parse */\n float left,\t\t/* I - Left margin */\n float right,\t\t/* I - Printable width */\n float bottom,\t/* I - Bottom margin */\n float top,\t\t/* I - Printable top */\n float *x,\t\t/* IO - X position */\n float *y,\t\t/* IO - Y position */\n int *page,\t\t/* IO - Page # */\n int needspace)\t/* I - Need whitespace? */\n{\n tree_t\t*flat, *start, *next;\n uchar\t\t*link,\n\t\tline[10240],\n\t\t*lineptr,\n\t\t*dataptr;\n int\t\tcol;\n float\t\twidth,\n\t\theight,\n\t\trgb[3];\n render_t\t*r;", "\n REF(right);", " DEBUG_printf((\"parse_pre(t=%p, left=%.1f, right=%.1f, x=%.1f, y=%.1f, page=%d\\n\",\n (void *)t, left, right, *x, *y, *page));", " if (t->child == NULL)\n return;", " if (*y < top && needspace)\n *y -= _htmlSpacings[SIZE_P];", " flat = flatten_tree(t->child);", " if (flat == NULL)\n return;", " if (flat->markup == MARKUP_NONE && flat->data != NULL)\n {\n // Skip leading blank line, if present...\n for (dataptr = flat->data; isspace(*dataptr); dataptr ++);", " if (!*dataptr)\n {\n next = flat->next;\n free(flat);\n flat = next;\n }\n }", " while (flat != NULL)\n {\n for (height = 0.0f, start = flat; flat != NULL; flat = flat->next)\n {\n if (flat->height > height)\n height = flat->height;", " if (flat->markup == MARKUP_BR ||\n (flat->markup == MARKUP_NONE && flat->data &&\n\t flat->data[strlen((char *)flat->data) - 1] == '\\n'))\n break;\n }", " if (flat)\n flat = flat->next;", " if (*y < (height + bottom))\n {\n (*page) ++;\n *y = top;", " if (Verbosity)\n\tprogress_show(\"Formatting page %d\", *page);\n }", " *x = left;\n *y -= height;", " if (Verbosity)\n progress_update(100 - (int)(100 * (*y) / PagePrintLength));", " col = 0;\n while (start != flat)\n {\n rgb[0] = start->red / 255.0f;\n rgb[1] = start->green / 255.0f;\n rgb[2] = start->blue / 255.0f;", " if (start->link &&\n\t (link = htmlGetVariable(start->link, (uchar *)\"_HD_FULL_HREF\")) != NULL)\n {\n /*\n\t* Add a page link...\n\t*/", "\tnew_render(*page, RENDER_LINK, *x, *y, start->width, start->height, link);", "\tif (PSLevel == 0 && Links)\n\t{\n memcpy(rgb, link_color, sizeof(rgb));", "\t start->red = (uchar)(link_color[0] * 255.0);\n\t start->green = (uchar)(link_color[1] * 255.0);\n\t start->blue = (uchar)(link_color[2] * 255.0);", " if (LinkStyle)\n\t new_render(*page, RENDER_BOX, *x, *y - 1, start->width, 0,\n\t link_color);\n\t}\n }", " if ((link = htmlGetVariable(start, (uchar *)\"ID\")) != NULL)\n {\n /*\n\t* Add a target link...\n\t*/", "\tadd_link(link, *page, (int)(*y + height));\n }", " switch (start->markup)\n {\n case MARKUP_COMMENT :\n\t parse_comment(start, &left, &right, &bottom, &top, x, y, page, NULL, 0);\n break;", "\tcase MARKUP_A :\n if ((link = htmlGetVariable(start, (uchar *)\"NAME\")) != NULL)\n {\n /*\n * Add a target link...\n */", " add_link(link, *page, (int)(*y + height));\n }\n break;", "\tcase MARKUP_NONE :\n for (lineptr = line, dataptr = start->data;\n\t\t *dataptr != '\\0' && lineptr < (line + sizeof(line) - 1);\n\t\t dataptr ++)\n if (*dataptr == '\\n')\n\t\tbreak;\n else if (*dataptr == '\\t')\n {\n /* This code changed after 15 years to work around new compiler optimization bugs (Issue #349) */\n int num_cols = 8 - (col & 7);", " memcpy(lineptr, \" \", num_cols);\n lineptr += num_cols;\n col += num_cols;\n }\n else if (*dataptr != '\\r')\n {\n \t*lineptr++ = *dataptr;\n \tcol ++;\n }", " *lineptr = '\\0';", " width = get_width(line, start->typeface, start->style, start->size);\n r = new_render(*page, RENDER_TEXT, *x, *y, width, 0, line);\n r->data.text.typeface = start->typeface;\n r->data.text.style = start->style;\n r->data.text.size = (float)_htmlSizes[start->size];\n memcpy(r->data.text.rgb, rgb, sizeof(rgb));", "\t if (start->underline)\n\t new_render(*page, RENDER_BOX, *x, *y - 1, start->width, 0, rgb);", "\t if (start->strikethrough)\n\t new_render(*page, RENDER_BOX, *x, *y + start->height * 0.25f,\n\t \t start->width, 0, rgb);", " *x += start->width;\n break;", "\tcase MARKUP_IMG :\n\t new_render(*page, RENDER_IMAGE, *x, *y, start->width, start->height,\n\t\t image_find((char *)htmlGetVariable(start, (uchar *)\"REALSRC\")));", " *x += start->width;\n col ++;\n\t break;", "\tdefault :\n break;\n }", " next = start->next;\n free(start);\n start = next;", " }", " if ((*x - right) > 0.001 && OverflowErrors)\n progress_error(HD_ERROR_CONTENT_TOO_LARGE,\n\t \"Preformatted text on page %d too long - \"\n\t\t \"truncation or overlapping may occur!\", *page + 1);", " *y -= _htmlSpacings[t->size] - _htmlSizes[t->size];\n }", " *x = left;\n}", "\n//#define TABLE_DEBUG 1\n#ifdef TABLE_DEBUG\n# undef DEBUG_puts\n# define DEBUG_puts(x) puts(x)\n# define DEBUG 1\n# undef DEBUG_printf\n# define DEBUG_printf(x) printf x\n#endif /* TABLE_DEBUG */", "\ntypedef struct\n{\n int debug;\n int num_cols,\n num_rows;\n float border,\n\t\tborder_left,\n border_rgb[3],\n\t\tborder_size,\n cellpadding,\n height;\n int\t\tcol_spans[MAX_COLUMNS],\n\t\trow_spans[MAX_COLUMNS];\n char\t\tcol_fixed[MAX_COLUMNS],\n\t\tcol_percent[MAX_COLUMNS];\n float\t\tcol_lefts[MAX_COLUMNS],\n\t\tcol_rights[MAX_COLUMNS],\n\t\tcol_widths[MAX_COLUMNS],\n\t\tcol_swidths[MAX_COLUMNS],\n\t\tcol_mins[MAX_COLUMNS],\n\t\tcol_smins[MAX_COLUMNS],\n\t\tcol_prefs[MAX_COLUMNS];\n int\t\tcell_page[MAX_COLUMNS],\t// Start page for cell\n\t\tcell_endpage[MAX_COLUMNS];\n\t\t\t\t\t// End page for cell\n float\t\tcell_y[MAX_COLUMNS],\t// Row for each cell\n\t\tcell_endy[MAX_COLUMNS],\t// Row for each cell\n\t\tcell_height[MAX_COLUMNS],\n\t\t\t\t\t// Height of each cell in a row\n\t\tspan_heights[MAX_COLUMNS];\n\t\t\t\t\t// Height of spans\n render_t\t*cell_bg[MAX_COLUMNS];\t// Background rectangles\n render_t\t*cell_start[MAX_COLUMNS];\n\t\t\t\t\t// Start of the content for a cell in the row\n render_t\t*cell_end[MAX_COLUMNS];\t// End of the content for a cell in a row\n} hdtable_t;", "\n/*\n * 'render_table_row()' - Render a table row.\n */", "static void\nrender_table_row(hdtable_t &table,\n tree_t ***cells,\n int row,\n uchar *height_var,\n float left,\t\t// I - Left margin\n float right,\t\t// I - Printable width\n float bottom,\t\t// I - Bottom margin\n float top,\t\t\t// I - Printable top\n float *x,\n float *y,\n int *page)\n{\n int\t\tcol,\n\t\ttcol,\n\t\tcolspan,\n\t\trowspan,\n\t\ttempspace;\n float\t\twidth,\n\t\ttemp_y;\n int\t\ttemp_page;\n uchar\t\t*var;\n int\t\tdo_valign;\t\t// True if we should do vertical alignment of cells\n int row_page;\n float\t\trow_y,\n row_starty,\n row_height,\t\t// Total height of the row\n\t\ttemp_height;\t\t// Temporary holder\n uchar\t\t*bgcolor;\n float\t\tbgrgb[3];", "\n do_valign = 1;\n row_height = 0.0f;\n row_page = *page;\n row_y = *y - table.cellpadding;\n row_starty = row_y;", " DEBUG_printf((\"BEFORE row_y = %.1f, *y = %.1f, row_page = %d\\n\",\n row_y, *y, row_page));", " for (col = 0, rowspan = 9999; col < table.num_cols; col += colspan)\n {\n if (table.row_spans[col] == 0)\n {\n if ((var = htmlGetVariable(cells[row][col], (uchar *)\"ROWSPAN\")) != NULL)\n table.row_spans[col] = atoi((char *)var);", " if (table.row_spans[col] <= 1)\n table.row_spans[col] = 0;", " if (table.row_spans[col] > (table.num_rows - row))\n table.row_spans[col] = table.num_rows - row;", " table.span_heights[col] = 0.0f;\n }", " if (table.row_spans[col] < rowspan)\n rowspan = table.row_spans[col];", " for (colspan = 1; (col + colspan) < table.num_cols; colspan ++)\n if (cells[row][col] != cells[row][col + colspan])\n break;\n }", " if (!rowspan)\n rowspan = 1;", " for (col = 0; col < table.num_cols;)\n {\n for (colspan = 1; (col + colspan) < table.num_cols; colspan ++)\n if (cells[row][col] != cells[row][col + colspan])\n break;\n colspan --;", " DEBUG_printf((\" col = %d, colspan = %d, left = %.1f, right = %.1f, cell = %p\\n\", col, colspan, table.col_lefts[col], table.col_rights[col + colspan], (void *)cells[row][col]));", " *x = table.col_lefts[col];\n temp_y = *y - table.cellpadding;\n temp_page = *page;\n tempspace = 0;", " if (row == 0 || cells[row][col] != cells[row - 1][col])\n {\n check_pages(*page);", " if (cells[row][col] == NULL)\n bgcolor = NULL;\n else if ((bgcolor = htmlGetVariable(cells[row][col], (uchar *)\"BGCOLOR\")) != NULL)\n {\n memcpy(bgrgb, background_color, sizeof(bgrgb));", " get_color(bgcolor, bgrgb, 0);", " width = table.col_rights[col + colspan] - table.col_lefts[col] + 2 * table.cellpadding;\n table.border_left = table.col_lefts[col] - table.cellpadding;", " table.cell_bg[col] = new_render(*page, RENDER_BOX, table.border_left, row_y, width + table.border, 0.0, bgrgb);\n }\n else\n {\n table.cell_bg[col] = NULL;", " new_render(*page, RENDER_TEXT, -1.0f, -1.0f, 0.0, 0.0, (void *)\"\");\n }", " DEBUG_printf((\"cell_bg[%d] = %p, pages[%d].end = %p\\n\", col, (void *)table.cell_bg[col], *page, (void *)pages[*page].end));", " table.cell_start[col] = pages[*page].end;\n table.cell_page[col] = temp_page;\n table.cell_y[col] = temp_y;", " if (table.debug)\n {\n check_pages(*page);", " render_t *r;\n char table_text[255];", " snprintf(table_text, sizeof(table_text), \"cell=%p [%d,%d]\",\n (void *)cells[row][col], row, col);\n r = new_render(temp_page, RENDER_TEXT, *x, temp_y,\n get_width((uchar *)table_text, TYPE_COURIER, STYLE_NORMAL, 1),\n _htmlSizes[1], table_text);", " r->data.text.typeface = TYPE_COURIER;\n r->data.text.style = STYLE_NORMAL;\n r->data.text.size = (float)_htmlSizes[1];\n }", " if (cells[row][col] != NULL && cells[row][col]->child != NULL)\n {\n DEBUG_printf((\" parsing cell %d,%d; width = %.1f\\n\", row, col, table.col_rights[col + colspan] - table.col_lefts[col]));", " bottom += table.cellpadding;\n top -= table.cellpadding;", " parse_doc(cells[row][col]->child, table.col_lefts + col, table.col_rights + col + colspan, &bottom, &top, x, &temp_y, &temp_page, NULL, &tempspace);", " bottom -= table.cellpadding;\n top += table.cellpadding;\n }", " table.cell_endpage[col] = temp_page;\n table.cell_endy[col] = temp_y;\n table.cell_height[col] = *y - table.cellpadding - temp_y;\n table.cell_end[col] = pages[*page].end;", " if (table.cell_start[col] == NULL)\n table.cell_start[col] = pages[*page].start;", " DEBUG_printf((\"row = %d, col = %d, y = %.1f, cell_y = %.1f, cell_height = %.1f\\n\", row, col, *y - table.cellpadding, temp_y, table.cell_height[col]));\n DEBUG_printf((\"cell_start[%d] = %p, cell_end[%d] = %p\\n\", col, (void *)table.cell_start[col], col, (void *)table.cell_end[col]));\n }", " if (table.row_spans[col] == 0 &&\n table.cell_page[col] == table.cell_endpage[col] &&\n table.cell_height[col] > row_height)\n row_height = table.cell_height[col];", " if (table.row_spans[col] <= rowspan)\n {\n if (table.cell_page[col] != table.cell_endpage[col])\n do_valign = 0;", " if (table.cell_endpage[col] > row_page)\n {\n row_page = table.cell_endpage[col];\n row_y = table.cell_endy[col];\n }\n else if (table.cell_endy[col] < row_y && table.cell_endpage[col] == row_page)\n row_y = table.cell_endy[col];\n }", " DEBUG_printf((\"**** col = %d, row = %d, row_y = %.1f, row_page = %d\\n\", col, row, row_y, row_page));", " for (col ++; colspan > 0; colspan --, col ++)\n {\n table.cell_start[col] = NULL;\n table.cell_page[col] = table.cell_page[col - 1];\n table.cell_y[col] = table.cell_y[col - 1];\n table.cell_end[col] = NULL;\n table.cell_endpage[col] = table.cell_endpage[col - 1];\n table.cell_endy[col] = table.cell_endy[col - 1];\n table.cell_height[col] = table.cell_height[col - 1];\n }\n }", " DEBUG_printf((\"row = %d, row_y = %.1f, row_height = %.1f\\n\", row, row_y, row_height));", " for (col = 0; col < table.num_cols; col += colspan)\n {\n for (colspan = 1; (col + colspan) < table.num_cols; colspan ++)\n if (cells[row][col] != cells[row][col + colspan])\n break;", " if (table.row_spans[col])\n table.span_heights[col] += row_height;", " DEBUG_printf((\"col = %d, cell_y = %.1f, cell_page = %d, cell_endpage = %d, row_spans = %d, span_heights = %.1f, cell_height = %.1f\\n\", col, table.cell_y[col], table.cell_page[col], table.cell_endpage[col], table.row_spans[col], table.span_heights[col], table.cell_height[col]));\n }", " for (col = 0; col < table.num_cols; col += colspan)\n {\n for (colspan = 1; (col + colspan) < table.num_cols; colspan ++)\n if (cells[row][col] != cells[row][col + colspan])\n break;", " if (table.row_spans[col] == rowspan &&\n table.cell_page[col] == table.cell_endpage[col] &&\n table.cell_height[col] > table.span_heights[col])\n {\n temp_height = table.cell_height[col] - table.span_heights[col];\n row_height += temp_height;\n DEBUG_printf((\"Adjusting row-span height by %.1f, new row_height = %.1f\\n\", temp_height, row_height));", " for (tcol = 0; tcol < table.num_cols; tcol ++)\n if (table.row_spans[tcol])\n {\n table.span_heights[tcol] += temp_height;\n DEBUG_printf((\"col = %d, span_heights = %.1f\\n\", tcol, table.span_heights[tcol]));\n }\n }\n }", " DEBUG_printf((\"AFTER row = %d, row_page = %d, row_y = %.1f, row_height = %.1f, *y = %.1f, do_valign = %d\\n\", row, row_page, row_y, row_height, *y, do_valign));", " /*\n * Do the vertical alignment\n */", " if (do_valign)\n {\n height_var = NULL;", " if (cells[row][0] != NULL)\n {\n if ((height_var = htmlGetVariable(cells[row][0]->parent, (uchar *)\"HEIGHT\")) == NULL)\n\tfor (col = 0; col < table.num_cols; col ++)\n\t if (htmlGetVariable(cells[row][col], (uchar *)\"ROWSPAN\") == NULL)\n\t if ((height_var = htmlGetVariable(cells[row][col], (uchar *)\"HEIGHT\")) != NULL)\n\t break;\n }", " if (height_var != NULL)\n {\n // Hardcode the row height...\n if (height_var[strlen((char *)height_var) - 1] == '%')\n temp_height = (float)(atof((char *)height_var) * 0.01f * PagePrintLength);\n else\n temp_height = (float)(atof((char *)height_var) * PagePrintWidth / _htmlBrowserWidth);", " if (table.height > 0 && temp_height > table.height)\n temp_height = table.height;", " temp_height -= 2 * table.cellpadding;", " if (temp_height > row_height)\n {\n // Only enforce the height if it is > the actual row height.\n row_height = temp_height;\n row_y = *y - temp_height;\n }\n }", " for (col = 0; col < table.num_cols; col += colspan + 1)\n {\n render_t\t*p;\n float\tdelta_y;", "\n for (colspan = 1; (col + colspan) < table.num_cols; colspan ++)\n if (cells[row][col] != cells[row][col + colspan])\n break;", " colspan --;", " if (table.cell_start[col] == NULL || table.row_spans[col] > rowspan ||\n cells[row][col] == NULL || cells[row][col]->child == NULL)\n continue;", " if (table.row_spans[col] == 1)\n {\n int tcol;\n float span_height = 0.0f;", " for (tcol = 0; tcol < table.num_cols; tcol ++)\n {\n if (table.row_spans[col] == 1 && table.span_heights[col] > span_height)\n span_height = table.span_heights[col];\n }", " switch (cells[row][col]->valignment)\n {\n case ALIGN_MIDDLE :\n// delta_y = (table.span_heights[col] - table.cell_height[col]) * 0.5f;\n delta_y = (span_height - table.cell_height[col]) * 0.5f;\n break;", " case ALIGN_BOTTOM :\n// delta_y = table.span_heights[col] - table.cell_height[col];\n delta_y = span_height - table.cell_height[col];\n break;", " default :\n delta_y = 0.0f;\n break;\n }\n }\n else if (table.row_spans[col])\n {\n delta_y = 0.0f;\n }\n else\n {\n switch (cells[row][col]->valignment)\n {\n case ALIGN_MIDDLE :\n delta_y = (row_height - table.cell_height[col]) * 0.5f;\n break;", " case ALIGN_BOTTOM :\n delta_y = row_height - table.cell_height[col];\n break;", " default :\n delta_y = 0.0f;\n break;\n }\n }", " DEBUG_printf((\"row = %d, col = %d, valign = %d, rowspans = %d, cell_height = %.1f, span_heights = %.1f, delta_y = %.1f\\n\", row, col, cells[row][col]->valignment, table.row_spans[col], table.cell_height[col], table.span_heights[col], delta_y));", " if (delta_y > 0.0f)\n {\n if (table.cell_start[col] == table.cell_end[col])\n p = table.cell_start[col];\n else\n p = table.cell_start[col]->next;", " for (; p != NULL; p = p->next)\n {\n DEBUG_printf((\"aligning %p (%s), y was %.1f, now %.1f\\n\",\n (void *)p, p->data.text.buffer, p->y, p->y - delta_y));", " p->y -= delta_y;\n if (p == table.cell_end[col])\n break;\n }\n }\n#ifdef DEBUG\n else\n {\n if (table.cell_start[col] == table.cell_end[col])\n p = table.cell_start[col];\n else\n p = table.cell_start[col]->next;", " for (; p != NULL; p = p->next)\n {\n printf(\"NOT aligning %p (%s)\\n\", (void *)p, p->data.text.buffer);", " if (p == table.cell_end[col])\n break;\n }\n }\n#endif /* DEBUG */\n }\n }", " // Update all current columns with ROWSPAN <= rowspan to use the same\n // end page and row...\n for (col = 0, temp_page = -1, temp_y = 99999999; col < table.num_cols; col ++)\n if (table.row_spans[col] <= rowspan &&\n cells[row][col] != NULL && cells[row][col]->child != NULL)\n {\n if (table.cell_endpage[col] > temp_page)\n {\n temp_page = table.cell_endpage[col];\n temp_y = table.cell_endy[col];\n }\n else if (table.cell_endpage[col] == temp_page && table.cell_endy[col] < temp_y)\n temp_y = table.cell_endy[col];\n }", " for (col = 0; col < table.num_cols; col ++)\n if (table.row_spans[col] <= rowspan &&\n cells[row][col] != NULL && cells[row][col]->child != NULL)\n {\n table.cell_endpage[col] = temp_page;\n table.cell_endy[col] = temp_y;\n }", " row_y -= table.cellpadding;", " table.border_left = table.col_lefts[0] - table.cellpadding;\n width = table.col_rights[table.num_cols - 1] - table.col_lefts[0] + 2 * table.cellpadding;", " for (bgcolor = NULL, col = 0; col < table.num_cols; col ++)\n if (table.row_spans[col] <= rowspan &&\n cells[row][col] &&\n !htmlGetVariable(cells[row][col], (uchar *)\"ROWSPAN\") &&\n (bgcolor = htmlGetVariable(cells[row][col]->parent,\n (uchar *)\"BGCOLOR\")) != NULL)\n break;", " if (bgcolor)\n {\n memcpy(bgrgb, background_color, sizeof(bgrgb));", " get_color(bgcolor, bgrgb, 0);", " if (row_page > *page)\n {\n // Draw background on multiple pages...", " // Bottom of first page...\n new_render(*page, RENDER_BOX, table.border_left, bottom,\n width, row_starty - bottom + table.cellpadding, bgrgb,\n pages[*page].start);", " // Intervening pages...\n for (temp_page = *page + 1; temp_page < row_page; temp_page ++)\n {\n new_render(temp_page, RENDER_BOX, table.border_left, bottom,\n width, top - bottom, bgrgb, pages[temp_page].start);\n }", " // Top of last page...\n check_pages(*page);", " new_render(row_page, RENDER_BOX, table.border_left, row_y,\n width, top - row_y, bgrgb,\n pages[row_page].start);\n }\n else\n {\n // Draw background in row...\n new_render(row_page, RENDER_BOX, table.border_left, row_y,\n width, row_height + 2 * table.cellpadding, bgrgb,\n pages[row_page].start);\n }\n }", " for (col = 0; col < table.num_cols; col += colspan + 1)\n {\n for (colspan = 0; (col + colspan) < table.num_cols; colspan ++)\n if (cells[row][col] != cells[row][col + colspan])\n break;\n else if (table.row_spans[col + colspan] > 0)\n {\n DEBUG_printf((\"row = %d, col = %d, decrementing row_spans (%d) to %d...\\n\", row,\n col, table.row_spans[col + colspan],\n table.row_spans[col + colspan] - rowspan));\n table.row_spans[col + colspan] -= rowspan;\n }", " colspan --;", " width = table.col_rights[col + colspan] - table.col_lefts[col] +\n 2 * table.cellpadding;", " if (cells[row][col] == NULL || cells[row][col]->child == NULL ||\n table.row_spans[col] > 0)\n continue;", " DEBUG_printf((\"DRAWING BORDER+BACKGROUND: col=%d, row=%d, cell_page=%d, cell_y=%.1f\\n\"\n \" cell_endpage=%d, cell_endy=%.1f\\n\",\n col, row, table.cell_page[col], table.cell_y[col],\n table.cell_endpage[col], table.cell_endy[col]));", " if ((bgcolor = htmlGetVariable(cells[row][col],\n (uchar *)\"BGCOLOR\")) != NULL)\n {\n memcpy(bgrgb, background_color, sizeof(bgrgb));", " get_color(bgcolor, bgrgb, 0);\n }", " table.border_left = table.col_lefts[col] - table.cellpadding;", " if (table.cell_page[col] != table.cell_endpage[col])\n {\n /*\n * Crossing a page boundary...\n */", " if (table.border > 0)\n {\n /*\n * +---+---+---+\n * | | | |\n */", " // Top\n new_render(table.cell_page[col], RENDER_BOX, table.border_left,\n table.cell_y[col] + table.cellpadding,\n width + table.border, table.border, table.border_rgb);\n // Left\n new_render(table.cell_page[col], RENDER_BOX, table.border_left, bottom,\n table.border, table.cell_y[col] - bottom + table.cellpadding + table.border, table.border_rgb);\n // Right\n new_render(table.cell_page[col], RENDER_BOX,\n table.border_left + width, bottom,\n table.border, table.cell_y[col] - bottom + table.cellpadding + table.border, table.border_rgb);\n }", " if (bgcolor != NULL)\n {\n table.cell_bg[col]->y = bottom;\n table.cell_bg[col]->height = table.cell_y[col] - bottom + table.cellpadding + table.border;\n }", " for (temp_page = table.cell_page[col] + 1; temp_page < table.cell_endpage[col]; temp_page ++)\n {\n /*\n * | | | |\n * | | | |\n */", " if (table.border > 0.0f)\n {\n // Left\n new_render(temp_page, RENDER_BOX, table.border_left, bottom,\n table.border, top - bottom, table.border_rgb);\n // Right\n new_render(temp_page, RENDER_BOX,\n table.border_left + width, bottom,\n table.border, top - bottom, table.border_rgb);\n }", " if (bgcolor != NULL)\n new_render(temp_page, RENDER_BOX, table.border_left, bottom,\n width + table.border, top - bottom, bgrgb,\n pages[temp_page].start);\n }", " if (table.border > 0.0f)\n {\n /*\n * | | | |\n * +---+---+---+\n */", " // Left\n new_render(table.cell_endpage[col], RENDER_BOX, table.border_left, row_y,\n table.border, top - row_y, table.border_rgb);\n // Right\n new_render(table.cell_endpage[col], RENDER_BOX,\n table.border_left + width, row_y,\n table.border, top - row_y, table.border_rgb);\n // Bottom\n new_render(table.cell_endpage[col], RENDER_BOX, table.border_left, row_y,\n width + table.border, table.border, table.border_rgb);\n }", " if (bgcolor != NULL)\n {\n check_pages(table.cell_endpage[col]);", " new_render(table.cell_endpage[col], RENDER_BOX, table.border_left, row_y,\n width + table.border, top - row_y, bgrgb,\n pages[table.cell_endpage[col]].start);\n }\n }\n else\n {\n /*\n * +---+---+---+\n * | | | |\n * +---+---+---+\n */", " if (table.border > 0.0f)\n {\n // Top\n new_render(table.cell_page[col], RENDER_BOX, table.border_left,\n table.cell_y[col] + table.cellpadding,\n width + table.border, table.border, table.border_rgb);\n // Left\n new_render(table.cell_page[col], RENDER_BOX, table.border_left, row_y,\n table.border, table.cell_y[col] - row_y + table.cellpadding + table.border, table.border_rgb);\n // Right\n new_render(table.cell_page[col], RENDER_BOX,\n table.border_left + width, row_y,\n table.border, table.cell_y[col] - row_y + table.cellpadding + table.border, table.border_rgb);\n // Bottom\n new_render(table.cell_page[col], RENDER_BOX, table.border_left, row_y,\n width + table.border, table.border, table.border_rgb);\n }", " if (bgcolor != NULL)\n {\n table.cell_bg[col]->y = row_y;\n table.cell_bg[col]->height = table.cell_y[col] - row_y + table.cellpadding + table.border;\n }\n }\n }", " *page = row_page;\n *y = row_y;\n}", "\n/*\n * 'parse_table()' - Parse a table and produce rendering output.\n */", "static void\nparse_table(tree_t *t,\t\t\t// I - Tree to parse\n float left,\t\t// I - Left margin\n float right,\t\t// I - Printable width\n float bottom,\t\t// I - Bottom margin\n float top,\t\t\t// I - Printable top\n float *x,\t\t\t// IO - X position\n float *y,\t\t\t// IO - Y position\n int *page,\t\t// IO - Page #\n int needspace)\t\t// I - Need whitespace?\n{\n int\t\tcol,\n\t\trow,\n header_row = -1,\n\t\ttcol,\n\t\tcolspan,\n\t\trowspan,\n\t\talloc_rows,\n\t\tregular_cols;\n hdtable_t table;\n float\t\tcol_width,\n\t\tcol_min,\n\t\tcol_pref,\n\t\tcol_height,\n\t\tcellspacing,\n\t\twidth,\n\t\tpref_width,\n\t\tspan_width,\n\t\tregular_width,\n\t\tactual_width,\n\t\ttable_width,\n\t\tmin_width,\n\t\ttemp_width,\n header_height = 0.0,\n\t\ttable_y,\n temp_bottom,\n\t\ttemp_top;\n int\t\ttemp_page, table_page;\n uchar\t\t*var,\n\t\t*height_var,\t\t// Row HEIGHT variable\n *header_height_var = NULL;\n tree_t\t*temprow,\n\t\t*tempcol,\n\t\t*tempnext,\n\t\t***cells,\n\t\t*caption;\t\t// Caption for bottom, if any\n float\t\ttemp_height;\t\t// Temporary holder\n uchar\t\t*bgcolor;\n float\t\tbgrgb[3];\n const char\t*htmldoc_debug;\t\t// HTMLDOC_DEBUG env var", "\n DEBUG_puts(\"\\n\\nTABLE\");", " DEBUG_printf((\"parse_table(t=%p, left=%.1f, right=%.1f, x=%.1f, y=%.1f, page=%d\\n\",\n (void *)t, left, right, *x, *y, *page));", " if (t->child == NULL)\n return; /* Empty table... */", " memset(&table, 0, sizeof(table));", " /*\n * Check debug mode...\n */", " if ((htmldoc_debug = getenv(\"HTMLDOC_DEBUG\")) != NULL &&\n (strstr(htmldoc_debug, \"table\") || strstr(htmldoc_debug, \"all\")))\n table.debug = 1;\n else\n table.debug = 0;", " /*\n * Figure out the # of rows, columns, and the desired widths...\n */", " cells = NULL;", " if ((var = htmlGetVariable(t, (uchar *)\"WIDTH\")) != NULL)\n {\n if (var[strlen((char *)var) - 1] == '%')\n table_width = (float)(atof((char *)var) * (right - left) / 100.0f);\n else\n table_width = (float)(atoi((char *)var) * PagePrintWidth / _htmlBrowserWidth);", " if (table_width < 0.0f || table_width > PagePrintWidth)\n table_width = right - left;\n }\n else\n table_width = right - left;", " if ((var = htmlGetVariable(t, (uchar *)\"HEIGHT\")) != NULL)\n {\n if (var[strlen((char *)var) - 1] == '%')\n table.height = (float)(atof((char *)var) * (top - bottom) / 100.0f);\n else\n table.height = (float)(atoi((char *)var) * PagePrintWidth / _htmlBrowserWidth);\n }\n else\n table.height = -1.0f;", " DEBUG_printf((\"table_width = %.1f\\n\", table_width));", " if ((var = htmlGetVariable(t, (uchar *)\"CELLPADDING\")) != NULL)\n {\n if ((table.cellpadding = atoi((char *)var)) < 0.0f)\n table.cellpadding = 0.0f;\n else if (table.cellpadding > 20.0f)\n table.cellpadding = 20.0f;\n }\n else\n table.cellpadding = 1.0f;", " if ((var = htmlGetVariable(t, (uchar *)\"CELLSPACING\")) != NULL)\n {\n if ((cellspacing = atoi((char *)var)) < 0.0f)\n cellspacing = 0.0f;\n else if (cellspacing > 20.0f)\n cellspacing = 20.0f;\n }\n else\n cellspacing = 0.0f;", " if ((var = htmlGetVariable(t, (uchar *)\"BORDER\")) != NULL)\n {\n if ((table.border = (float)atof((char *)var)) <= 0.0 && var[0] != '0')\n table.border = 1.0f;\n else if (table.border > 20.0f)\n table.border = 20.0f;", " table.cellpadding += table.border;\n }\n else\n table.border = 0.0f;", " if (table.debug && table.border == 0.0f)\n table.border = 0.01f;", " table.border_rgb[0] = t->red / 255.0f;\n table.border_rgb[1] = t->green / 255.0f;\n table.border_rgb[2] = t->blue / 255.0f;", " if ((var = htmlGetVariable(t, (uchar *)\"BORDERCOLOR\")) != NULL)\n get_color(var, table.border_rgb, 0);", " if (table.border == 0.0f && table.cellpadding > 0.0f)\n {\n /*\n * Ah, the strange table formatting nightmare that is HTML.\n * Netscape and MSIE assign an invisible border width of 1\n * pixel if no border is specified...\n */", " table.cellpadding += 1.0f;\n }", " table.border_size = table.border - 1.0f;", " cellspacing *= PagePrintWidth / _htmlBrowserWidth;\n table.cellpadding *= PagePrintWidth / _htmlBrowserWidth;\n table.border *= PagePrintWidth / _htmlBrowserWidth;\n table.border_size *= PagePrintWidth / _htmlBrowserWidth;", " DEBUG_printf((\"border = %.1f, cellpadding = %.1f\\n\", table.border, table.cellpadding));", " temp_bottom = bottom - table.cellpadding;\n temp_top = top + table.cellpadding;", " for (temprow = t->child, table.num_cols = 0, table.num_rows = 0, alloc_rows = 0, caption = NULL;\n temprow != NULL;\n temprow = tempnext)\n {\n tempnext = temprow->next;", " if (temprow->markup == MARKUP_CAPTION)\n {\n if ((var = htmlGetVariable(temprow, (uchar *)\"ALIGN\")) == NULL ||\n strcasecmp((char *)var, \"bottom\"))\n {\n /*\n * Show caption at top...\n\t*/", " parse_paragraph(temprow, left, right, bottom, top, x, y, page, needspace);\n needspace = 1;\n }\n else\n {\n /*\n * Flag caption for bottom of table...\n\t*/", " caption = temprow;\n }\n }\n else if (temprow->markup == MARKUP_TR ||\n ((temprow->markup == MARKUP_TBODY || temprow->markup == MARKUP_THEAD ||\n temprow->markup == MARKUP_TFOOT) && temprow->child != NULL))\n {\n if (temprow->markup == MARKUP_THEAD)\n header_row = table.num_rows;", " // Descend into table body as needed...\n if (temprow->markup == MARKUP_TBODY || temprow->markup == MARKUP_THEAD ||\n temprow->markup == MARKUP_TFOOT)\n temprow = temprow->child;", " // Figure out the next row...\n if ((tempnext = temprow->next) == NULL)\n if (temprow->parent->markup == MARKUP_TBODY ||\n temprow->parent->markup == MARKUP_THEAD ||\n temprow->parent->markup == MARKUP_TFOOT)\n tempnext = temprow->parent->next;", " // Allocate memory for the table as needed...\n if (table.num_rows >= alloc_rows)\n {\n alloc_rows += ALLOC_ROWS;", " if (alloc_rows == ALLOC_ROWS)\n\t cells = (tree_t ***)malloc(sizeof(tree_t **) * (size_t)alloc_rows);\n\telse\n\t cells = (tree_t ***)realloc(cells, sizeof(tree_t **) * (size_t)alloc_rows);", " if (cells == (tree_t ***)0)\n\t{\n\t progress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory for table!\");\n\t return;\n\t}\n }", " if ((cells[table.num_rows] = (tree_t **)calloc(sizeof(tree_t *), MAX_COLUMNS)) == NULL)\n {\n\tprogress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory for table!\");\n free(cells);\n\treturn;\n }", "#ifdef DEBUG\n printf(\"BEFORE row %d: num_cols = %d\\n\", table.num_rows, table.num_cols);", " if (table.num_rows)\n for (col = 0; col < table.num_cols; col ++)\n\t printf(\" col %d: row_spans[] = %d\\n\", col, table.row_spans[col]);\n#endif // DEBUG", " // Figure out the starting column...\n if (table.num_rows)\n {\n\tfor (col = 0, rowspan = 9999; col < table.num_cols; col ++)\n\t if (table.row_spans[col] < rowspan)\n\t rowspan = table.row_spans[col];", "\tfor (col = 0; col < table.num_cols; col ++)\n\t table.row_spans[col] -= rowspan;", "\tfor (col = 0; table.row_spans[col] && col < table.num_cols; col ++)\n cells[table.num_rows][col] = cells[table.num_rows - 1][col];\n }\n else\n col = 0;", " for (tempcol = temprow->child;\n tempcol != NULL && col < MAX_COLUMNS;\n tempcol = tempcol->next)\n {\n if (tempcol->markup == MARKUP_TH && table.num_rows == 0)\n header_row = table.num_rows;", " if (tempcol->markup == MARKUP_TD || tempcol->markup == MARKUP_TH)\n {\n\t // Handle colspan and rowspan stuff...\n if ((var = htmlGetVariable(tempcol, (uchar *)\"COLSPAN\")) != NULL)\n {\n if ((colspan = atoi((char *)var)) < 1)\n colspan = 1;\n else if (colspan > (MAX_COLUMNS - col))\n colspan = MAX_COLUMNS - col;\n }\n else\n colspan = 1;", " if ((var = htmlGetVariable(tempcol, (uchar *)\"ROWSPAN\")) != NULL)\n\t {\n table.row_spans[col] = atoi((char *)var);", "\t if (table.row_spans[col] <= 1)\n\t table.row_spans[col] = 0;", "\t for (tcol = 1; tcol < colspan; tcol ++)\n table.row_spans[col + tcol] = table.row_spans[col];\n }", " // Compute the cell size...\n col_width = get_cell_size(tempcol, 0.0f, table_width, &col_min, &col_pref, &col_height);\n if ((var = htmlGetVariable(tempcol, (uchar *)\"WIDTH\")) != NULL)\n\t {\n\t if (var[strlen((char *)var) - 1] == '%')\n\t {\n col_width -= 2.0 * table.cellpadding - cellspacing;", "\t if (colspan <= 1)\n\t table.col_percent[col] = 1;\n\t }\n\t else\n\t {\n col_width -= 2.0 * table.cellpadding;\n\t }", "\t if (col_width <= 0.0f)\n\t col_width = 0.0f;\n\t else if (col_width > PageWidth)\n\t col_width = PageWidth;\n\t }\n\t else\n\t col_width = 0.0f;", " tempcol->height = col_height;", "\t DEBUG_printf((\"%d,%d: colsp=%d, rowsp=%d, width=%.1f, minw=%.1f, prefw=%.1f, minh=%.1f\\n\", col, table.num_rows, colspan, table.row_spans[col], col_width, col_min, col_pref, col_height));", " // Add widths to columns...\n if (colspan > 1)\n {\n\t if (colspan > table.col_spans[col])\n\t table.col_spans[col] = colspan;", "\t if (col_width > table.col_swidths[col])\n\t table.col_swidths[col] = col_width;", "\t if (col_min > table.col_smins[col])\n\t table.col_smins[col] = col_min;", "\t temp_width = col_width / colspan;\n\t for (int i = 0; i < colspan; i ++)\n\t {\n\t if (temp_width > table.col_widths[col + i])\n\t table.col_widths[col + i] = temp_width;\n\t }\n }\n\t else\n\t {\n\t if (col_width > 0.0f)\n\t table.col_fixed[col] = 1;", "\t if (col_width > table.col_widths[col])\n\t table.col_widths[col] = col_width;", "\t if (col_pref > table.col_prefs[col])\n\t table.col_prefs[col] = col_pref;", "\t if (col_min > table.col_mins[col])\n\t table.col_mins[col] = col_min;\n }", "\t while (colspan > 0 && col < MAX_COLUMNS)\n\t {\n cells[table.num_rows][col] = tempcol;\n col ++;\n colspan --;\n }", " while (table.row_spans[col] && col < table.num_cols)\n\t {\n cells[table.num_rows][col] = cells[table.num_rows - 1][col];\n\t col ++;\n\t }\n }\n }", " DEBUG_printf((\"header_row=%d\\n\", header_row));", " if (col > table.num_cols)\n table.num_cols = col;", "#ifdef DEBUG\n printf(\"AFTER row %d: num_cols = %d\\n\", table.num_rows, table.num_cols);", " for (col = 0; col < table.num_cols; col ++)\n printf(\" col %d: row_spans[] = %d\\n\", col, table.row_spans[col]);\n#endif // DEBUG", " table.num_rows ++;", " for (col = 0; col < table.num_cols; col ++)\n if (table.row_spans[col])\n\t table.row_spans[col] --;\n }\n }", " /*\n * OK, some people apparently create HTML tables with no columns or\n * rows... If this happened, return immediately...\n */", " if (table.num_cols == 0)\n return;", " /*\n * Now figure out the width of the table...\n */", " if ((var = htmlGetVariable(t, (uchar *)\"WIDTH\")) != NULL)\n {\n if (var[strlen((char *)var) - 1] == '%')\n width = (float)(atof((char *)var) * (right - left) / 100.0f);\n else\n width = (float)(atoi((char *)var) * PagePrintWidth / _htmlBrowserWidth);\n }\n else\n {\n for (col = 0, width = 0.0; col < table.num_cols; col ++)\n width += table.col_prefs[col];", " width += (2 * table.cellpadding + cellspacing) * table.num_cols - cellspacing;", " if (width > (right - left))\n width = right - left;\n }", " /*\n * Compute the width of each column based on the printable width.\n */", " DEBUG_printf((\"\\nTABLE: %dx%d\\n\\n\", table.num_cols, table.num_rows));", " actual_width = (2 * table.cellpadding + cellspacing) * table.num_cols -\n cellspacing;\n regular_width = (width - actual_width) / table.num_cols;", " DEBUG_printf((\" width = %.1f, actual_width = %.1f, regular_width = %.1f\\n\\n\",\n width, actual_width, regular_width));\n DEBUG_puts(\" Col Width Min Pref Fixed? Percent?\");\n DEBUG_puts(\" --- ------ ------ ------ ------ --------\");", "#ifdef DEBUG\n for (col = 0; col < table.num_cols; col ++)\n printf(\" %-3d %-6.1f %-6.1f %-6.1f %-6s %s\\n\", col, table.col_widths[col], table.col_mins[col], table.col_prefs[col], table.col_fixed[col] ? \"YES\" : \"NO\", table.col_percent[col] ? \"YES\" : \"NO\");", " puts(\"\");\n#endif /* DEBUG */", " /*\n * The first pass just handles columns with a specified width...\n */", " DEBUG_puts(\"PASS 1: fixed width handling\\n\");", " for (col = 0, regular_cols = 0; col < table.num_cols; col ++)\n if (table.col_widths[col] > 0.0f)\n {\n if (table.col_mins[col] > table.col_widths[col])\n {\n DEBUG_printf((\" updating column %d to width=%.1f\\n\", col, table.col_mins[col]));", " table.col_widths[col] = table.col_mins[col];\n }", " actual_width += table.col_widths[col];\n }\n else\n {\n regular_cols ++;", " actual_width += table.col_mins[col];\n }", " DEBUG_printf((\" actual_width = %.1f, regular_cols = %d\\n\\n\", actual_width,regular_cols));", " /*\n * Pass two uses the \"preferred\" width whenever possible, and the\n * minimum otherwise...\n */", " DEBUG_puts(\"PASS 2: preferred width handling\\n\");", " for (col = 0, pref_width = 0.0f; col < table.num_cols; col ++)\n if (table.col_widths[col] == 0.0f)\n pref_width += table.col_prefs[col] - table.col_mins[col];", " DEBUG_printf((\" pref_width = %.1f\\n\", pref_width));", " if (pref_width > 0.0f)\n {\n if ((regular_width = (width - actual_width) / pref_width) < 0.0f)\n regular_width = 0.0f;\n else if (regular_width > 1.0f)\n regular_width = 1.0f;", " DEBUG_printf((\" regular_width = %.1f\\n\", regular_width));", " for (col = 0; col < table.num_cols; col ++)\n if (table.col_widths[col] == 0.0f)\n {\n\tpref_width = (table.col_prefs[col] - table.col_mins[col]) * regular_width;", "\tif ((actual_width + pref_width) > width)\n\t{\n if (col == (table.num_cols - 1) && (width - actual_width) >= table.col_mins[col])\n\t table.col_widths[col] = width - actual_width;\n\t else\n\t table.col_widths[col] = table.col_mins[col];\n\t}\n\telse\n table.col_widths[col] = pref_width + table.col_mins[col];", " DEBUG_printf((\" col_widths[%d] = %.1f\\n\", col, table.col_widths[col]));", "\tactual_width += table.col_widths[col] - table.col_mins[col];\n }\n }\n else\n {\n /*\n * Assign min widths for all cells...\n */", " for (col = 0; col < table.num_cols; col ++)\n if (table.col_widths[col] == 0.0f)\n table.col_widths[col] = table.col_mins[col];\n }", " DEBUG_printf((\" actual_width = %.1f\\n\\n\", actual_width));", " /*\n * Pass three enforces any hard or minimum widths for COLSPAN'd\n * columns...\n */", " DEBUG_puts(\"PASS 3: colspan handling\\n\\n\");", " for (col = 0; col < table.num_cols; col ++)\n {\n DEBUG_printf((\" col %d, colspan %d\\n\", col, table.col_spans[col]));", " if (table.col_spans[col] > 1)\n {\n for (colspan = 0, span_width = 0.0f; colspan < table.col_spans[col]; colspan ++)\n span_width += table.col_widths[col + colspan];", " pref_width = 0.0f;", " if (span_width < table.col_swidths[col])\n pref_width = table.col_swidths[col];\n if (span_width < table.col_smins[col] && pref_width < table.col_smins[col])\n pref_width = table.col_smins[col];", " for (colspan = 0; colspan < table.col_spans[col]; colspan ++)\n if (table.col_fixed[col + colspan])\n\t{\n span_width -= table.col_widths[col + colspan];\n\t pref_width -= table.col_widths[col + colspan];\n\t}", " DEBUG_printf((\" col_swidths=%.1f, col_smins=%.1f, span_width=%.1f, pref_width=%.1f\\n\", table.col_swidths[col], table.col_smins[col], span_width, pref_width));", " if (pref_width > 0.0f && pref_width > span_width)\n {\n if (span_width >= 1.0f)\n\t{\n // Expand cells proportionately...\n\t regular_width = pref_width / span_width;", "\t for (colspan = 0; colspan < table.col_spans[col]; colspan ++)\n\t if (!table.col_fixed[col + colspan])\n\t {\n\t actual_width -= table.col_widths[col + colspan];\n\t table.col_widths[col + colspan] *= regular_width;\n\t actual_width += table.col_widths[col + colspan];", " DEBUG_printf((\" col_widths[%d] = %.1f\\n\", col + colspan, table.col_widths[col + colspan]));\n\t }\n }\n\telse\n\t{\n\t // Divide the space up equally between columns, since the\n\t // colspan area is always by itself... (this hack brought\n\t // to you by Yahoo! and their single cell tables with\n\t // colspan=2 :)", "\t regular_width = pref_width / table.col_spans[col];", "\t for (colspan = 0; colspan < table.col_spans[col]; colspan ++)\n\t {\n\t actual_width += regular_width;\n\t table.col_widths[col + colspan] += regular_width;", " DEBUG_printf((\" col_widths[%d] = %.1f\\n\", col, table.col_widths[col]));\n\t }\n\t}\n }\n }\n }", " DEBUG_printf((\" actual_width = %.1f\\n\\n\", actual_width));", " /*\n * Pass four divides up the remaining space amongst the columns...\n */", " DEBUG_puts(\"PASS 4: divide remaining space, if any...\\n\");", " if (width > actual_width)\n {\n for (col = 0, colspan = 0; col < table.num_cols; col ++)\n if (!table.col_fixed[col] || table.col_percent[col])\n colspan ++;", " if (colspan > 0)\n {\n regular_width = (width - actual_width) / table.num_cols;", " for (col = 0; col < table.num_cols; col ++)\n if (!table.col_fixed[col])\n\t{\n\t table.col_widths[col] += regular_width;\n\t DEBUG_printf((\" col_widths[%d] = %.1f\\n\", col, table.col_widths[col]));\n\t}\n }\n }\n else\n width = actual_width;", " DEBUG_puts(\"\");", " /*\n * The final pass is only run if the width > table_width...\n */", " DEBUG_puts(\"PASS 5: Squeeze table as needed...\");", " if (width > table_width)\n {\n /*\n * Squeeze the table to fit the requested width or the printable width\n * as determined at the beginning...\n */", " for (col = 0, min_width = -cellspacing; col < table.num_cols; col ++)\n min_width += table.col_mins[col] + 2 * table.cellpadding + cellspacing;", " DEBUG_printf((\" table_width = %.1f, width = %.1f, min_width = %.1f\\n\", table_width, width, min_width));", " temp_width = table_width - min_width;\n if (temp_width < 0.0f)\n temp_width = 0.0f;", " width -= min_width;\n if (width < 1.0f)\n width = 1.0f;", " for (col = 0; col < table.num_cols; col ++)\n {\n table.col_widths[col] = table.col_mins[col] + temp_width * (table.col_widths[col] - table.col_mins[col]) / width;", " DEBUG_printf((\" col_widths[%d] = %.1f\\n\", col, table.col_widths[col]));\n }", " for (col = 0, width = -cellspacing; col < table.num_cols; col ++)\n width += table.col_widths[col] + 2 * table.cellpadding + cellspacing;", " DEBUG_printf((\" new width = %.1f, max width = %.1f\\n\", width, right - left));\n }", " if ((width - right + left) > 0.001f && OverflowErrors)\n progress_error(HD_ERROR_CONTENT_TOO_LARGE, \"Table on page %d too wide - truncation or overlapping may occur!\", *page + 1);", " DEBUG_puts(\"\");", " DEBUG_printf((\"Final table width = %.1f, alignment = %d\\n\", width, t->halignment));", " switch (t->halignment)\n {\n case ALIGN_LEFT :\n *x = left + table.cellpadding;\n break;\n case ALIGN_CENTER :\n *x = left + 0.5f * (right - left - width) + table.cellpadding;\n break;\n case ALIGN_RIGHT :\n *x = right - width + table.cellpadding;\n break;\n }", " for (col = 0; col < table.num_cols; col ++)\n {\n table.col_lefts[col] = *x;\n table.col_rights[col] = *x + table.col_widths[col];\n *x = table.col_rights[col] + 2 * table.cellpadding + cellspacing;", " DEBUG_printf((\"left[%d] = %.1f, right[%d] = %.1f\\n\", col, table.col_lefts[col], col, table.col_rights[col]));\n }", " /*\n * Now render the whole table...\n */", " if (*y < top && needspace)\n *y -= _htmlSpacings[SIZE_P];", " if (table.debug)\n {\n check_pages(*page);", " render_t *r;\n char table_text[255];", " snprintf(table_text, sizeof(table_text), \"t=%p\", (void *)t);\n r = new_render(*page, RENDER_TEXT, left, *y,\n get_width((uchar *)table_text, TYPE_COURIER, STYLE_NORMAL, 3),\n\t\t _htmlSizes[3], table_text);", " r->data.text.typeface = TYPE_COURIER;\n r->data.text.style = STYLE_NORMAL;\n r->data.text.size = (float)_htmlSizes[3];\n }", " table_page = *page;\n table_y = *y;", " for (row = 0; row < table.num_rows; row ++)\n {\n height_var = NULL;", " if (cells[row][0] != NULL)\n {\n /*\n * Do page comments...\n */", " if (cells[row][0]->parent->prev != NULL &&\n cells[row][0]->parent->prev->markup == MARKUP_COMMENT)\n parse_comment(cells[row][0]->parent->prev, &left, &right, &temp_bottom, &temp_top, x, y, page, NULL, 0);", " /*\n * Get height...\n */", " if ((height_var = htmlGetVariable(cells[row][0]->parent, (uchar *)\"HEIGHT\")) == NULL)\n\tfor (col = 0; col < table.num_cols; col ++)\n\t if (htmlGetVariable(cells[row][col], (uchar *)\"ROWSPAN\") == NULL)\n\t if ((height_var = htmlGetVariable(cells[row][col], (uchar *)\"HEIGHT\")) != NULL)\n\t break;\n }", " if (height_var != NULL && row == header_row)\n header_height_var = height_var;", " if (cells[row][0] != NULL && height_var != NULL)\n {\n // Row height specified; make sure it'll fit...\n if (height_var[strlen((char *)height_var) - 1] == '%')\n\ttemp_height = (float)(atof((char *)height_var) * 0.01f * (PagePrintLength - 2 * table.cellpadding));\n else\n temp_height = (float)(atof((char *)height_var) * PagePrintWidth / _htmlBrowserWidth);", " if (table.height > 0.0f && temp_height > table.height)\n temp_height = table.height;", " temp_height -= 2 * table.cellpadding;\n }\n else\n {\n // Use min height computed from get_cell_size()...\n for (col = 0, temp_height = (float)_htmlSpacings[SIZE_P];\n col < table.num_cols;\n\t col ++)\n if (cells[row][col] != NULL &&\n\t cells[row][col]->height > temp_height &&\n\t !htmlGetVariable(cells[row][col], (uchar *)\"ROWSPAN\"))\n\t temp_height = cells[row][col]->height;", " if (table.height > 0.0)\n {\n\t// Table height specified; make sure it'll fit...\n\tif (temp_height > table.height)\n temp_height = table.height;\n\ttemp_height -= 2 * table.cellpadding;\n }\n else if (temp_height > (PageLength / 8.0) && height_var == NULL)\n\ttemp_height = PageLength / 8.0;\n }", " DEBUG_printf((\"BEFORE row = %d, temp_height = %.1f, *y = %.1f, *page = %d\\n\",\n row, temp_height, *y, *page));", " if (*y < (bottom + 2 * table.cellpadding + temp_height) &&\n temp_height <= (top - bottom - 2 * table.cellpadding))\n {\n DEBUG_puts(\"NEW PAGE\");", " *y = top - header_height;\n (*page) ++;", " if (Verbosity)\n progress_show(\"Formatting page %d\", *page);", " if (row > 0 && header_row >= 0)\n {\n // Render header row...\n render_table_row(table, cells, header_row, header_height_var, left, right, bottom, top, x, y, page);\n }\n }", " float start_y = *y;\n temp_page = *page;\n render_table_row(table, cells, row, height_var, left, right, bottom, top, x, y, page);\n if (header_row >= 0 && row == header_row)\n {\n header_height = *y - start_y;\n top += header_height;\n }\n else if (temp_page != *page && header_row >= 0)\n {\n // Render header row on new page(s)...\n do\n {\n float temp_y = top - header_height;", " temp_page ++;\n render_table_row(table, cells, header_row, header_height_var, left, right, bottom, top, x, &temp_y, &temp_page);\n }\n while (temp_page < *page);\n }", " if (row < (table.num_rows - 1))\n (*y) -= cellspacing;", " DEBUG_printf((\"END row = %d, *y = %.1f, *page = %d\\n\", row, *y, *page));\n }", " top -= header_height;", " /*\n * Handle table background color...\n */", " if ((bgcolor = htmlGetVariable(t, (uchar *)\"BGCOLOR\")) != NULL)\n {\n memcpy(bgrgb, background_color, sizeof(bgrgb));", " get_color(bgcolor, bgrgb, 0);", " table.border_left = table.col_lefts[0] - table.cellpadding;\n width = table.col_rights[table.num_cols - 1] - table.col_lefts[0] + 2 * table.cellpadding;", " if (table_page != *page)\n {\n // Draw background on multiple pages...", " // Bottom of first page...\n new_render(table_page, RENDER_BOX, table.border_left, bottom,\n\t width, table_y - bottom, bgrgb,\n\t\t pages[table_page].start);", " // Intervening pages...\n for (temp_page = table_page + 1; temp_page < *page; temp_page ++)\n {\n new_render(temp_page, RENDER_BOX, table.border_left, bottom,\n width, top - bottom, bgrgb, pages[temp_page].start);\n }", " // Top of last page...\n check_pages(*page);", " new_render(*page, RENDER_BOX, table.border_left, *y,\n\t width, top - *y, bgrgb, pages[*page].start);\n }\n else\n {\n // Draw background in row...\n new_render(table_page, RENDER_BOX, table.border_left, *y,\n\t width, table_y - *y, bgrgb, pages[table_page].start);\n }\n }", " *x = left;", " if (caption)\n {\n /*\n * Show caption at bottom...\n */", " parse_paragraph(caption, left, right, bottom, top, x, y, page, needspace);\n needspace = 1;\n }", " /*\n * Free memory for the table...\n */", " if (table.num_rows > 0)\n {\n for (row = 0; row < table.num_rows; row ++)\n free(cells[row]);", " free(cells);\n }\n}\n#ifdef TABLE_DEBUG\n# undef DEBUG\n# undef DEBUG_puts\n# define DEBUG_puts(x)\n# undef DEBUG_printf\n# define DEBUG_printf(x)\n#endif /* TABLE_DEBUG */", "\n/*\n * 'parse_list()' - Parse a list entry and produce rendering output.\n */", "static void\nparse_list(tree_t *t,\t\t/* I - Tree to parse */\n float *left,\t/* I - Left margin */\n float *right,\t/* I - Printable width */\n float *bottom,\t/* I - Bottom margin */\n float *top,\t\t/* I - Printable top */\n float *x,\t\t/* IO - X position */\n float *y,\t\t/* IO - Y position */\n int *page,\t/* IO - Page # */\n int needspace)\t/* I - Need whitespace? */\n{\n uchar\t\tnumber[255];\t/* List number (for numbered types) */\n uchar\t\t*value;\t\t/* VALUE= variable */\n int\t\ttypeface;\t/* Typeface of list number */\n float\t\twidth;\t\t/* Width of list number */\n render_t\t*r;\t\t/* Render primitive */\n int\t\toldpage;\t/* Old page value */\n float\t\toldy;\t\t/* Old Y value */\n float\t\ttempx;\t\t/* Temporary X value */", "\n DEBUG_printf((\"parse_list(t=%p, left=%.1f, right=%.1f, x=%.1f, y=%.1f, page=%d\\n\",\n (void *)t, *left, *right, *x, *y, *page));", " if (needspace && *y < *top)\n {\n *y -= _htmlSpacings[t->size];\n needspace = 0;\n }", " check_pages(*page);", " oldy = *y;\n oldpage = *page;\n r = pages[*page].end;\n tempx = *x;", " if (t->indent == 0)\n {\n // Adjust left margin when no UL/OL/DL is being used...\n *left += _htmlSizes[t->size];\n tempx += _htmlSizes[t->size];\n }", " parse_doc(t->child, left, right, bottom, top, &tempx, y, page, NULL,\n &needspace);", " // Handle when paragraph wrapped to new page...\n if (*page != oldpage)\n {\n // First see if anything was added to the old page...\n if ((r != NULL && r->next == NULL) || pages[oldpage].end == NULL)\n {\n // No, put the symbol on the next page...\n oldpage = *page;\n oldy = *top;\n }\n }", " if ((value = htmlGetVariable(t, (uchar *)\"VALUE\")) != NULL)\n {\n if (isdigit(value[0]))\n list_values[t->indent] = atoi((char *)value);\n else if (isupper(value[0]))\n list_values[t->indent] = value[0] - 'A' + 1;\n else\n list_values[t->indent] = value[0] - 'a' + 1;\n }", " switch (list_types[t->indent])\n {\n case 'a' :\n case 'A' :\n case '1' :\n case 'i' :\n case 'I' :\n strlcpy((char *)number, format_number(list_values[t->indent], (char)list_types[t->indent]), sizeof(number));\n strlcat((char *)number, \". \", sizeof(number));\n typeface = t->typeface;\n break;", " default :\n snprintf((char *)number, sizeof(number), \"%c \", list_types[t->indent]);\n typeface = TYPE_SYMBOL;\n break;\n }", " width = get_width(number, typeface, t->style, t->size);", " r = new_render(oldpage, RENDER_TEXT, *left - width, oldy - _htmlSizes[t->size],\n width, _htmlSpacings[t->size], number);\n r->data.text.typeface = typeface;\n r->data.text.style = t->style;\n r->data.text.size = (float)_htmlSizes[t->size];\n r->data.text.rgb[0] = t->red / 255.0f;\n r->data.text.rgb[1] = t->green / 255.0f;\n r->data.text.rgb[2] = t->blue / 255.0f;", " list_values[t->indent] ++;", " if (t->indent == 0)\n {\n // Adjust left margin when no UL/OL/DL is being used...\n *left -= _htmlSizes[t->size];\n }\n}", "\n/*\n * 'init_list()' - Initialize the list type and value as necessary.\n */", "static void\ninit_list(tree_t *t)\t\t/* I - List entry */\n{\n uchar\t\t*type,\t\t/* TYPE= variable */\n\t\t*value;\t\t/* VALUE= variable */\n static uchar\t*symbols = (uchar *)\"\\327\\267\\250\\340\";", "\n if ((type = htmlGetVariable(t, (uchar *)\"TYPE\")) != NULL)\n {\n if (strlen((char *)type) == 1)\n list_types[t->indent] = type[0];\n else if (strcasecmp((char *)type, \"disc\") == 0 ||\n strcasecmp((char *)type, \"circle\") == 0)\n list_types[t->indent] = symbols[1];\n else\n list_types[t->indent] = symbols[2];\n }\n else if (t->markup == MARKUP_UL)\n list_types[t->indent] = symbols[t->indent & 3];\n else if (t->markup == MARKUP_OL)\n list_types[t->indent] = '1';", " if ((value = htmlGetVariable(t, (uchar *)\"VALUE\")) == NULL)\n value = htmlGetVariable(t, (uchar *)\"START\");", " if (value != NULL)\n {\n if (isdigit(value[0]))\n list_values[t->indent] = atoi((char *)value);\n else if (isupper(value[0]))\n list_values[t->indent] = value[0] - 'A' + 1;\n else\n list_values[t->indent] = value[0] - 'a' + 1;\n }\n else if (t->markup == MARKUP_OL)\n list_values[t->indent] = 1;\n}", "\n/*\n * 'parse_comment()' - Parse a comment for HTMLDOC comments.\n */", "#ifdef COMMENT_DEBUG\n# undef DEBUG_puts\n# define DEBUG_puts(x) puts(x)\n# define DEBUG\n# undef DEBUG_printf\n# define DEBUG_printf(x) printf x\n#endif /* COMMENT_DEBUG */", "static void\nparse_comment(tree_t *t,\t/* I - Tree to parse */\n float *left,\t/* I - Left margin */\n float *right,\t/* I - Printable width */\n float *bottom,\t/* I - Bottom margin */\n float *top,\t/* I - Printable top */\n float *x,\t/* IO - X position */\n float *y,\t/* IO - Y position */\n int *page,\t/* IO - Page # */\n\t tree_t *para,\t/* I - Current paragraph */\n\t int needspace)\t/* I - Need whitespace? */\n{\n int\t\ti;\t\t/* Looping var */\n const char\t*comment;\t/* Comment text */\n char\t\t*ptr,\t\t/* Pointer into value string */\n\t\tbuffer[1024];\t/* Buffer for strings */\n int\t\tpos,\t\t/* Position (left, center, right) */\n\t\ttof;\t\t/* Top of form */", "\n DEBUG_printf((\"parse_comment(t=%p, left=%.1f, right=%.1f, bottom=%.1f, \"\n \"top=%.1f, x=%.1f, y=%.1f, page=%d, para=%p, needspace=%d\\n\",\n (void *)t, *left, *right, *bottom, *top, *x, *y, *page, (void *)para,\n\t\tneedspace));", " if (t->data == NULL)\n return;", " if (para != NULL && para->child != NULL && para->child->next == NULL &&\n para->child->child == NULL && para->child->markup == MARKUP_NONE &&\n strcmp((const char *)para->child->data, \" \") == 0)\n {\n // Remove paragraph consisting solely of whitespace...\n htmlDeleteTree(para->child);\n para->child = para->last_child = NULL;\n }", " // Mark if we are at the top of form...\n tof = (*y >= *top);", " DEBUG_printf((\"BEFORE tof=%d, *y=%.1f, *top=%.1f, *page=%d, t->data=\\\"%s\\\"\\n\",\n \ttof, *y, *top, *page, t->data));\n DEBUG_printf((\" PagePrintWidth = %d\\n\", PagePrintWidth));\n DEBUG_printf((\"PagePrintLength = %d\\n\", PagePrintLength));\n DEBUG_printf((\" PageWidth = %d\\n\", PageWidth));\n DEBUG_printf((\" PageLength = %d\\n\", PageLength));\n DEBUG_printf((\" PageLeft = %d\\n\", PageLeft));\n DEBUG_printf((\" PageBottom = %d\\n\", PageBottom));\n DEBUG_printf((\" PageRight = %d\\n\", PageRight));\n DEBUG_printf((\" PageTop = %d\\n\", PageTop));\n DEBUG_printf((\" Landscape = %d\\n\", Landscape));", "\n for (comment = (const char *)t->data; *comment;)\n {\n // Skip leading whitespace...\n while (isspace(*comment))\n comment ++;", " if (!*comment)\n break;", " if (strncasecmp(comment, \"PAGE BREAK\", 10) == 0 &&\n\t(!comment[10] || isspace(comment[10])))\n {\n /*\n * <!-- PAGE BREAK --> generates a page break...\n */", " comment += 10;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;\n }", " (*page) ++;\n if (Verbosity)\n\tprogress_show(\"Formatting page %d\", *page);\n *x = *left;\n *y = *top;", " tof = 1;\n }\n else if (strncasecmp(comment, \"NEW PAGE\", 8) == 0 &&\n\t (!comment[8] || isspace(comment[8])))\n {\n /*\n * <!-- NEW PAGE --> generates a page break...\n */", " comment += 8;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;\n }", " (*page) ++;\n if (Verbosity)\n\tprogress_show(\"Formatting page %d\", *page);\n *x = *left;\n *y = *top;", " tof = 1;\n }\n else if (strncasecmp(comment, \"NEW SHEET\", 9) == 0 &&\n\t (!comment[9] || isspace(comment[9])))\n {\n /*\n * <!-- NEW SHEET --> generate a page break to a new sheet...\n */", " comment += 9;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;\n }", " if (NumberUp == 1)\n {\n // NEW SHEET breaks to the next sheet of paper...\n (*page) ++;", "\tif (PageDuplex && ((*page) & 1))\n\t (*page) ++;\n }\n else\n {\n // NEW SHEET breaks to the next side/sheet...\n (*page) ++;", "\tfor (i = *page - 1; i >= 0; i --)\n\t if (pages[i].nup != NumberUp)\n\t break;", " i ++;\n\tfor (i = *page - i; (i % NumberUp) != 0; i ++, (*page) ++);\n }", " if (Verbosity)\n\tprogress_show(\"Formatting page %d\", *page);", " *x = *left;\n *y = *top;", " tof = 1;\n }\n else if (strncasecmp(comment, \"HALF PAGE\", 9) == 0 &&\n (!comment[9] || isspace(comment[9])))\n {\n /*\n * <!-- HALF PAGE --> Go to the next half page. If in the\n * top half of a page, go to the bottom half. If in the\n * bottom half, go to the next page.\n */\n float halfway;", "\n comment += 9;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;\n }", " halfway = 0.5f * (*top + *bottom);", " if (*y <= halfway)\n {\n\t(*page) ++;\n\tif (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n\t*x = *left;\n\t*y = *top;", " tof = 1;\n }\n else\n {\n\t*x = *left;\n\t*y = halfway;", " tof = 0;\n }\n }\n else if (strncasecmp(comment, \"NEED \", 5) == 0)\n {\n /*\n * <!-- NEED amount --> generate a page break if there isn't\n * enough remaining space...\n */", " comment += 5;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if ((*y - get_measurement(comment, (float)_htmlSpacings[SIZE_P])) < *bottom)\n {\n\t(*page) ++;", "\tif (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n\t*y = *top;\n tof = 1;\n }", " *x = *left;", " // Skip amount...\n while (*comment && !isspace(*comment))\n comment ++;\n }\n else if (strncasecmp(comment, \"MEDIA COLOR \", 12) == 0)\n {\n // Media color for page...\n comment += 12;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (!tof)\n {\n\t(*page) ++;", "\tif (PageDuplex && ((*page) & 1))\n\t (*page) ++;", "\tif (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n\t*y = *top;\n tof = 1;\n }", " *x = *left;", " check_pages(*page);", " // Get color...\n if (*comment == '\\\"')\n {\n\tfor (ptr = pages[*page].media_color, comment ++;\n *comment && *comment != '\\\"';\n\t comment ++)\n if (ptr < (pages[*page].media_color +\n\t sizeof(pages[*page].media_color) - 1))\n\t *ptr++ = *comment;", " if (*comment == '\\\"')\n\t comment ++;\n }\n else\n {\n\tfor (ptr = pages[*page].media_color;\n *comment && !isspace(*comment);\n\t comment ++)\n if (ptr < (pages[*page].media_color +\n\t sizeof(pages[*page].media_color) - 1))\n\t *ptr++ = *comment;\n }", " *ptr = '\\0';\n }\n else if (strncasecmp(comment, \"MEDIA POSITION \", 15) == 0)\n {\n // Media position for page...\n comment += 15;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (!tof)\n {\n\t(*page) ++;", "\tif (PageDuplex && ((*page) & 1))\n\t (*page) ++;", "\tif (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n\t*y = *top;\n tof = 1;\n }", " *x = *left;", " check_pages(*page);", " pages[*page].media_position = atoi(comment);", " // Skip position...\n while (*comment && !isspace(*comment))\n comment ++;\n }\n else if (strncasecmp(comment, \"MEDIA TYPE \", 11) == 0)\n {\n // Media type for page...\n comment += 11;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (!tof)\n {\n\t(*page) ++;", "\tif (PageDuplex && ((*page) & 1))\n\t (*page) ++;", "\tif (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n\t*y = *top;\n tof = 1;\n }", " *x = *left;", " check_pages(*page);", " // Get type...\n if (*comment == '\\\"')\n {\n\tfor (ptr = pages[*page].media_type, comment ++;\n *comment && *comment != '\\\"';\n\t comment ++)\n if (ptr < (pages[*page].media_type +\n\t sizeof(pages[*page].media_type) - 1))\n\t *ptr++ = *comment;", " if (*comment == '\\\"')\n\t comment ++;\n }\n else\n {\n\tfor (ptr = pages[*page].media_type;\n *comment && !isspace(*comment);\n\t comment ++)\n if (ptr < (pages[*page].media_type +\n\t sizeof(pages[*page].media_type) - 1))\n\t *ptr++ = *comment;\n }", " *ptr = '\\0';\n }\n else if (strncasecmp(comment, \"MEDIA SIZE \", 11) == 0)\n {\n // Media size...\n comment += 11;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (!tof)\n {\n\t(*page) ++;", " tof = 1;\n }", " if (PageDuplex && ((*page) & 1))\n\t(*page) ++;", " if (Verbosity)\n\tprogress_show(\"Formatting page %d\", *page);", " check_pages(*page);", " *right = PagePrintWidth - *right;\n *top = PagePrintLength - *top;", " set_page_size(comment);", " if (Landscape)\n {\n\tPagePrintWidth = PageLength - PageLeft - PageRight;\n\tPagePrintLength = PageWidth - PageTop - PageBottom;\n }\n else\n {\n\tPagePrintWidth = PageWidth - PageLeft - PageRight;\n\tPagePrintLength = PageLength - PageTop - PageBottom;\n }", " *right = PagePrintWidth - *right;\n *top = PagePrintLength - *top;", " *x = *left;\n *y = *top;", " pages[*page].width = PageWidth;\n pages[*page].length = PageLength;", " // Skip width...\n while (*comment && !isspace(*comment))\n comment ++;\n }\n else if (strncasecmp(comment, \"MEDIA LEFT \", 11) == 0)\n {\n // Left margin...\n comment += 11;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (!tof)\n {\n\t(*page) ++;", "\tif (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n\t*y = *top;\n tof = 1;\n }", " *x = *left;", " check_pages(*page);", " *right = PagePrintWidth - *right;\n PageLeft = pages[*page].left = get_measurement(comment);", " if (Landscape)\n\tPagePrintWidth = PageLength - PageRight - PageLeft;\n else\n\tPagePrintWidth = PageWidth - PageRight - PageLeft;", " *right = PagePrintWidth - *right;", " // Skip left...\n while (*comment && !isspace(*comment))\n comment ++;\n }\n else if (strncasecmp(comment, \"MEDIA RIGHT \", 12) == 0)\n {\n // Right margin...\n comment += 12;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (!tof)\n {\n\t(*page) ++;", "\tif (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n\t*y = *top;\n tof = 1;\n }", " *x = *left;", " check_pages(*page);", " *right = PagePrintWidth - *right;\n PageRight = pages[*page].right = get_measurement(comment);", " if (Landscape)\n\tPagePrintWidth = PageLength - PageRight - PageLeft;\n else\n\tPagePrintWidth = PageWidth - PageRight - PageLeft;", " *right = PagePrintWidth - *right;", " // Skip right...\n while (*comment && !isspace(*comment))\n comment ++;\n }\n else if (strncasecmp(comment, \"MEDIA BOTTOM \", 13) == 0)\n {\n // Bottom margin...\n comment += 13;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (!tof)\n {\n\t(*page) ++;", "\tif (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n tof = 1;\n }", " *x = *left;", " check_pages(*page);", " *top = PagePrintLength - *top;\n PageBottom = pages[*page].bottom = get_measurement(comment);", " if (Landscape)\n PagePrintLength = PageWidth - PageTop - PageBottom;\n else\n PagePrintLength = PageLength - PageTop - PageBottom;", " *top = PagePrintLength - *top;\n *y = *top;", " // Skip bottom...\n while (*comment && !isspace(*comment))\n comment ++;\n }\n else if (strncasecmp(comment, \"MEDIA TOP \", 10) == 0)\n {\n // Top margin...\n comment += 10;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (!tof)\n {\n\t(*page) ++;", "\tif (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);", " tof = 1;\n }", " *x = *left;", " check_pages(*page);", " *top = PagePrintLength - *top;\n PageTop = pages[*page].top = get_measurement(comment);", " if (Landscape)\n PagePrintLength = PageWidth - PageTop - PageBottom;\n else\n PagePrintLength = PageLength - PageTop - PageBottom;", " *top = PagePrintLength - *top;\n *y = *top;", " // Skip top...\n while (*comment && !isspace(*comment))\n comment ++;\n }\n else if (strncasecmp(comment, \"MEDIA LANDSCAPE \", 16) == 0)\n {\n // Landscape on/off...\n comment += 16;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (!tof)\n {\n\t(*page) ++;", " tof = 1;\n }", " if (PageDuplex && ((*page) & 1))\n\t(*page) ++;", " if (Verbosity)\n\tprogress_show(\"Formatting page %d\", *page);", " *x = *left;", " check_pages(*page);", " if (strncasecmp(comment, \"OFF\", 3) == 0 || tolower(comment[0]) == 'n')\n {\n if (Landscape)\n\t{\n\t *right = PageLength - PageRight - *right;\n\t PagePrintWidth = PageWidth - PageRight - PageLeft;\n\t *right = PageWidth - PageRight - *right;", "\t *top = PageWidth - PageTop - *top;\n\t PagePrintLength = PageLength - PageTop - PageBottom;\n\t *top = PageLength - PageTop - *top;\n }", " Landscape = pages[*page].landscape = 0;\n }\n else if (strncasecmp(comment, \"ON\", 2) == 0 || tolower(comment[0]) == 'y')\n {\n if (!Landscape)\n\t{\n\t *top = PageLength - PageTop - *top;\n\t PagePrintLength = PageWidth - PageTop - PageBottom;\n\t *top = PageWidth - PageTop - *top;", "\t *right = PageWidth - PageRight - *right;\n\t PagePrintWidth = PageLength - PageRight - PageLeft;\n\t *right = PageLength - PageRight - *right;\n }", " Landscape = pages[*page].landscape = 1;\n }", " *y = *top;", " // Skip landscape...\n while (*comment && !isspace(*comment))\n comment ++;\n }\n else if (strncasecmp(comment, \"MEDIA DUPLEX \", 13) == 0)\n {\n // Duplex printing on/off...\n comment += 13;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (!tof)\n {\n\t(*page) ++;", "\t*y = *top;\n tof = 1;\n }", " if (PageDuplex && ((*page) & 1))\n\t(*page) ++;", " if (Verbosity)\n\tprogress_show(\"Formatting page %d\", *page);", " *x = *left;", " check_pages(*page);", " if (strncasecmp(comment, \"OFF\", 3) == 0 || tolower(comment[0]) == 'n')\n PageDuplex = pages[*page].duplex = 0;\n else if (strncasecmp(comment, \"ON\", 2) == 0 || tolower(comment[0]) == 'y')\n {\n\tif ((*page) & 1)\n\t{\n\t (*page) ++;", " check_pages(*page);", "\t if (Verbosity)\n\t progress_show(\"Formatting page %d\", *page);\n\t}", " PageDuplex = pages[*page].duplex = 1;\n }", " // Skip duplex...\n while (*comment && !isspace(*comment))\n comment ++;\n }\n else if (strncasecmp(comment, \"HEADER \", 7) == 0)\n {\n // Header string...\n comment += 7;", " while (isspace(*comment))\n\tcomment ++;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (strncasecmp(comment, \"LEFT\", 4) == 0 && isspace(comment[4]))\n {\n pos = 0;\n\tcomment += 4;\n }\n else if (strncasecmp(comment, \"CENTER\", 6) == 0 && isspace(comment[6]))\n {\n pos = 1;\n\tcomment += 6;\n }\n else if (strncasecmp(comment, \"RIGHT\", 5) == 0 && isspace(comment[5]))\n {\n pos = 2;\n\tcomment += 5;\n }\n else\n {\n progress_error(HD_ERROR_BAD_COMMENT,\n \"Bad HEADER position: \\\"%s\\\"\", comment);\n\treturn;\n }", " while (isspace(*comment))\n\tcomment ++;", " if (*comment != '\\\"')\n {\n progress_error(HD_ERROR_BAD_COMMENT,\n \"Bad HEADER string: \\\"%s\\\"\", comment);\n\treturn;\n }", " for (ptr = buffer, comment ++; *comment && *comment != '\\\"'; comment ++)\n {\n if (*comment == '\\\\')\n\t comment ++;", "\tif (ptr < (buffer + sizeof(buffer) - 1))\n\t *ptr++ = *comment;\n }", " if (*comment == '\\\"')\n comment ++;", " *ptr = '\\0';", " if (ptr > buffer)\n Header[pos] = strdup(buffer);\n else\n Header[pos] = NULL;", " if (tof)\n {\n DEBUG_printf((\"Setting header %d for page %d to \\\"%s\\\"...\\n\",\n\t pos, *page, Header[pos] ? Header[pos] : \"(null)\"));", "\tcheck_pages(*page);", "\tpages[*page].header[pos] = (uchar *)Header[pos];\n }", " // Adjust top margin as needed...\n float adjust, image_adjust, temp_adjust;", " if (maxhfheight > HeadFootSize)\n\timage_adjust = (float)(maxhfheight + HeadFootSize);\n else\n\timage_adjust = (float)(2 * HeadFootSize);", " for (adjust = 0.0, pos = 0; pos < 3; pos ++)\n {\n\tif (Header[pos] &&\n\t (strstr(Header[pos], \"$IMAGE\") != NULL ||\n\t strstr(Header[pos], \"$HFIMAGE\") != NULL))\n\t temp_adjust = image_adjust;\n\telse if (Header1[pos] &&\n\t\t (strstr(Header1[pos], \"$IMAGE\") != NULL ||\n\t\t strstr(Header1[pos], \"$HFIMAGE\") != NULL))\n\t temp_adjust = image_adjust;\n\telse if (Header[pos] || Header1[pos])\n\t temp_adjust = (float)(2 * HeadFootSize);\n\telse\n\t temp_adjust = 0.0;", "\tif (temp_adjust > adjust)\n\t adjust = temp_adjust;\n }", " *top = PagePrintLength - adjust;", " if (tof)\n *y = *top;\n }\n else if (strncasecmp(comment, \"HEADER1 \", 8) == 0)\n {\n // First page header string...\n comment += 8;", " while (isspace(*comment))\n\tcomment ++;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (strncasecmp(comment, \"LEFT\", 4) == 0 && isspace(comment[4]))\n {\n pos = 0;\n\tcomment += 4;\n }\n else if (strncasecmp(comment, \"CENTER\", 6) == 0 && isspace(comment[6]))\n {\n pos = 1;\n\tcomment += 6;\n }\n else if (strncasecmp(comment, \"RIGHT\", 5) == 0 && isspace(comment[5]))\n {\n pos = 2;\n\tcomment += 5;\n }\n else\n {\n progress_error(HD_ERROR_BAD_COMMENT,\n \"Bad HEADER1 position: \\\"%s\\\"\", comment);\n\treturn;\n }", " while (isspace(*comment))\n\tcomment ++;", " if (*comment != '\\\"')\n {\n progress_error(HD_ERROR_BAD_COMMENT,\n \"Bad HEADER1 string: \\\"%s\\\"\", comment);\n\treturn;\n }", " for (ptr = buffer, comment ++; *comment && *comment != '\\\"'; comment ++)\n {\n if (*comment == '\\\\')\n\t comment ++;", "\tif (ptr < (buffer + sizeof(buffer) - 1))\n\t *ptr++ = *comment;\n }", " if (*comment == '\\\"')\n comment ++;", " *ptr = '\\0';", " if (ptr > buffer)\n Header1[pos] = strdup(buffer);\n else\n Header1[pos] = NULL;", " // Adjust top margin as needed...\n float adjust, image_adjust, temp_adjust;", " if (maxhfheight > HeadFootSize)\n\timage_adjust = (float)(maxhfheight + HeadFootSize);\n else\n\timage_adjust = (float)(2 * HeadFootSize);", " for (adjust = 0.0, pos = 0; pos < 3; pos ++)\n {\n\tif (Header[pos] &&\n\t (strstr(Header[pos], \"$IMAGE\") != NULL ||\n\t strstr(Header[pos], \"$HFIMAGE\") != NULL))\n\t temp_adjust = image_adjust;\n\telse if (Header1[pos] &&\n\t\t (strstr(Header1[pos], \"$IMAGE\") != NULL ||\n\t\t strstr(Header1[pos], \"$HFIMAGE\") != NULL))\n\t temp_adjust = image_adjust;\n\telse if (Header[pos] || Header1[pos])\n\t temp_adjust = (float)(2 * HeadFootSize);\n\telse\n\t temp_adjust = 0.0;", "\tif (temp_adjust > adjust)\n\t adjust = temp_adjust;\n }", " *top = PagePrintLength - adjust;", " if (tof)\n *y = *top;\n }\n else if (strncasecmp(comment, \"FOOTER \", 7) == 0)\n {\n // Footer string...\n comment += 7;", " while (isspace(*comment))\n\tcomment ++;", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (strncasecmp(comment, \"LEFT\", 4) == 0 && isspace(comment[4]))\n {\n pos = 0;\n\tcomment += 4;\n }\n else if (strncasecmp(comment, \"CENTER\", 6) == 0 && isspace(comment[6]))\n {\n pos = 1;\n\tcomment += 6;\n }\n else if (strncasecmp(comment, \"RIGHT\", 5) == 0 && isspace(comment[5]))\n {\n pos = 2;\n\tcomment += 5;\n }\n else\n {\n progress_error(HD_ERROR_BAD_COMMENT,\n \"Bad FOOTER position: \\\"%s\\\"\", comment);\n\treturn;\n }", " while (isspace(*comment))\n\tcomment ++;", " if (*comment != '\\\"')\n {\n progress_error(HD_ERROR_BAD_COMMENT,\n \"Bad FOOTER string: \\\"%s\\\"\", comment);\n\treturn;\n }", " for (ptr = buffer, comment ++; *comment && *comment != '\\\"'; comment ++)\n {\n if (*comment == '\\\\')\n\t comment ++;", "\tif (ptr < (buffer + sizeof(buffer) - 1))\n\t *ptr++ = *comment;\n }", " if (*comment == '\\\"')\n comment ++;", " *ptr = '\\0';", " if (ptr > buffer)\n Footer[pos] = strdup(buffer);\n else\n Footer[pos] = NULL;", " if (tof)\n {\n\tcheck_pages(*page);", "\tpages[*page].footer[pos] = (uchar *)Footer[pos];\n }", " // Adjust bottom margin as needed...\n float adjust, image_adjust, temp_adjust;", " if (maxhfheight > HeadFootSize)\n\timage_adjust = (float)(maxhfheight + HeadFootSize);\n else\n\timage_adjust = (float)(2 * HeadFootSize);", " for (adjust = 0.0, pos = 0; pos < 3; pos ++)\n {\n\tif (Footer[pos] &&\n\t (strstr(Footer[pos], \"$IMAGE\") != NULL ||\n\t strstr(Footer[pos], \"$HFIMAGE\") != NULL))\n\t temp_adjust = image_adjust;\n\telse if (Footer[pos])\n\t temp_adjust = (float)(2 * HeadFootSize);\n\telse\n\t temp_adjust = 0.0;", "\tif (temp_adjust > adjust)\n\t adjust = temp_adjust;\n }", " *bottom = adjust;\n }\n else if (strncasecmp(comment, \"NUMBER-UP \", 10) == 0)\n {\n // N-up printing...\n comment += 10;", " while (isspace(*comment))\n\tcomment ++;", " if (!*comment)\n\tbreak;", " NumberUp = strtol(comment, (char **)&comment, 10);", " if (para != NULL && para->child != NULL)\n {\n\tparse_paragraph(para, *left, *right, *bottom, *top, x, y, page, needspace);\n\thtmlDeleteTree(para->child);\n\tpara->child = para->last_child = NULL;", "\t// Mark if we are still at the top of form...\n\ttof = (*y >= *top);\n }", " if (tof)\n {\n\tcheck_pages(*page);", " pages[*page].nup = NumberUp;\n }\n }\n else\n break;\n }", " DEBUG_printf((\"LEAVING parse_comment() x=%.1f, y=%.1f, page=%d\\n\",\n *x, *y, *page));\n DEBUG_printf((\" PagePrintWidth = %d\\n\", PagePrintWidth));\n DEBUG_printf((\"PagePrintLength = %d\\n\", PagePrintLength));\n DEBUG_printf((\" PageWidth = %d\\n\", PageWidth));\n DEBUG_printf((\" PageLength = %d\\n\", PageLength));\n DEBUG_printf((\" PageLeft = %d\\n\", PageLeft));\n DEBUG_printf((\" PageBottom = %d\\n\", PageBottom));\n DEBUG_printf((\" PageRight = %d\\n\", PageRight));\n DEBUG_printf((\" PageTop = %d\\n\", PageTop));\n DEBUG_printf((\" Landscape = %d\\n\", Landscape));\n}", "#ifdef COMMENT_DEBUG\n# undef DEBUG\n# undef DEBUG_puts\n# define DEBUG_puts(x)\n# undef DEBUG_printf\n# define DEBUG_printf(x)\n#endif /* COMMENT_DEBUG */", "\n/*\n * 'find_background()' - Find the background image/color for the given document.\n */", "static void\nfind_background(tree_t *t)\t/* I - Document to search */\n{\n uchar\t\t*var;\t\t/* BGCOLOR/BACKGROUND variable */", "\n /*\n * First see if the --bodycolor or --bodyimage options have been\n * specified...\n */", " if (BodyImage[0] != '\\0')\n {\n background_image = image_load(BodyImage, !OutputColor);\n return;\n }\n else if (BodyColor[0] != '\\0')\n {\n get_color((uchar *)BodyColor, background_color, 0);\n return;\n }", " /*\n * If not, search the document tree...\n */", " while (t != NULL && background_image == NULL &&\n background_color[0] == 1.0 && background_color[1] == 1.0 &&\n\t background_color[2] == 1.0)\n {\n if (t->markup == MARKUP_BODY)\n {\n if ((var = htmlGetVariable(t, (uchar *)\"BACKGROUND\")) != NULL)\n background_image = image_load((char *)var, !OutputColor);", " if ((var = htmlGetVariable(t, (uchar *)\"BGCOLOR\")) != NULL)\n get_color(var, background_color, 0);\n }", " if (t->child != NULL)\n find_background(t->child);", " t = t->next;\n }\n}", "\n/*\n * 'write_background()' - Write the background image/color for to the current\n * page.\n */", "static void\nwrite_background(int page,\t/* I - Page we are writing for */\n FILE *out)\t/* I - File to write to */\n{\n float\tx, y;\n float\twidth, height;\n int\tpage_width, page_length;", "\n if (Landscape)\n {\n page_length = pages[page].width;\n page_width = pages[page].length;\n }\n else\n {\n page_width = pages[page].width;\n page_length = pages[page].length;\n }", " if (background_color[0] != 1.0 ||\n background_color[1] != 1.0 ||\n background_color[2] != 1.0)\n {\n if (PSLevel > 0)\n {\n render_x = -1.0;\n render_y = -1.0;\n set_color(out, background_color);\n fprintf(out, \"0 0 M %d %d F\\n\", page_width, page_length);\n }\n else\n {\n set_color(out, background_color);\n flate_printf(out, \"0 0 %d %d re f\\n\", page_width, page_length);\n }\n }", " if (background_image != NULL)\n {\n width = (float)(background_image->width * 72.0f / _htmlPPI);\n height = (float)(background_image->height * 72.0f / _htmlPPI);", " if (width < 1.0f)\n width = 1.0f;\n if (height < 1.0f)\n height = 1.0f;", " switch (PSLevel)\n {\n case 0 :\n for (x = 0.0; x < page_width; x += width)\n for (y = page_length; y >= 0.0f;)\n {\n\t y -= height;\n \t flate_printf(out, \"q %.1f 0 0 %.1f %.1f %.1f cm\", width, height, x, y);\n flate_printf(out, \"/I%d Do\\n\", background_image->obj);\n\t flate_puts(\"Q\\n\", out);\n }\n\t break;", " default :\n fprintf(out, \"0 %.1f %d{/y exch neg %d add def\\n\",\n\t height, page_length + (int)height - 1, page_length);\n\t fprintf(out, \"0 %.1f %d{/x exch def\\n\",\n\t width, page_width);\n fprintf(out, \"GS[%.1f 0 0 %.1f x y]CM/iy -1 def\\n\", width, height);\n\t fprintf(out, \"%d %d 8[%d 0 0 %d 0 %d]\",\n\t background_image->width, background_image->height,\n background_image->width, -background_image->height,\n\t\t background_image->height);\n fputs(\"{/iy iy 1 add def BG iy get}\", out);\n\t if (background_image->depth == 1)\n\t fputs(\"image\\n\", out);\n\t else\n\t fputs(\"false 3 colorimage\\n\", out);\n\t fputs(\"GR}for}for\\n\", out);\n break;\n }\n }\n}", "\n/*\n * 'new_render()' - Allocate memory for a new rendering structure.\n */", "static render_t *\t\t\t/* O - New render structure */\nnew_render(int page,\t\t/* I - Page number (0-n) */\n int type,\t\t/* I - Type of render primitive */\n double x,\t\t\t/* I - Horizontal position */\n double y,\t\t\t/* I - Vertical position */\n double width,\t\t/* I - Width */\n double height,\t\t/* I - Height */\n void *data,\t\t/* I - Data */\n\t render_t *insert)\t\t/* I - Insert before here... */\n{\n render_t\t\t*r;\t\t/* New render primitive */\n size_t\t\tdatalen = 0;\t/* Length of data */\n static render_t\tdummy;\t\t/* Dummy var for errors... */", "\n DEBUG_printf((\"new_render(page=%d, type=%d, x=%.1f, y=%.1f, width=%.1f, height=%.1f, data=%p, insert=%p)\\n\",\n page, type, x, y, width, height, (void *)data, (void *)insert));", " check_pages(page);", " if (page < 0 || page >= (int)alloc_pages)\n {\n progress_error(HD_ERROR_INTERNAL_ERROR,\n \"Page number (%d) out of range (1...%d)\\n\", page + 1,\n (int)alloc_pages);\n memset(&dummy, 0, sizeof(dummy));\n return (&dummy);\n }", " if ((type != RENDER_TEXT && type != RENDER_LINK) || data == NULL)\n r = (render_t *)calloc(sizeof(render_t), 1);\n else\n {\n datalen = strlen((char *)data);\n r = (render_t *)calloc(sizeof(render_t) + datalen, 1);\n }", " if (r == NULL)\n {\n progress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory on page %d\\n\", (int)page + 1);\n memset(&dummy, 0, sizeof(dummy));\n return (&dummy);\n }", " r->type = type;\n r->x = (float)x;\n r->y = (float)y;\n r->width = (float)width;\n r->height = (float)height;", " switch (type)\n {\n case RENDER_TEXT :\n if (data == NULL)\n {\n free(r);\n return (NULL);\n }\n\t// Safe because buffer is allocated...\n memcpy((char *)r->data.text.buffer, (char *)data, datalen);\n get_color(_htmlTextColor, r->data.text.rgb);\n break;\n case RENDER_IMAGE :\n if (data == NULL)\n {\n free(r);\n return (NULL);\n }\n r->data.image = (image_t *)data;\n break;\n case RENDER_BOX :\n memcpy(r->data.box, data, sizeof(r->data.box));\n break;\n case RENDER_LINK :\n if (data == NULL)\n {\n free(r);\n return (NULL);\n }\n\t// Safe because buffer is allocated...\n memcpy((char *)r->data.link, (char *)data, datalen);\n break;\n }", " if (insert)\n {\n if (insert->prev)\n insert->prev->next = r;\n else\n pages[page].start = r;", " r->prev = insert->prev;\n r->next = insert;\n insert->prev = r;\n }\n else\n {\n if (pages[page].end != NULL)\n pages[page].end->next = r;\n else\n pages[page].start = r;", " r->next = NULL;\n r->prev = pages[page].end;\n pages[page].end = r;\n }", " DEBUG_printf((\" returning r = %p\\n\", (void *)r));", " return (r);\n}", "\n/*\n * 'check_pages()' - Allocate memory for more pages as needed...\n */", "static void\ncheck_pages(int page)\t// I - Current page\n{\n page_t\t*temp;\t// Temporary page pointer", "\n DEBUG_printf((\"check_pages(%d)\\n\", page));", " // See if we need to allocate memory for the page...\n if (page >= (int)alloc_pages)\n {\n // Yes, allocate enough for ALLOC_PAGES more pages...\n while (page >= (int)alloc_pages)\n alloc_pages += ALLOC_PAGES;", " // Do the pages pointers...\n if (num_pages == 0)\n temp = (page_t *)malloc(sizeof(page_t) * alloc_pages);\n else\n temp = (page_t *)realloc(pages, sizeof(page_t) * alloc_pages);", " if (temp == NULL)\n {\n progress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory for %d pages - %s\",\n\t (int)alloc_pages, strerror(errno));\n alloc_pages -= ALLOC_PAGES;\n return;\n }", " memset(temp + num_pages, 0, (alloc_pages - num_pages) * sizeof(page_t));", " pages = temp;\n }", " // Initialize the page data as needed...\n for (temp = pages + num_pages; (int)num_pages <= page; num_pages ++, temp ++)\n {\n if (!temp->width)\n {\n if (num_pages == 0 || !temp[-1].width || !temp[-1].length || chapter == 0)\n {\n\ttemp->width = PageWidth;\n\ttemp->length = PageLength;\n\ttemp->left = PageLeft;\n\ttemp->right = PageRight;\n\ttemp->top = PageTop;\n\ttemp->bottom = PageBottom;\n\ttemp->duplex = PageDuplex;\n\ttemp->landscape = Landscape;\n\ttemp->nup = NumberUp;\n }\n else\n {\n\tmemcpy(temp, temp - 1, sizeof(page_t));\n\ttemp->start = NULL;\n\ttemp->end = NULL;\n }", " temp->url = current_url;", " if (chapter == 0)\n {\n\tmemcpy(temp->header, TocHeader, sizeof(temp->header));\n\tmemcpy(temp->footer, TocFooter, sizeof(temp->footer));\n }\n else\n {\n\tmemcpy(temp->header, Header, sizeof(temp->header));\n\tmemcpy(temp->header1, Header1, sizeof(temp->header1));\n\tmemcpy(temp->footer, Footer, sizeof(temp->footer));", " if (current_heading != temp->headnode)\n\t{\n\t temp->heading = htmlGetText(current_heading);\n\t temp->headnode = current_heading;\n\t}\n }", " memcpy(temp->background_color, background_color,\n sizeof(temp->background_color));\n temp->background_image = background_image;\n }\n }\n}", "\n/*\n * 'add_link()' - Add a named link...\n */", "static void\nadd_link(uchar *name,\t\t/* I - Name of link */\n int page,\t\t/* I - Page # */\n int top)\t\t/* I - Y position */\n{\n link_t\t*temp;\t\t/* New name */", "\n if (name == NULL)\n return;", " DEBUG_printf((\"add_link(name=\\\"%s\\\", page=%d, top=%d)\\n\", name, page, top));", " if ((temp = find_link(name)) != NULL)\n {\n temp->page = (short)page;\n temp->top = (short)top;\n }\n else\n {\n // See if we need to allocate memory for links...\n if (num_links >= alloc_links)\n {\n // Allocate more links...\n alloc_links += ALLOC_LINKS;", " if (num_links == 0)\n temp = (link_t *)malloc(sizeof(link_t) * alloc_links);\n else\n temp = (link_t *)realloc(links, sizeof(link_t) * alloc_links);", " if (temp == NULL)\n {\n\tprogress_error(HD_ERROR_OUT_OF_MEMORY,\n \"Unable to allocate memory for %d links - %s\",\n\t (int)alloc_links, strerror(errno));\n alloc_links -= ALLOC_LINKS;\n\treturn;\n }", " links = temp;\n }", " // Add a new link...\n temp = links + num_links;\n num_links ++;", " strlcpy((char *)temp->name, (char *)name, sizeof(temp->name));\n temp->page = (short)page;\n temp->top = (short)top;", " if (num_links > 1)\n qsort(links, num_links, sizeof(link_t),\n (compare_func_t)compare_links);\n }\n}", "\n/*\n * 'find_link()' - Find a named link...\n */", "static link_t *\nfind_link(uchar *name)\t/* I - Name to find */\n{\n link_t\tkey,\t/* Search key */\n\t\t*match;\t/* Matching name entry */", "\n if (name == NULL || num_links == 0)\n return (NULL);", " if (name[0] == '#')\n name ++;", " strlcpy((char *)key.name, (char *)name, sizeof(key.name));\n match = (link_t *)bsearch(&key, links, num_links, sizeof(link_t),\n (compare_func_t)compare_links);", " return (match);\n}", "\n/*\n * 'compare_links()' - Compare two named links.\n */", "static int\t\t\t/* O - 0 = equal, -1 or 1 = not equal */\ncompare_links(link_t *n1,\t/* I - First name */\n link_t *n2)\t/* I - Second name */\n{\n return (strcasecmp((char *)n1->name, (char *)n2->name));\n}", "\n#ifdef TABLE_DEBUG\n# undef DEBUG_printf\n# undef DEBUG_puts\n# define DEBUG_printf(x) printf x\n# define DEBUG_puts(x) puts(x)\n#endif /* TABLE_DEBUG */", "//\n// 'get_cell_size()' - Compute the minimum width of a cell.\n//", "static float\t\t\t\t// O - Required width of cell\nget_cell_size(tree_t *t,\t\t// I - Cell\n float left,\t\t// I - Left margin\n\t float right,\t\t// I - Right margin\n\t float *minwidth,\t\t// O - Minimum width\n\t float *prefwidth,\t// O - Preferred width\n\t float *minheight)\t// O - Minimum height\n{\n tree_t\t*temp,\t\t\t// Current tree entry\n\t\t*next;\t\t\t// Next tree entry\n uchar\t\t*var;\t\t\t// Attribute value\n int\t\tnowrap;\t\t\t// NOWRAP attribute?\n float\t\twidth,\t\t\t// Width of cell\n\t\tfrag_width,\t\t// Fragment required width\n\t\tfrag_height,\t\t// Fragment height\n\t\tfrag_pref,\t\t// Fragment preferred width\n\t\tfrag_min,\t\t// Fragment minimum width\n\t\tminh,\t\t\t// Local minimum height\n\t\tminw,\t\t\t// Local minimum width\n\t\tprefw,\t\t\t// Local preferred width\n\t\tformat_width;\t\t// Working format width for images", "\n DEBUG_printf((\"get_cell_size(%p, %.1f, %.1f, %p, %p, %p)\\n\",\n (void *)t, left, right, (void *)minwidth, (void *)prefwidth, (void *)minheight));", " // First see if the width has been specified for this cell...\n if ((var = htmlGetVariable(t, (uchar *)\"WIDTH\")) != NULL &&\n (var[strlen((char *)var) - 1] != '%' || (right - left) > 0.0f))\n {\n // Yes, use it!\n if (var[strlen((char *)var) - 1] == '%')\n width = (right - left) * atoi((char *)var) * 0.01f;\n else\n width = (float)(atoi((char *)var) * PagePrintWidth / _htmlBrowserWidth);\n }\n else\n width = 0.0f;", " if ((format_width = right - left) <= 0.0f)\n format_width = PagePrintWidth;", " minw = 0.0f;\n prefw = 0.0f;", " // Then the height...\n if ((var = htmlGetVariable(t, (uchar *)\"HEIGHT\")) != NULL)\n {\n // Yes, use it!\n if (var[strlen((char *)var) - 1] == '%')\n minh = PagePrintLength * atoi((char *)var) * 0.01f;\n else\n minh = (float)(atoi((char *)var) * PagePrintWidth / _htmlBrowserWidth);\n }\n else\n minh = 0.0f;", " nowrap = (htmlGetVariable(t, (uchar *)\"NOWRAP\") != NULL);", " DEBUG_printf((\"nowrap = %d\\n\", nowrap));", " for (temp = t->child, frag_width = 0.0f, frag_pref = 0.0f;\n temp != NULL;\n temp = next)\n {\n // Point to next markup, if any...\n next = temp->child;", " switch (temp->markup)\n {\n case MARKUP_TABLE :\n\t // Update widths...\n\t if (frag_pref > prefw)\n\t prefw = frag_pref;", "\t if (frag_width > minw)\n\t {\n\t DEBUG_printf((\"Setting minw to %.1f (was %.1f) for block...\\n\",\n\t \t frag_width, minw));\n\t minw = frag_width;\n\t }", "\t if (nowrap && frag_pref > minw)\n\t {\n\t DEBUG_printf((\"Setting minw to %.1f (was %.1f) for break...\\n\",\n\t \t frag_pref, minw));\n\t minw = frag_pref;\n\t }", " // For nested tables, compute the width of the table.\n frag_width = get_table_size(temp, left, right, &frag_min,\n\t &frag_pref, &frag_height);", "\t if (frag_pref > prefw)\n\t prefw = frag_pref;", "\t if (frag_min > minw)\n\t {\n\t DEBUG_printf((\"Setting minw to %.1f (was %.1f) for nested table...\\n\",\n\t frag_min, minw));\n\t minw = frag_min;\n\t }", "\t frag_width = 0.0f;\n\t frag_pref = 0.0f;\n\t frag_min = 0.0f;\n\t next = NULL;\n\t break;", " case MARKUP_IMG :\n // Update the image width as needed...\n\t if (temp->markup == MARKUP_IMG)\n\t update_image_size(temp);\n case MARKUP_NONE :\n case MARKUP_SPACER :\n frag_height = temp->height;", "#ifdef TABLE_DEBUG2\n if (temp->markup == MARKUP_NONE)\n\t printf(\"FRAG(%s) = %.1f\\n\", temp->data, temp->width);\n\t else if (temp->markup == MARKUP_SPACER)\n\t printf(\"SPACER = %.1f\\n\", temp->width);\n\t else\n\t printf(\"IMG(%s) = %.1f\\n\", htmlGetVariable(temp, (uchar *)\"SRC\"),\n\t temp->width);\n#endif // TABLE_DEBUG2", " // Handle min/preferred widths separately...\n if (temp->width > minw)\n\t {\n\t DEBUG_printf((\"Setting minw to %.1f (was %.1f) for fragment...\\n\",\n\t temp->width, minw));\n\t minw = temp->width;\n\t }", " if (temp->preformatted && temp->data != NULL &&\n temp->data[strlen((char *)temp->data) - 1] == '\\n')\n {\n\t // End of a line - check preferred width...\n\t frag_pref += temp->width + 1;", " if (frag_pref > prefw)\n prefw = frag_pref;", " if (temp->preformatted && frag_pref > minw)\n\t {\n\t DEBUG_printf((\"Setting minw to %.1f (was %.1f) for preformatted...\\n\",\n\t frag_pref, minw));\n minw = frag_pref;\n\t }", "\t frag_pref = 0.0f;\n }\n else if (temp->data != NULL)\n\t frag_pref += temp->width + 1;\n\t else if ((frag_pref + temp->width) > format_width)\n\t {\n\t // parse_paragraph() will force a break\n if (frag_pref > prefw)\n prefw = frag_pref;", "\t frag_pref = temp->width;\n\t }\n\t else\n\t frag_pref += temp->width;", " if (temp->preformatted && temp->data != NULL &&\n temp->data[strlen((char *)temp->data) - 1] == '\\n')\n\t {\n\t // Check required width...\n frag_width += temp->width + 1;", " if (frag_width > minw)\n\t {\n\t DEBUG_printf((\"Setting minw to %.1f (was %.1f) for block...\\n\",\n\t frag_width, minw));\n minw = frag_width;\n\t }", " frag_width = 0.0f;\n\t }\n else if (!temp->preformatted && temp->data != NULL &&\n\t (isspace(temp->data[0]) ||\n\t \t (temp->data[0] && isspace(temp->data[strlen((char *)temp->data) - 1]))))\n\t {\n\t // Check required width...\n\t if (isspace(temp->data[0]))\n\t frag_width = temp->width + 1;\n\t else\n frag_width += temp->width + 1;", " if (frag_width > minw)\n\t {\n\t DEBUG_printf((\"Setting minw to %.1f (was %.1f) for block...\\n\",\n\t frag_width, minw));\n minw = frag_width;\n\t }", "\t if (!isspace(temp->data[0]))\n frag_width = 0.0f;", " DEBUG_printf((\"frag_width=%.1f after whitespace processing...\\n\",\n\t frag_width));\n\t }\n\t else if (temp->data != NULL)\n frag_width += temp->width + 1;\n\t else if ((frag_width + temp->width) > format_width)\n\t // parse_paragraph() will force a break\n\t frag_width = temp->width;\n\t else\n\t frag_width += temp->width;\n\t break;", " case MARKUP_ADDRESS :\n case MARKUP_BLOCKQUOTE :\n case MARKUP_BR :\n case MARKUP_CENTER :\n case MARKUP_DD :\n case MARKUP_DIV :\n case MARKUP_DT :\n case MARKUP_H1 :\n case MARKUP_H2 :\n case MARKUP_H3 :\n case MARKUP_H4 :\n case MARKUP_H5 :\n case MARKUP_H6 :\n case MARKUP_H7 :\n case MARKUP_H8 :\n case MARKUP_H9 :\n case MARKUP_H10 :\n case MARKUP_H11 :\n case MARKUP_H12 :\n case MARKUP_H13 :\n case MARKUP_H14 :\n case MARKUP_H15 :\n case MARKUP_HR :\n case MARKUP_LI :\n case MARKUP_P :\n case MARKUP_PRE :\n DEBUG_printf((\"BREAK at %.1f\\n\", frag_pref));", "\t if (frag_pref > prefw)\n\t prefw = frag_pref;", " if (frag_width > minw)\n\t {\n\t DEBUG_printf((\"Setting minw to %.1f (was %.1f) for block...\\n\",\n\t frag_width, minw));\n minw = frag_width;\n\t }", "\t if (nowrap && frag_pref > minw)\n\t {\n\t DEBUG_printf((\"Setting minw to %.1f (was %.1f) for break...\\n\",\n\t frag_pref, minw));\n\t minw = frag_pref;\n\t }", " frag_pref = 0.0f;\n\t frag_width = 0.0f;", " default :\n frag_height = 0.0f;\n\t break;\n }", " // Update minimum height...\n if (frag_height > minh)\n minh = frag_height;", " // Update next pointer as needed...\n if (next == NULL)\n next = temp->next;", " if (next == NULL)\n {\n // This code is almost funny if you say it fast... :)\n for (next = temp->parent; next != NULL && next != t; next = next->parent)\n\tif (next->next != NULL)\n\t break;", " if (next == t)\n\tnext = NULL;\n else if (next)\n\tnext = next->next;\n }\n }", " // Check the last fragment's width...\n if (frag_pref > prefw)\n prefw = frag_pref;", " if (frag_width > minw)\n {\n DEBUG_printf((\"Setting minw to %.1f (was %.1f) for block...\\n\",\n\t frag_width, minw));\n minw = frag_width;\n }", " // Handle the \"NOWRAP\" option...\n if (nowrap && prefw > minw)\n {\n DEBUG_printf((\"Setting minw to %.1f (was %.1f) for NOWRAP...\\n\",\n\t prefw, minw));\n minw = prefw;\n }", " // Return the required, minimum, and preferred size of the cell...\n *minwidth = minw;\n *prefwidth = prefw;\n *minheight = minh;", " DEBUG_printf((\"get_cell_size(): width=%.1f, minw=%.1f, prefw=%.1f, minh=%.1f\\n\",\n width, minw, prefw, minh));", " return (width);\n}", "\n//\n// 'get_table_size()' - Compute the minimum width of a table.\n//", "static float\t\t\t\t// O - Minimum width of table\nget_table_size(tree_t *t,\t\t// I - Table\n float left,\t\t// I - Left margin\n\t float right,\t\t// I - Right margin\n\t float *minwidth,\t// O - Minimum width\n\t float *prefwidth,\t// O - Preferred width\n\t float *minheight)\t// O - Minimum height\n{\n tree_t\t*temp,\t\t\t// Current tree entry\n\t\t*next;\t\t\t// Next tree entry\n uchar\t\t*var;\t\t\t// Attribute value\n float\t\twidth,\t\t\t// Required width of table\n\t\tminw,\t\t\t// Minimum width of table\n\t\tminh,\t\t\t// Minimum height of table\n\t\tprefw,\t\t\t// Preferred width of table\n\t\tcell_width,\t\t// Cell required width\n\t\tcell_pref,\t\t// Cell preferred width\n\t\tcell_min,\t\t// Cell minimum width\n\t\tcell_height,\t\t// Cell minimum height\n\t\trow_width,\t\t// Row required width\n\t\trow_pref,\t\t// Row preferred width\n\t\trow_min,\t\t// Row minimum width\n\t\trow_height,\t\t// Row minimum height\n\t\tborder,\t\t\t// Border around cells\n\t\tcellpadding,\t\t// Padding inside cells\n\t\tcellspacing;\t\t// Spacing around cells\n int\t\tcolumns,\t\t// Current number of columns\n\t\tmax_columns,\t\t// Maximum columns\n\t\trows;\t\t\t// Number of rows", "\n DEBUG_printf((\"get_table_size(%p, %.1f, %.1f, %p, %p, %p)\\n\",\n (void *)t, left, right, (void *)minwidth, (void *)prefwidth, (void *)minheight));", " // First see if the width has been specified for this table...\n if ((var = htmlGetVariable(t, (uchar *)\"WIDTH\")) != NULL &&\n (var[strlen((char *)var) - 1] != '%' || (right - left) > 0.0f))\n {\n // Yes, use it!\n if (var[strlen((char *)var) - 1] == '%')\n width = (right - left) * atoi((char *)var) * 0.01f;\n else\n width = (float)(atoi((char *)var) * PagePrintWidth / _htmlBrowserWidth);\n }\n else\n width = 0.0f;", " minw = 0.0f;\n prefw = 0.0f;", " // Then the height...\n if ((var = htmlGetVariable(t, (uchar *)\"HEIGHT\")) != NULL)\n {\n // Yes, use it!\n if (var[strlen((char *)var) - 1] == '%')\n minh = PagePrintLength * atoi((char *)var) * 0.01f;\n else\n minh = (float)(atoi((char *)var) * PagePrintWidth / _htmlBrowserWidth);\n }\n else\n minh = 0.0f;", " // Update the size as needed...\n for (temp = t->child, row_width = 0.0f, row_min = 0.0f, row_pref = 0.0f,\n\t row_height = 0.0f, columns = 0, rows = 0, max_columns = 0;\n temp != NULL;\n temp = next)\n {\n // Point to next markup, if any...\n next = temp->child;", " // Start a new row or add the cell width as needed...\n if (temp->markup == MARKUP_TR)\n {\n minh += row_height;", " row_width = 0.0f;\n row_pref = 0.0f;\n row_min = 0.0f;\n row_height = 0.0f;\n rows ++;\n columns = 0;\n }\n else if (temp->markup == MARKUP_TD || temp->markup == MARKUP_TH)\n {\n // Update columns...\n columns ++;\n if (columns > max_columns)\n\tmax_columns = columns;", " // Get widths of cell...\n cell_width = get_cell_size(temp, left, right, &cell_min, &cell_pref,\n &cell_height);", " // Update row widths...\n row_width += cell_width;\n row_pref += cell_pref;\n row_min += cell_min;", " if (cell_height > row_height)\n\trow_height = cell_height;", " // Check current row widths against table...\n if (row_pref > prefw)\n\tprefw = row_pref;", " if (row_min > minw)\n\tminw = row_min;\n }", " // Update next pointer as needed...\n if (next == NULL)\n next = temp->next;", " if (next == NULL)\n {\n // This code is almost funny if you say it fast... :)\n for (next = temp->parent; next != NULL && next != t; next = next->parent)\n\tif (next->next != NULL)\n\t break;", " if (next == t)\n\tnext = NULL;\n else if (next)\n\tnext = next->next;\n }\n }", " // Make sure last row is counted in min height calcs.\n minh += row_height;", " // Add room for spacing and padding...\n if ((var = htmlGetVariable(t, (uchar *)\"CELLPADDING\")) != NULL)\n cellpadding = atoi((char *)var);\n else\n cellpadding = 1.0f;", " if ((var = htmlGetVariable(t, (uchar *)\"CELLSPACING\")) != NULL)\n cellspacing = atoi((char *)var);\n else\n cellspacing = 0.0f;", " if ((var = htmlGetVariable(t, (uchar *)\"BORDER\")) != NULL)\n {\n if ((border = (float)atof((char *)var)) == 0.0 && var[0] != '0')\n border = 1.0f;", " cellpadding += border;\n }\n else\n border = 0.0f;", " if (border == 0.0f && cellpadding > 0.0f)\n {\n /*\n * Ah, the strange table formatting nightmare that is HTML.\n * Netscape and MSIE assign an invisible border width of 1\n * pixel if no border is specified...\n */", " cellpadding += 1.0f;\n }", " cellspacing *= PagePrintWidth / _htmlBrowserWidth;\n cellpadding *= PagePrintWidth / _htmlBrowserWidth;", " DEBUG_printf((\"ADDING %.1f for table space for %d columns...\\n\",\n max_columns * (2 * cellpadding + cellspacing) - cellspacing,\n\t\tmax_columns));", " if (width > 0.0f)\n width += max_columns * (2 * cellpadding + cellspacing) - cellspacing;", " minw += max_columns * (2 * cellpadding + cellspacing) - cellspacing;\n prefw += max_columns * (2 * cellpadding + cellspacing) - cellspacing;\n minh += rows * (2 * cellpadding + cellspacing) - cellspacing;", " // Return the required, minimum, and preferred size of the table...\n *minwidth = minw;\n *prefwidth = prefw;\n *minheight = minh;", " DEBUG_printf((\"get_table_size(): width=%.1f, minw=%.1f, prefw=%.1f, minh=%.1f\\n\",\n width, minw, prefw, minh));", " return (width);\n}", "#ifdef TABLE_DEBUG\n# undef DEBUG_printf\n# undef DEBUG_puts\n# define DEBUG_printf(x)\n# define DEBUG_puts(x)\n#endif /* TABLE_DEBUG */", "\n/*\n * 'flatten_tree()' - Flatten an HTML tree to only include the text, image,\n * link, and break markups.\n */", "static tree_t *\t\t\t/* O - Flattened markup tree */\nflatten_tree(tree_t *t)\t\t/* I - Markup tree to flatten */\n{\n tree_t\t*temp,\t\t/* New tree node */\n\t\t*flat;\t\t/* Flattened tree */", "\n flat = NULL;", " while (t != NULL)\n {\n switch (t->markup)\n {\n case MARKUP_NONE :\n if (t->data == NULL)\n\t break;\n case MARKUP_COMMENT :\n case MARKUP_BR :\n case MARKUP_SPACER :\n case MARKUP_IMG :\n\t temp = (tree_t *)calloc(sizeof(tree_t), 1);\n\t memcpy(temp, t, sizeof(tree_t));\n\t temp->parent = NULL;\n\t temp->child = NULL;\n\t temp->prev = flat;\n\t temp->next = NULL;\n\t if (flat != NULL)\n flat->next = temp;\n flat = temp;", " if (temp->markup == MARKUP_IMG)\n update_image_size(temp);\n break;", " case MARKUP_A :\n if (htmlGetVariable(t, (uchar *)\"NAME\") != NULL)\n {\n\t temp = (tree_t *)calloc(sizeof(tree_t), 1);\n\t memcpy(temp, t, sizeof(tree_t));\n\t temp->parent = NULL;\n\t temp->child = NULL;\n\t temp->prev = flat;\n\t temp->next = NULL;\n\t if (flat != NULL)\n flat->next = temp;\n flat = temp;\n }\n\t break;", " case MARKUP_P :\n case MARKUP_PRE :\n case MARKUP_H1 :\n case MARKUP_H2 :\n case MARKUP_H3 :\n case MARKUP_H4 :\n case MARKUP_H5 :\n case MARKUP_H6 :\n case MARKUP_H7 :\n case MARKUP_H8 :\n case MARKUP_H9 :\n case MARKUP_H10 :\n case MARKUP_H11 :\n case MARKUP_H12 :\n case MARKUP_H13 :\n case MARKUP_H14 :\n case MARKUP_H15 :\n case MARKUP_UL :\n case MARKUP_DIR :\n case MARKUP_MENU :\n case MARKUP_OL :\n case MARKUP_DL :\n case MARKUP_LI :\n case MARKUP_DD :\n case MARKUP_DT :\n case MARKUP_TR :\n case MARKUP_CAPTION :\n\t temp = (tree_t *)calloc(sizeof(tree_t), 1);\n\t temp->markup = MARKUP_BR;\n\t temp->parent = NULL;\n\t temp->child = NULL;\n\t temp->prev = flat;\n\t temp->next = NULL;\n\t if (flat != NULL)\n flat->next = temp;\n flat = temp;\n break;", " default :\n break;\n }", " if (t->child != NULL && t->markup != MARKUP_UNKNOWN)\n {\n temp = flatten_tree(t->child);", " if (temp != NULL)\n temp->prev = flat;\n if (flat != NULL)\n flat->next = temp;\n else\n flat = temp;\n }", " if (flat != NULL)\n while (flat->next != NULL)\n flat = flat->next;", " t = t->next;\n }", " if (flat == NULL)\n return (NULL);", " while (flat->prev != NULL)\n flat = flat->prev;", " return (flat);\n}", "\n/*\n * 'update_image_size()' - Update the size of an image based upon the\n * printable width.\n */", "static void\nupdate_image_size(tree_t *t)\t/* I - Tree entry */\n{\n image_t\t*img;\t\t/* Image file */\n uchar\t\t*width,\t\t/* Width string */\n\t\t*height;\t/* Height string */", "\n width = htmlGetVariable(t, (uchar *)\"WIDTH\");\n height = htmlGetVariable(t, (uchar *)\"HEIGHT\");", " if (width != NULL && height != NULL)\n {\n if (width[strlen((char *)width) - 1] == '%')\n t->width = (float)(atof((char *)width) * PagePrintWidth / 100.0f);\n else\n t->width = (float)(atoi((char *)width) * PagePrintWidth / _htmlBrowserWidth);", " if (height[strlen((char *)height) - 1] == '%')\n t->height = (float)(atof((char *)height) * PagePrintWidth / 100.0f);\n else\n t->height = (float)(atoi((char *)height) * PagePrintWidth / _htmlBrowserWidth);", " return;\n }", " img = image_find((char *)htmlGetVariable(t, (uchar *)\"REALSRC\"));", " if (img == NULL)\n return;", " if (width != NULL)\n {\n if (width[strlen((char *)width) - 1] == '%')\n t->width = (float)(atof((char *)width) * PagePrintWidth / 100.0f);\n else\n t->width = (float)(atoi((char *)width) * PagePrintWidth / _htmlBrowserWidth);", " t->height = t->width * img->height / img->width;\n }\n else if (height != NULL)\n {\n if (height[strlen((char *)height) - 1] == '%')\n t->height = (float)(atof((char *)height) * PagePrintWidth / 100.0f);\n else\n t->height = (float)(atoi((char *)height) * PagePrintWidth / _htmlBrowserWidth);", " t->width = t->height * img->width / img->height;\n }\n else\n {\n t->width = (float)(img->width * PagePrintWidth / _htmlBrowserWidth);\n t->height = (float)(img->height * PagePrintWidth / _htmlBrowserWidth);\n }\n}", "\n/*\n * 'get_width()' - Get the width of a string in points.\n */", "static float\t\t\t/* O - Width in points */\nget_width(uchar *s,\t\t/* I - String to scan */\n int typeface,\t/* I - Typeface code */\n int style,\t\t/* I - Style code */\n int size)\t\t/* I - Size */\n{\n uchar\t*ptr;\t\t\t/* Current character */\n int\twidth;\t\t\t/* Current width */", "\n DEBUG_printf((\"get_width(\\\"%s\\\", %d, %d, %d)\\n\",\n s == NULL ? \"(null)\" : (const char *)s,\n typeface, style, size));", " if (s == NULL)\n return (0.0);", " if (!_htmlWidthsLoaded[typeface][style])\n htmlLoadFontWidths(typeface, style);", " for (width = 0, ptr = s; *ptr != '\\0'; ptr ++)\n width += _htmlWidths[typeface][style][*ptr];", " return (width * _htmlSizes[size] * 0.001f);\n}", "\n/*\n * 'get_title()' - Get the title string for a document.\n */", "static uchar *\t\t/* O - Title string */\nget_title(tree_t *doc)\t/* I - Document */\n{\n uchar\t*temp;", "\n while (doc != NULL)\n {\n if (doc->markup == MARKUP_TITLE)\n return (htmlGetText(doc->child));\n else if (doc->child != NULL)\n if ((temp = get_title(doc->child)) != NULL)\n return (temp);\n doc = doc->next;\n }", " return (NULL);\n}", "\n/*\n * 'open_file()' - Open an output file for the current chapter.\n */", "static FILE *\t\t/* O - File pointer */\nopen_file(void)\n{\n char\tfilename[255];\t/* Filename */", "\n if (OutputFiles && PSLevel > 0)\n {\n if (chapter == -1)\n snprintf(filename, sizeof(filename), \"%s/cover.ps\", OutputPath);\n else if (chapter == 0)\n snprintf(filename, sizeof(filename), \"%s/contents.ps\", OutputPath);\n else\n snprintf(filename, sizeof(filename), \"%s/doc%d.ps\", OutputPath, chapter);", " return (fopen(filename, \"wb+\"));\n }\n else if (OutputFiles)\n {\n snprintf(filename, sizeof(filename), \"%s/doc.pdf\", OutputPath);", " return (fopen(filename, \"wb+\"));\n }\n else if (OutputPath[0] != '\\0')\n return (fopen(OutputPath, \"wb+\"));\n else if (PSLevel == 0)\n return (file_temp(stdout_filename, sizeof(stdout_filename)));\n else\n return (stdout);\n}", "\n/*\n * 'set_color()' - Set the current text color...\n */", "static void\nset_color(FILE *out,\t/* I - File to write to */\n float *rgb)\t/* I - RGB color */\n{\n if (rgb[0] == render_rgb[0] &&\n rgb[1] == render_rgb[1] &&\n rgb[2] == render_rgb[2])\n return;", " render_rgb[0] = rgb[0];\n render_rgb[1] = rgb[1];\n render_rgb[2] = rgb[2];", " if (OutputColor)\n {\n // Output RGB color...\n if (PSLevel > 0)\n fprintf(out, \"%.2f %.2f %.2f C \", rgb[0], rgb[1], rgb[2]);\n else\n flate_printf(out, \"%.2f %.2f %.2f rg \", rgb[0], rgb[1], rgb[2]);\n }\n else\n {\n // Output grayscale...\n if (PSLevel > 0)\n fprintf(out, \"%.2f G \",\n rgb[0] * 0.31f + rgb[1] * 0.61f + rgb[2] * 0.08f);\n else\n flate_printf(out, \"%.2f g \",\n rgb[0] * 0.31f + rgb[1] * 0.61f + rgb[2] * 0.08f);\n }\n}", "\n/*\n * 'set_font()' - Set the current text font.\n */", "static void\nset_font(FILE *out,\t\t\t/* I - File to write to */\n int typeface,\t\t/* I - Typeface code */\n int style,\t\t\t/* I - Style code */\n float size)\t\t\t/* I - Size */\n{\n char\tsizes[255],\t/* Formatted string for size... */\n\t*s;\t\t/* Pointer to end of string */", "\n if (typeface == render_typeface &&\n style == render_style &&\n size == render_size)\n return;", " /*\n * Format size and strip trailing 0's and decimals...\n */", " snprintf(sizes, sizeof(sizes), \"%.1f\", size);", " for (s = sizes + strlen(sizes) - 1; s > sizes && *s == '0'; s --)\n *s = '\\0';", " if (*s == '.')\n *s = '\\0';", " /*\n * Set the new typeface, style, and size.\n */", " if (PSLevel > 0)\n {\n if (size != render_size)\n fprintf(out, \"%s FS\", sizes);", " fprintf(out, \"/F%x SF \", typeface * 4 + style);\n }\n else\n flate_printf(out, \"/F%x %s Tf \", typeface * 4 + style, sizes);", " render_typeface = typeface;\n render_style = style;\n render_size = size;\n}", "\n/*\n * 'set_pos()' - Set the current text position.\n */", "static void\nset_pos(FILE *out,\t\t\t/* I - File to write to */\n float x,\t\t\t/* I - X position */\n float y)\t\t\t/* I - Y position */\n{\n char\txs[255],\t\t\t/* Formatted string for X... */\n\tys[255],\t\t\t/* Formatted string for Y... */\n\t*s;\t\t\t\t/* Pointer to end of string */", "\n if (fabs(render_x - x) < 0.1 && fabs(render_y - y) < 0.1)\n return;", " /*\n * Format X and Y...\n */", " if (PSLevel > 0 || render_x == -1.0)\n {\n snprintf(xs, sizeof(xs), \"%.3f\", x);\n snprintf(ys, sizeof(ys), \"%.3f\", y);\n }\n else\n {\n snprintf(xs, sizeof(xs), \"%.3f\", x - render_startx);\n snprintf(ys, sizeof(ys), \"%.3f\", y - render_y);\n }", " /*\n * Strip trailing 0's and decimals...\n */", " for (s = xs + strlen(xs) - 1; s > xs && *s == '0'; s --)\n *s = '\\0';", " if (*s == '.')\n *s = '\\0';", " for (s = ys + strlen(ys) - 1; s > ys && *s == '0'; s --)\n *s = '\\0';", " if (*s == '.')\n *s = '\\0';", " if (PSLevel > 0)\n fprintf(out, \"%s %s M\", xs, ys);\n else\n flate_printf(out, \"%s %s Td\", xs, ys);", " render_x = render_startx = x;\n render_y = y;\n}", "\n/*\n * 'ps_hex()' - Print binary data as a series of hexadecimal numbers.\n */", "static void\nps_hex(FILE *out,\t\t\t/* I - File to print to */\n uchar *data,\t\t\t/* I - Data to print */\n int length)\t\t\t/* I - Number of bytes to print */\n{\n int\t\tcol;\n static const char *hex = \"0123456789ABCDEF\";", "\n col = 0;\n while (length > 0)\n {\n /*\n * Put the hex uchars out to the file; note that we don't use fprintf()\n * for speed reasons...\n */", " putc(hex[*data >> 4], out);\n putc(hex[*data & 15], out);", " data ++;\n length --;", " col = (col + 1) % 40;\n if (col == 0)\n putc('\\n', out);\n }", " if (col > 0)\n putc('\\n', out);\n}", "", "#ifdef HTMLDOC_ASCII85\n/*\n * 'ps_ascii85()' - Print binary data as a series of base-85 numbers.\n */", "static void\nps_ascii85(FILE *out,\t\t\t/* I - File to print to */\n\t uchar *data,\t\t\t/* I - Data to print */\n\t int length,\t\t/* I - Number of bytes to print */\n\t int eod)\t\t\t/* I - 1 = end-of-data */\n{\n unsigned\tb = 0;\t\t\t/* Current 32-bit word */\n uchar\t\tc[5];\t\t\t/* Base-85 encoded characters */\n static int\tcol = 0;\t\t/* Column */\n static uchar\tleftdata[4];\t\t/* Leftover data at the end */\n static int\tleftcount = 0;\t\t/* Size of leftover data */", "\n length += leftcount;", " while (length > 3)\n {\n switch (leftcount)\n {\n case 0 :\n b = (unsigned)((((((data[0] << 8) | data[1]) << 8) | data[2]) << 8) | data[3]);\n\t break;\n case 1 :\n b = (unsigned)((((((leftdata[0] << 8) | data[0]) << 8) | data[1]) << 8) | data[2]);\n\t break;\n case 2 :\n b = (unsigned)((((((leftdata[0] << 8) | leftdata[1]) << 8) | data[0]) << 8) | data[1]);\n\t break;\n case 3 :\n b = (unsigned)((((((leftdata[0] << 8) | leftdata[1]) << 8) | leftdata[2]) << 8) | data[0]);\n\t break;\n }", " if (col >= 76)\n {\n col = 0;\n putc('\\n', out);\n }", " if (b == 0)\n {\n putc('z', out);\n col ++;\n }\n else\n {\n c[4] = (b % 85) + '!';\n b /= 85;\n c[3] = (b % 85) + '!';\n b /= 85;\n c[2] = (b % 85) + '!';\n b /= 85;\n c[1] = (b % 85) + '!';\n b /= 85;\n c[0] = (uchar)(b + '!');", " fwrite(c, 1, 5, out);\n col += 5;\n }", " data += 4 - leftcount;\n length -= 4 - leftcount;\n leftcount = 0;\n }", " if (length > 0)\n {\n // Copy any remainder into the leftdata array...\n if ((length - leftcount) > 0)\n memcpy(leftdata + leftcount, data, (size_t)(length - leftcount));", " memset(leftdata + length, 0, (size_t)(4 - length));", " leftcount = length;\n }", " if (eod)\n {\n // Do the end-of-data dance...\n if (col >= 76)\n {\n col = 0;\n putc('\\n', out);\n }", " if (leftcount > 0)\n {\n // Write the remaining bytes as needed...\n b = (unsigned)((((((leftdata[0] << 8) | leftdata[1]) << 8) | leftdata[2]) << 8) | leftdata[3]);", " c[4] = (b % 85) + '!';\n b /= 85;\n c[3] = (b % 85) + '!';\n b /= 85;\n c[2] = (b % 85) + '!';\n b /= 85;\n c[1] = (b % 85) + '!';\n b /= 85;\n c[0] = (uchar)(b + '!');", " fwrite(c, (size_t)(leftcount + 1), 1, out);", " leftcount = 0;\n }", " fputs(\"~>\\n\", out);\n col = 0;\n }\n}\n#endif // HTMLDOC_ASCII85", "\n/*\n * JPEG library destination data manager. These routines direct\n * compressed data from libjpeg into the PDF or PostScript file.\n */", "static FILE\t\t\t*jpg_file;\t/* JPEG file */\nstatic uchar\t\t\tjpg_buf[8192];\t/* JPEG buffer */\nstatic jpeg_destination_mgr\tjpg_dest;\t/* JPEG destination manager */\nstatic struct jpeg_error_mgr\tjerr;\t\t/* JPEG error handler */", "\n/*\n * 'jpg_init()' - Initialize the JPEG destination.\n */", "static void\njpg_init(j_compress_ptr cinfo)\t\t/* I - Compressor info */\n{\n (void)cinfo;", " jpg_dest.next_output_byte = jpg_buf;\n jpg_dest.free_in_buffer = sizeof(jpg_buf);\n}", "\n/*\n * 'jpg_empty()' - Empty the JPEG output buffer.\n */", "static boolean\t\t\t\t/* O - True if buffer written OK */\njpg_empty(j_compress_ptr cinfo)\t\t/* I - Compressor info */\n{\n (void)cinfo;", " if (PSLevel > 0)\n#ifdef HTMLDOC_ASCII85\n ps_ascii85(jpg_file, jpg_buf, sizeof(jpg_buf));\n#else\n ps_hex(jpg_file, jpg_buf, sizeof(jpg_buf));\n#endif // HTMLDOC_ASCII85\n else\n flate_write(jpg_file, jpg_buf, sizeof(jpg_buf));", " jpg_dest.next_output_byte = jpg_buf;\n jpg_dest.free_in_buffer = sizeof(jpg_buf);", " return (TRUE);\n}", "\n/*\n * 'jpg_term()' - Write the last JPEG data to the file.\n */", "static void\njpg_term(j_compress_ptr cinfo)\t\t/* I - Compressor info */\n{\n int nbytes;\t\t\t\t/* Number of bytes to write */", "\n (void)cinfo;", " nbytes = sizeof(jpg_buf) - jpg_dest.free_in_buffer;", " if (PSLevel > 0)\n#ifdef HTMLDOC_ASCII85\n ps_ascii85(jpg_file, jpg_buf, nbytes);\n#else\n ps_hex(jpg_file, jpg_buf, nbytes);\n#endif // HTMLDOC_ASCII85\n else\n flate_write(jpg_file, jpg_buf, nbytes);\n}", "\n/*\n * 'jpg_setup()' - Setup the JPEG compressor for writing an image.\n */", "static void\njpg_setup(FILE *out,\t/* I - Output file */\n image_t *img,\t/* I - Output image */\n j_compress_ptr cinfo)\t/* I - Compressor info */\n{\n int\ti;\t\t\t// Looping var", "\n jpg_file = out;\n cinfo->err = jpeg_std_error(&jerr);", " jpeg_create_compress(cinfo);", " cinfo->dest = &jpg_dest;\n jpg_dest.init_destination = jpg_init;\n jpg_dest.empty_output_buffer = jpg_empty;\n jpg_dest.term_destination = jpg_term;", " cinfo->image_width = (JDIMENSION)img->width;\n cinfo->image_height = (JDIMENSION)img->height;\n cinfo->input_components = img->depth;\n cinfo->in_color_space = img->depth == 1 ? JCS_GRAYSCALE : JCS_RGB;", " jpeg_set_defaults(cinfo);\n jpeg_set_quality(cinfo, OutputJPEG, TRUE);", " // Update things when writing to PS files...\n if (PSLevel)\n {\n // Adobe uses sampling == 1\n for (i = 0; i < img->depth; i ++)\n {\n cinfo->comp_info[i].h_samp_factor = 1;\n cinfo->comp_info[i].v_samp_factor = 1;\n }\n }", " cinfo->write_JFIF_header = FALSE;\n cinfo->write_Adobe_marker = TRUE;", " jpeg_start_compress(cinfo, TRUE);\n}", "\n/*\n * 'compare_rgb()' - Compare two RGB colors...\n */", "static int\t\t\t\t/* O - -1 if rgb1<rgb2, etc. */\ncompare_rgb(unsigned *rgb1,\t\t/* I - First color */\n unsigned *rgb2)\t\t/* I - Second color */\n{\n return ((int)*rgb1 - (int)*rgb2);\n}", "\n/*\n * 'write_image()' - Write an image to the given output file...\n */", "static void\nwrite_image(FILE *out,\t\t/* I - Output file */\n render_t *r,\t\t/* I - Image to write */\n\t int write_obj)\t\t/* I - Write an object? */\n{\n int\t\ti, j, k, m,\t\t/* Looping vars */\n\t\tncolors;\t\t/* Number of colors */\n uchar\t\t*pixel,\t\t\t/* Current pixel */\n\t\t*indices,\t\t/* New indexed pixel array */\n\t\t*indptr;\t\t/* Current index */\n int\t\tindwidth,\t\t/* Width of indexed line */\n\t\tindbits;\t\t/* Bits per index */\n int\t\tmax_colors;\t\t/* Max colors to use */\n unsigned\tcolors[256],\t\t/* Colormap values */\n\t\tkey,\t\t\t/* Color key */\n\t\t*match;\t\t\t/* Matching color value */\n uchar\t\tgrays[256],\t\t/* Grayscale usage */\n\t\tcmap[256][3];\t\t/* Colormap */\n image_t \t*img;\t\t\t/* Image */\n struct jpeg_compress_struct cinfo;\t/* JPEG compressor */\n uchar\t\t*data,\t\t\t/* PS Level 3 image data */\n\t\t*dataptr,\t\t/* Pointer into image data */\n\t\t*maskptr;\t\t/* Pointer into mask data */", "\n /*\n * See if we can optimize the image as indexed without color loss...\n */", " img = r->data.image;\n ncolors = 0;\n indices = NULL;\n indwidth = 0;", " if (!img->pixels && !img->obj)\n image_load(img->filename, !OutputColor, 1);", " // Note: Acrobat 6 tries to decrypt the colormap of indexed in-line images twice, which\n // is 1) not consistent with prior Acrobat releases and 2) in violation of their\n // PDF spec. The \"img->use > 1 || !Encryption\" test prevents the use of indexed\n // in-line images when encryption is enabled.\n //\n // We are filing a bug on this with Adobe, but if history is any indicator, we are\n // stuck with this workaround forever...\n if (PSLevel != 1 && PDFVersion >= 12 && img->obj == 0 && (img->use > 1 || !Encryption))\n {\n if (img->depth == 1)\n {\n /*\n * Greyscale image...\n */", " memset(grays, 0, sizeof(grays));", " for (i = img->width * img->height, pixel = img->pixels;\n\t i > 0;\n\t i --, pixel ++)\n\tif (!grays[*pixel])\n\t{\n if (ncolors >= 16)\n\t break;", "\t grays[*pixel] = 1;\n\t ncolors ++;\n\t}", " if (i == 0)\n {\n\tfor (i = 0, j = 0; i < 256; i ++)\n\t if (grays[i])\n\t {\n\t colors[j] = (unsigned)((((i << 8) | i) << 8) | i);\n\t grays[i] = (uchar)j;\n\t j ++;\n\t }\n }\n else\n ncolors = 0;\n }\n else\n {\n /*\n * Color image...\n */", " if (OutputJPEG && !Compression)\n max_colors = 16;\n else\n max_colors = 256;", " for (i = img->width * img->height, pixel = img->pixels, match = NULL;\n\t i > 0;\n\t i --, pixel += 3)\n {\n key = (unsigned)((((pixel[0] << 8) | pixel[1]) << 8) | pixel[2]);", "\tif (!match || *match != key)\n\t{\n if (ncolors > 0)\n match = (unsigned *)bsearch(&key, colors, (size_t)ncolors, sizeof(unsigned), (compare_func_t)compare_rgb);\n else\n match = NULL;\n }", " if (match == NULL)\n {\n if (ncolors >= max_colors)\n break;", " colors[ncolors] = key;\n ncolors ++;", " if (ncolors > 1)\n qsort(colors, (size_t)ncolors, sizeof(unsigned), (compare_func_t)compare_rgb);\n }\n }", " if (i > 0)\n ncolors = 0;\n }\n }", " if (ncolors > 0)\n {\n if (PSLevel == 3 && img->mask)\n indbits = 8;\n else if (ncolors <= 2)\n indbits = 1;\n else if (ncolors <= 4)\n indbits = 2;\n else if (ncolors <= 16)\n indbits = 4;\n else\n indbits = 8;", " indwidth = (img->width * indbits + 7) / 8;\n indices = (uchar *)calloc((size_t)indwidth, (size_t)(img->height + 1));\n\t\t\t\t\t// height + 1 for PS odd-row-count bug", " if (img->depth == 1)\n {\n /*\n * Convert a grayscale image...\n */", " switch (indbits)\n {\n case 1 :\n\t for (i = img->height, pixel = img->pixels, indptr = indices;\n\t\t i > 0;\n\t\t i --)\n\t {\n\t for (j = img->width, k = 7; j > 0; j --, k = (k + 7) & 7, pixel ++)\n\t\tswitch (k)\n\t\t{\n\t\t case 7 :\n\t *indptr = (uchar)(grays[*pixel] << 7);\n\t\t break;\n\t\t default :\n\t *indptr |= (uchar)(grays[*pixel] << k);\n\t\t break;\n\t\t case 0 :\n\t *indptr++ |= (uchar)grays[*pixel];\n\t\t break;\n \t}", "\t if (k != 7)\n\t\tindptr ++;\n\t }\n\t break;", " case 2 :\n\t for (i = img->height, pixel = img->pixels, indptr = indices;\n\t\t i > 0;\n\t\t i --)\n\t {\n\t for (j = img->width, k = 0; j > 0; j --, k = (k + 1) & 3, pixel ++)\n\t\tswitch (k)\n\t\t{\n\t\t case 0 :\n\t *indptr = (uchar)(grays[*pixel] << 6);\n\t\t break;\n\t\t case 1 :\n\t *indptr |= (uchar)(grays[*pixel] << 4);\n\t\t break;\n\t\t case 2 :\n\t *indptr |= (uchar)(grays[*pixel] << 2);\n\t\t break;\n\t\t case 3 :\n\t *indptr++ |= (uchar)grays[*pixel];\n\t\t break;\n \t}", "\t if (k)\n\t\tindptr ++;\n\t }\n\t break;", " case 4 :\n\t for (i = img->height, pixel = img->pixels, indptr = indices;\n\t\t i > 0;\n\t\t i --)\n\t {\n\t for (j = img->width, k = 0; j > 0; j --, k ^= 1, pixel ++)\n\t\tif (k)\n\t\t *indptr++ |= grays[*pixel];\n\t\telse\n\t\t *indptr = (uchar)(grays[*pixel] << 4);", "\t if (k)\n\t\tindptr ++;\n\t }\n\t break;\n }\n }\n else\n {\n /*\n * Convert a color image...\n */", " switch (indbits)\n {\n case 1 :\n\t for (i = img->height, pixel = img->pixels, indptr = indices,\n\t match = colors;\n\t\t i > 0;\n\t\t i --)\n\t {\n\t for (j = img->width, k = 7;\n\t j > 0;\n\t\t j --, k = (k + 7) & 7, pixel += 3)\n\t {\n key = (unsigned)((((pixel[0] << 8) | pixel[1]) << 8) | pixel[2]);", "\t\tif (*match != key)\n \t match = (unsigned *)bsearch(&key, colors, (size_t)ncolors, sizeof(unsigned), (compare_func_t)compare_rgb);\n\t m = match - colors;", "\t\tswitch (k)\n\t\t{\n\t\t case 7 :\n\t *indptr = (uchar)(m << 7);\n\t\t break;\n\t\t default :\n\t *indptr |= (uchar)(m << k);\n\t\t break;\n\t\t case 0 :\n\t *indptr++ |= (uchar)m;\n\t\t break;\n \t}\n\t }", "\t if (k != 7)\n\t indptr ++;\n\t }\n\t break;", " case 2 :\n\t for (i = img->height, pixel = img->pixels, indptr = indices,\n\t match = colors;\n\t\t i > 0;\n\t\t i --)\n\t {\n\t for (j = img->width, k = 0;\n\t j > 0;\n\t\t j --, k = (k + 1) & 3, pixel += 3)\n\t {\n key = (unsigned)((((pixel[0] << 8) | pixel[1]) << 8) | pixel[2]);", "\t\tif (*match != key)\n \t match = (unsigned *)bsearch(&key, colors, (size_t)ncolors, sizeof(unsigned), (compare_func_t)compare_rgb);\n\t m = match - colors;", "\t\tswitch (k)\n\t\t{\n\t\t case 0 :\n\t *indptr = (uchar)(m << 6);\n\t\t break;\n\t\t case 1 :\n\t *indptr |= (uchar)(m << 4);\n\t\t break;\n\t\t case 2 :\n\t *indptr |= (uchar)(m << 2);\n\t\t break;\n\t\t case 3 :\n\t *indptr++ |= (uchar)m;\n\t\t break;\n \t}\n\t }", "\t if (k)\n\t indptr ++;\n\t }\n\t break;", " case 4 :\n\t for (i = img->height, pixel = img->pixels, indptr = indices,\n\t match = colors;\n\t\t i > 0;\n\t\t i --)\n\t {\n\t for (j = img->width, k = 0; j > 0; j --, k ^= 1, pixel += 3)\n\t {\n key = (unsigned)((((pixel[0] << 8) | pixel[1]) << 8) | pixel[2]);", "\t\tif (*match != key)\n \t match = (unsigned *)bsearch(&key, colors, (size_t)ncolors, sizeof(unsigned), (compare_func_t)compare_rgb);\n\t m = match - colors;", "\t\tif (k)\n\t\t *indptr++ |= (uchar)m;\n\t\telse\n\t\t *indptr = (uchar)(m << 4);\n\t }", "\t if (k)\n\t indptr ++;\n\t }\n\t break;", " case 8 :\n\t for (i = img->height, pixel = img->pixels, indptr = indices,\n\t match = colors;\n\t\t i > 0;\n\t\t i --)\n\t {\n\t for (j = img->width; j > 0; j --, pixel += 3, indptr ++)\n\t {\n key = (unsigned)((((pixel[0] << 8) | pixel[1]) << 8) | pixel[2]);", "\t\tif (*match != key)\n \t match = (unsigned *)bsearch(&key, colors, (size_t)ncolors, sizeof(unsigned), (compare_func_t)compare_rgb);\n\t *indptr = (uchar)(match - colors);\n\t }\n\t }\n\t break;\n }\n }\n }\n else\n indbits = 8;", " if (ncolors == 1)\n {\n /*\n * Adobe doesn't like 1 color images...\n */", " ncolors = 2;\n colors[1] = 0;\n }", " /*\n * Now write the image...\n */", " switch (PSLevel)\n {\n case 0 : /* PDF */\n if (!write_obj)\n\t flate_printf(out, \"q %.1f 0 0 %.1f %.1f %.1f cm\\n\", r->width, r->height,\n\t r->x, r->y);", " if (img->obj)\n\t{\n\t if (img->mask && PDFVersion < 13)\n\t write_imagemask(out, r);", "\t flate_printf(out, \"/I%d Do Q\\n\", img->obj);\n\t break;\n\t}", " if (img->mask && write_obj && PDFVersion >= 13)\n\t{\n\t // We have a mask image, write it!\n pdf_start_object(out);\n\t fputs(\"/Type/XObject/Subtype/Image\", out);\n fputs(\"/ColorSpace/DeviceGray\", out);\n\t if (img->maskscale == 8)\n\t fprintf(out, \"/Width %d/Height %d/BitsPerComponent 8\",\n\t img->width, img->height);\n else\n\t fprintf(out, \"/Width %d/Height %d/BitsPerComponent 1/ImageMask true\",\n\t img->width * img->maskscale, img->height * img->maskscale);\n if (Compression)\n fputs(\"/Filter/FlateDecode\", out);", " pdf_start_stream(out);\n flate_open_stream(out);\n\t if (img->maskscale == 8)\n \t flate_write(out, img->mask, img->width * img->height);\n\t else\n \t flate_write(out, img->mask,\n\t img->maskwidth * img->height * img->maskscale);\n\t flate_close_stream(out);", " pdf_end_object(out);\n\t}", " if (write_obj)\n\t{\n\t // Write an image object...\n\t img->obj = pdf_start_object(out);", "\t fputs(\"/Type/XObject/Subtype/Image\", out);\n\t if (img->mask && PDFVersion >= 13)\n\t {\n\t if (img->maskscale == 8)\n\t fprintf(out, \"/SMask %d 0 R\", img->obj - 1);\n\t else\n\t fprintf(out, \"/Mask %d 0 R\", img->obj - 1);\n\t }", "\t if (ncolors > 0)\n\t {\n\t for (i = 0; i < ncolors; i ++)\n\t {\n\t cmap[i][0] = (uchar)(colors[i] >> 16);\n\t cmap[i][1] = (uchar)(colors[i] >> 8);\n\t cmap[i][2] = (uchar)colors[i];\n\t }", "\t if (Encryption)\n\t {\n\t // Encrypt the colormap...\n\t encrypt_init();\n\t rc4_encrypt(&encrypt_state, cmap[0], cmap[0], (unsigned)(ncolors * 3));\n\t }", "\t fprintf(out, \"/ColorSpace[/Indexed/DeviceRGB %d<\", ncolors - 1);\n\t for (i = 0; i < ncolors; i ++)\n\t fprintf(out, \"%02X%02X%02X\", cmap[i][0], cmap[i][1],\n\t cmap[i][2]);\n\t fputs(\">]\", out);\n }\n\t else if (img->depth == 1)\n fputs(\"/ColorSpace/DeviceGray\", out);\n else\n fputs(\"/ColorSpace/DeviceRGB\", out);", "#ifdef HTMLDOC_INTERPOLATION\n if (ncolors != 2)\n fputs(\"/Interpolate true\", out);\n#endif // HTMLDOC_INTERPOLATION", " if (Compression && (ncolors || !OutputJPEG))\n fputs(\"/Filter/FlateDecode\", out);\n\t else if (OutputJPEG && ncolors == 0)\n\t {\n\t if (Compression)\n\t fputs(\"/Filter[/FlateDecode/DCTDecode]\", out);\n\t else\n\t fputs(\"/Filter/DCTDecode\", out);\n\t }", " \t fprintf(out, \"/Width %d/Height %d/BitsPerComponent %d\",\n\t img->width, img->height, indbits);\n pdf_start_stream(out);\n flate_open_stream(out);", " if (OutputJPEG && ncolors == 0)\n\t {\n\t jpg_setup(out, img, &cinfo);", "\t for (i = img->height, pixel = img->pixels;\n\t i > 0;\n\t i --, pixel += img->width * img->depth)\n\t jpeg_write_scanlines(&cinfo, &pixel, 1);", "\t jpeg_finish_compress(&cinfo);\n\t jpeg_destroy_compress(&cinfo);\n\t }\n else\n\t {\n\t if (ncolors > 0)\n \t flate_write(out, indices, indwidth * img->height);\n\t else\n \t flate_write(out, img->pixels,\n\t img->width * img->height * img->depth);\n }", " flate_close_stream(out);\n pdf_end_object(out);\n\t}\n\telse\n\t{\n\t // Put the image in-line...\n flate_puts(\"BI\", out);", "\t if (ncolors > 0)\n\t {\n\t flate_printf(out, \"/CS[/I/RGB %d<\", ncolors - 1);\n\t for (i = 0; i < ncolors; i ++)\n\t flate_printf(out, \"%02X%02X%02X\", colors[i] >> 16,\n\t \t (colors[i] >> 8) & 255, colors[i] & 255);\n\t flate_puts(\">]\", out);\n }\n\t else if (img->depth == 1)\n flate_puts(\"/CS/G\", out);\n else\n flate_puts(\"/CS/RGB\", out);", " if (ncolors != 2)\n flate_puts(\"/I true\", out);", " \t flate_printf(out, \"/W %d/H %d/BPC %d\", img->width, img->height, indbits);", "\t if (ncolors > 0)\n\t {\n \t flate_puts(\" ID\\n\", out);\n \t flate_write(out, indices, indwidth * img->height, 1);\n\t }\n\t else if (OutputJPEG)\n\t {\n \t flate_puts(\"/F/DCT ID\\n\", out);", "\t jpg_setup(out, img, &cinfo);", "\t for (i = img->height, pixel = img->pixels;\n\t i > 0;\n\t i --, pixel += img->width * img->depth)\n\t jpeg_write_scanlines(&cinfo, &pixel, 1);", "\t jpeg_finish_compress(&cinfo);\n\t jpeg_destroy_compress(&cinfo);\n }\n\t else\n\t {\n \t flate_puts(\" ID\\n\", out);\n \t flate_write(out, img->pixels, img->width * img->height * img->depth, 1);\n }", "\t flate_write(out, (uchar *)\"\\nEI\\nQ\\n\", 6, 1);\n\t}\n break;", " case 1 : /* PostScript, Level 1 */\n fputs(\"GS\", out);\n\tfprintf(out, \"[%.1f 0 0 %.1f %.1f %.1f]CM\", r->width, r->height,\n\t r->x, r->y);", "\tif (img->mask)\n\t write_imagemask(out, r);", "\tfprintf(out, \"/picture %d string def\\n\", img->width * img->depth);", "\tif (img->depth == 1)\n\t fprintf(out, \"%d %d 8 [%d 0 0 %d 0 %d] {currentfile picture readhexstring pop} image\\n\",\n \t img->width, img->height,\n \t img->width, -img->height,\n \t img->height);\n\telse\n\t fprintf(out, \"%d %d 8 [%d 0 0 %d 0 %d] {currentfile picture readhexstring pop} false 3 colorimage\\n\",\n \t img->width, img->height,\n \t img->width, -img->height,\n \t img->height);", "\tps_hex(out, img->pixels, img->width * img->height * img->depth);", "\tfputs(\"GR\\n\", out);\n break;\n case 3 : /* PostScript, Level 3 */\n // Fallthrough to Level 2 output if compression is disabled and\n\t// we aren't doing transparency...\n if ((Compression && (!OutputJPEG || ncolors > 0)) ||\n\t (img->mask && img->maskscale == 8))\n\t{\n fputs(\"GS\", out);\n\t fprintf(out, \"[%.1f 0 0 %.1f %.1f %.1f]CM\", r->width, r->height,\n\t r->x, r->y);", "\t if (img->mask && img->maskscale != 8)\n\t write_imagemask(out, r);", " if (ncolors > 0)\n {\n\t if (ncolors <= 2)\n\t ncolors = 2; /* Adobe doesn't like 1 color images... */", "\t fprintf(out, \"[/Indexed/DeviceRGB %d\\n<\", ncolors - 1);\n\t for (i = 0; i < ncolors; i ++)\n\t {\n\t fprintf(out, \"%02X%02X%02X\", colors[i] >> 16,\n\t (colors[i] >> 8) & 255, colors[i] & 255);\n\t if ((i % 13) == 12)\n\t putc('\\n', out);\n }\n\t fputs(\">]setcolorspace\\n\", out);", "\t if (img->mask && img->maskscale == 8)\n\t fprintf(out, \"<<\"\n\t \"/ImageType 3\"\n\t\t\t \"/InterleaveType 1\"\n\t\t\t \"/MaskDict<<\"\n\t \"/ImageType 1\"\n\t \"/Width %d\"\n\t \"/Height %d\"\n\t \"/BitsPerComponent 8\"\n\t \"/ImageMatrix[%d 0 0 %d 0 %d]\"\n\t\t\t \"/Decode[0 1]\"\n\t \">>\\n\"\n\t\t\t \"/DataDict\",\n\t img->width, img->height,\n \t img->width, -img->height, img->height);", "\t fprintf(out, \"<<\"\n\t \"/ImageType 1\"\n\t \"/Width %d\"\n\t \"/Height %d\"\n\t \"/BitsPerComponent %d\"\n\t \"/ImageMatrix[%d 0 0 %d 0 %d]\"\n\t \"/Decode[0 %d]\",\n\t img->width, img->height, indbits,\n \t img->width, -img->height, img->height,\n \t (1 << indbits) - 1);", "#ifdef HTMLDOC_INTERPOLATION\n if (ncolors != 2)\n\t fputs(\"/Interpolate true\", out);\n#endif // HTMLDOC_INTERPOLATION", "#ifdef HTMLDOC_ASCII85\n fputs(\"/DataSource currentfile/ASCII85Decode filter\", out);\n#else\n fputs(\"/DataSource currentfile/ASCIIHexDecode filter\", out);\n#endif // HTMLDOC_ASCII85", " if (Compression)\n\t fputs(\"/FlateDecode filter\", out);", "\t fputs(\">>\\n\", out);", "\t if (img->mask && img->maskscale == 8)\n\t fputs(\">>\\n\", out);", "\t fputs(\"image\\n\", out);", " flate_open_stream(out);", "\t if (img->mask && img->maskscale == 8)\n\t {\n\t data = (uchar *)malloc((size_t)(img->width * 2));", "\t for (i = 0, maskptr = img->mask, indptr = indices;\n\t i < img->height;\n\t\t i ++)\n\t {\n\t for (j = img->width, dataptr = data; j > 0; j --)\n\t\t{\n\t\t *dataptr++ = *maskptr++;\n\t\t *dataptr++ = *indptr++;\n\t\t}", "\t\tflate_write(out, data, img->width * 2);\n\t }", "\t free(data);\n\t }\n\t else\n\t flate_write(out, indices, indwidth * img->height);", "\t flate_close_stream(out);\n }\n else\n {\n\t if (img->depth == 1)\n\t fputs(\"/DeviceGray setcolorspace\", out);\n\t else\n\t fputs(\"/DeviceRGB setcolorspace\", out);", "\t if (img->mask && img->maskscale == 8)\n\t fprintf(out, \"<<\"\n\t \"/ImageType 3\"\n\t\t\t \"/InterleaveType 1\"\n\t\t\t \"/MaskDict<<\"\n\t \"/ImageType 1\"\n\t \"/Width %d\"\n\t \"/Height %d\"\n\t \"/BitsPerComponent 8\"\n\t \"/ImageMatrix[%d 0 0 %d 0 %d]\"\n\t\t\t \"/Decode[0 1]\"\n\t \">>\\n\"\n\t\t\t \"/DataDict\",\n\t img->width, img->height,\n \t img->width, -img->height, img->height);", "\t fprintf(out, \"<<\"\n\t \"/ImageType 1\"\n\t \"/Width %d\"\n\t \"/Height %d\"\n\t \"/BitsPerComponent 8\"\n\t \"/ImageMatrix[%d 0 0 %d 0 %d]\"\n\t \"/Decode[%s]\",\n\t img->width, img->height,\n \t img->width, -img->height, img->height,\n \t img->depth == 1 ? \"0 1\" : \"0 1 0 1 0 1\");", "#ifdef HTMLDOC_INTERPOLATION\n\t fputs(\"/Interpolate true\", out);\n#endif // HTMLDOC_INTERPOLATION", "#ifdef HTMLDOC_ASCII85\n fputs(\"/DataSource currentfile/ASCII85Decode filter\", out);\n#else\n fputs(\"/DataSource currentfile/ASCIIHexDecode filter\", out);\n#endif // HTMLDOC_ASCII85", " if (Compression)\n\t fputs(\"/FlateDecode filter\", out);", "\t fputs(\">>\\n\", out);", "\t if (img->mask && img->maskscale == 8)\n\t fputs(\">>\\n\", out);", "\t fputs(\"image\\n\", out);", " flate_open_stream(out);", "\t if (img->mask && img->maskscale == 8)\n\t {\n\t data = (uchar *)malloc((size_t)(img->width * (img->depth + 1)));", "\t for (i = 0, maskptr = img->mask, pixel = img->pixels;\n\t i < img->height;\n\t\t i ++)\n\t {\n\t if (img->depth == 1)\n\t\t{\n\t for (j = img->width, dataptr = data; j > 0; j --)\n\t\t {\n\t\t *dataptr++ = *maskptr++;\n\t\t *dataptr++ = *pixel++;\n\t\t }\n\t\t}\n\t\telse\n\t\t{\n\t for (j = img->width, dataptr = data; j > 0; j --)\n\t\t {\n\t\t *dataptr++ = *maskptr++;\n\t\t *dataptr++ = *pixel++;\n\t\t *dataptr++ = *pixel++;\n\t\t *dataptr++ = *pixel++;\n\t\t }\n\t\t}", "\t\tflate_write(out, data, img->width * (img->depth + 1));\n\t }", "\t free(data);\n\t }\n\t else\n\t flate_write(out, img->pixels,\n\t img->width * img->height * img->depth);", "\t flate_close_stream(out);\n }", "\t fputs(\"GR\\n\", out);\n break;\n\t}", " case 2 : /* PostScript, Level 2 */\n fputs(\"GS\", out);\n\tfprintf(out, \"[%.1f 0 0 %.1f %.1f %.1f]CM\", r->width, r->height,\n\t r->x, r->y);", "\tif (img->mask)\n\t write_imagemask(out, r);", " if (ncolors > 0)\n {\n\t fprintf(out, \"[/Indexed/DeviceRGB %d\\n<\", ncolors - 1);\n\t for (i = 0; i < ncolors; i ++)\n\t {\n\t fprintf(out, \"%02X%02X%02X\", colors[i] >> 16,\n\t (colors[i] >> 8) & 255, colors[i] & 255);\n\t if ((i % 13) == 12)\n\t putc('\\n', out);\n }", "\t fputs(\">]setcolorspace\\n\", out);", "\t fprintf(out, \"<<\"\n\t \"/ImageType 1\"\n\t \"/Width %d\"\n\t \"/Height %d\"\n\t \"/BitsPerComponent %d\"\n\t \"/ImageMatrix[%d 0 0 %d 0 %d]\"\n\t \"/Decode[0 %d]\",\n\t img->width, img->height, indbits,\n \t img->width, -img->height, img->height,\n \t (1 << indbits) - 1);", "#ifdef HTMLDOC_INTERPOLATION\n if (ncolors != 2)\n\t fputs(\"/Interpolate true\", out);\n#endif // HTMLDOC_INTERPOLATION", "#ifdef HTMLDOC_ASCII85\n\t fputs(\"/DataSource currentfile/ASCII85Decode filter>>image\\n\", out);", " ps_ascii85(out, indices, indwidth * img->height, 1);\n#else\n\t fputs(\"/DataSource currentfile/ASCIIHexDecode filter>>image\\n\", out);", " ps_hex(out, indices, indwidth * img->height);\n\t // End of data marker...\n\t fputs(\">\\n\", out);\n#endif /* HTMLDOC_ASCII85 */\n }\n\telse if (OutputJPEG)\n\t{\n\t if (img->depth == 1)\n\t fputs(\"/DeviceGray setcolorspace\\n\", out);\n\t else\n\t fputs(\"/DeviceRGB setcolorspace\\n\", out);", "\t fprintf(out, \"<<\"\n\t \"/ImageType 1\"\n\t \"/Width %d\"\n\t \"/Height %d\"\n\t \"/BitsPerComponent 8\"\n\t \"/ImageMatrix[%d 0 0 %d 0 %d]\"\n\t \"/Decode[%s]\",\n\t img->width, img->height,\n \t img->width, -img->height, img->height,\n \t img->depth == 1 ? \"0 1\" : \"0 1 0 1 0 1\");", "#ifdef HTMLDOC_INTERPOLATION\n\t fputs(\"/Interpolate true\", out);\n#endif // HTMLDOC_INTERPOLATION", "#ifdef HTMLDOC_ASCII85\n\t fputs(\"/DataSource currentfile/ASCII85Decode filter/DCTDecode filter\"\n\t \">>image\\n\", out);\n#else\n\t fputs(\"/DataSource currentfile/ASCIIHexDecode filter/DCTDecode filter\"\n\t \">>image\\n\", out);\n#endif // HTMLDOC_ASCII85", "\t jpg_setup(out, img, &cinfo);", "\t for (i = img->height, pixel = img->pixels;\n\t i > 0;\n\t i --, pixel += img->width * img->depth)\n\t jpeg_write_scanlines(&cinfo, &pixel, 1);", "\t jpeg_finish_compress(&cinfo);\n\t jpeg_destroy_compress(&cinfo);", "#ifdef HTMLDOC_ASCII85\n ps_ascii85(out, (uchar *)\"\", 0, 1);\n#else\n\t // End of data marker...\n\t fputs(\">\\n\", out);\n#endif // HTMLDOC_ASCII85\n }\n else\n {\n\t if (img->depth == 1)\n\t fputs(\"/DeviceGray setcolorspace\\n\", out);\n\t else\n\t fputs(\"/DeviceRGB setcolorspace\\n\", out);", "\t fprintf(out, \"<<\"\n\t \"/ImageType 1\"\n\t \"/Width %d\"\n\t \"/Height %d\"\n\t \"/BitsPerComponent 8\"\n\t \"/ImageMatrix[%d 0 0 %d 0 %d]\"\n\t \"/Decode[%s]\",\n\t img->width, img->height,\n \t img->width, -img->height, img->height,\n \t img->depth == 1 ? \"0 1\" : \"0 1 0 1 0 1\");", "#ifdef HTMLDOC_INTERPOLATION\n\t fputs(\"/Interpolate true\", out);\n#endif // HTMLDOC_INTERPOLATION", "#ifdef HTMLDOC_ASCII85\n fputs(\"/DataSource currentfile/ASCII85Decode filter\"\n\t \">>image\\n\", out);", "\t ps_ascii85(out, img->pixels, img->width * img->height *\n\t img->depth, 1);\n#else\n fputs(\"/DataSource currentfile/ASCIIHexDecode filter\"\n\t \">>image\\n\", out);", " ps_hex(out, img->pixels, img->width * img->depth * img->height);\n\t // End of data marker...\n\t fputs(\">\\n\", out);\n#endif // HTMLDOC_ASCII85\n }", "\tfputs(\"GR\\n\", out);\n break;\n }", " if (ncolors > 0)\n free(indices);", " image_unload(img);\n}", "\n/*\n * 'write_imagemask()' - Write an imagemask to the output file...\n */", "static void\nwrite_imagemask(FILE *out,\t\t/* I - Output file */\n render_t *r)\t\t/* I - Image to write */\n{\n image_t\t*img;\t\t\t/* Current image */\n int\t\tx, y;\t\t\t/* Position in mask image */\n int\t\tstartx, count;\t\t/* Start and count */\n uchar\t\t*ptr,\t\t\t/* Pointer into mask image */\n\t\tbyte,\t\t\t/* Current byte */\n\t\tbit;\t\t\t/* Current bit */\n float\t\tscalex, scaley;\t\t/* 1/(w-1) and 1/(h-1) scaling factors */\n int\t\twidth, height;\t\t/* Scaled width and height */", "\n img = r->data.image;\n width = img->width * img->maskscale;\n height = img->height * img->maskscale;\n scalex = 1.0f / width;\n scaley = 1.0f / height;", " switch (PSLevel)\n {\n case 0 : // PDF\n break;", " default : // PostScript\n fputs(\"\\nnewpath\\n\", out);\n break;\n }", " for (y = 0; y < height; y ++)\n {\n for (x = 0, ptr = img->mask + (height - y - 1) * img->maskwidth,\n bit = 128, byte = *ptr++, startx = 0, count = 0;\n x < width;\n\t x ++)\n {\n if (!(bit & byte))\n {\n if (!count)\n\t startx = x;", " count ++;\n }\n else if (count)\n {\n\tswitch (PSLevel)\n\t{\n\t case 0 : // PDF\n\t flate_printf(out, \"%.6f %.6f %.6f %.6f re\\n\",\n\t\t\t (float)startx * scalex,\n\t\t\t (float)y * scaley,\n\t\t\t (float)count * scalex,\n\t\t\t 1.0f * scaley);\n break;", "\t default : // PostScript\n\t fprintf(out, \"%.6f %.6f %.6f %.6f re\\n\",\n\t\t (float)startx * scalex,\n\t\t (float)y * scaley,\n\t\t (float)count * scalex,\n\t\t 1.0f * scaley);\n break;\n\t}", "\tcount = 0;\n }", " if (bit > 1)\n bit >>= 1;\n else\n {\n bit = 128;\n\tbyte = *ptr++;\n }\n }", " if (count)\n {\n switch (PSLevel)\n {\n\tcase 0 : // PDF\n\t flate_printf(out, \"%.6f %.6f %.6f %.6f re\\n\",\n\t\t\t (float)startx * scalex,\n\t\t\t (float)y * scaley,\n\t\t\t (float)count * scalex,\n\t\t\t 1.0f * scaley);\n break;", "\tdefault : // PostScript\n\t fprintf(out, \"%.6f %.6f %.6f %.6f re\\n\",\n\t\t (float)startx * scalex,\n\t\t (float)y * scaley,\n\t\t (float)count * scalex,\n\t\t 1.0f * scaley);\n break;\n }\n }\n }", " switch (PSLevel)\n {\n case 0 : // PDF\n flate_puts(\"W n\\n\", out);\n break;", " default : // PostScript\n fputs(\"clip\\n\", out);\n break;\n }\n}", "\n/*\n * 'write_prolog()' - Write the file prolog...\n */", "static void\nwrite_prolog(FILE *out,\t\t/* I - Output file */\n int page_count,\t\t/* I - Number of pages (0 if not known) */\n uchar *author,\t\t/* I - Author of document */\n uchar *creator,\t\t/* I - Application that generated the HTML file */\n uchar *copyright,\t\t/* I - Copyright (if any) on the document */\n uchar *keywords,\t\t/* I - Search keywords */\n\t uchar *subject)\t\t/* I - Subject */\n{\n FILE\t\t*prolog;\t\t/* PostScript prolog file */\n int\t\ti, j,\t\t\t/* Looping vars */\n\t\tencoding_object;\t/* Font encoding object */\n int\t\tpage;\t\t\t/* Current page */\n render_t\t*r;\t\t\t/* Current render data */\n int\t\tfonts_used[TYPE_MAX][STYLE_MAX];\n\t\t\t\t\t/* Whether or not a font is used */\n int\t\tfont_desc[TYPE_MAX][STYLE_MAX];\n\t\t\t\t\t/* Font descriptor objects */\n char\t\ttemp[1024];\t\t/* Temporary string */\n md5_state_t\tmd5;\t\t\t/* MD5 state */\n md5_byte_t\tdigest[16];\t\t/* MD5 digest value */\n rc4_context_t\trc4;\t\t\t/* RC4 context */\n uchar\t\towner_pad[32],\t\t/* Padded owner password */\n\t\towner_key[32],\t\t/* Owner key */\n\t\tuser_pad[32],\t\t/* Padded user password */\n\t\tuser_key[32];\t\t/* User key */\n uchar\t\tperm_bytes[4];\t\t/* Permission bytes */\n unsigned\tperm_value;\t\t/* Permission value, unsigned */\n static unsigned char pad[32] =\n\t\t{\t\t\t/* Padding for passwords */\n\t\t 0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41,\n\t\t 0x64, 0x00, 0x4e, 0x56, 0xff, 0xfa, 0x01, 0x08,\n\t\t 0x2e, 0x2e, 0x00, 0xb6, 0xd0, 0x68, 0x3e, 0x80,\n\t\t 0x2f, 0x0c, 0xa9, 0xfe, 0x64, 0x53, 0x69, 0x7a\n\t\t};", "\n /*\n * See what fonts are used...\n */", " memset(fonts_used, 0, sizeof(fonts_used));\n fonts_used[HeadFootType][HeadFootStyle] = 1;", " for (page = 0; page < (int)num_pages; page ++)\n for (r = pages[page].start; r != NULL; r = r->next)\n if (r->type == RENDER_TEXT)\n\tfonts_used[r->data.text.typeface][r->data.text.style] = 1;", "#ifdef DEBUG\n puts(\"The following fonts were used:\");\n for (i = 0; i < TYPE_MAX; i ++)\n for (j = 0; j < STYLE_MAX; j ++)\n if (fonts_used[i][j])\n printf(\" %s\\n\", _htmlFonts[i][j]);\n#endif // DEBUG", " /*\n * Generate the heading...\n */", " if (PSLevel > 0)\n {\n /*\n * Write PostScript prolog stuff...\n */", " if (XRXComments)\n {\n int start, end;\t// Start and end of document pages...\n int count;\t// Number of exception pages in this range...", "\n // The following comments are Xerox job ticket information that\n // is used on the high-end Laser Printing Systems rather than\n // embedded commands...\n fputs(\"%XRXbegin: 001.0300\\n\", out);\n fputs(\"%XRXPDLformat: PS-Adobe\\n\", out);\n if (doc_title)\n\tfprintf(out, \"%%XRXtitle: %s\\n\", doc_title);", " if (OutputFiles)\n {\n // Output a single chapter...\n\tif (chapter < 0)\n\t{\n\t start = 0;\n\t end = chapter_outstarts[1] - 1;\n\t}\n\telse\n\t{\n\t start = chapter_outstarts[chapter];\n\t end = chapter_outends[chapter];\n\t}\n }\n else\n {\n start = 0;\n\tend = 0;\n }", " if (pages[outpages[start].pages[0]].duplex)\n {\n\tif (pages[outpages[start].pages[0]].landscape)\n\t fputs(\"%XRXrequirements: duplex(tumble)\\n\", out);\n\telse\n\t fputs(\"%XRXrequirements: duplex\\n\", out);\n }\n else\n\tfputs(\"%XRXrequirements: simplex\\n\", out);", " fputs(\"%XRXdisposition: PRINT\\n\", out);\n fputs(\"%XRXsignature: False\\n\", out);\n fprintf(out, \"%%XRXpaperType-size: %.0f %.0f\\n\",\n pages[outpages[start].pages[0]].width * 25.4f / 72.0f,\n pages[outpages[start].pages[0]].length * 25.4f / 72.0f);\n if (pages[outpages[start].pages[0]].media_type[0])\n\tfprintf(out, \"%%XRXpaperType-preFinish: %s 0 0\\n\",\n \tpages[start].media_type);\n if (pages[outpages[start].pages[0]].media_color[0])\n\tfprintf(out, \"%%XRXdocumentPaperColors: %c%s\\n\",\n \ttolower(pages[start].media_color[0]),\n\t\tpages[start].media_color + 1);", " if (OutputFiles)\n {\n // Handle document settings per-chapter...\n\tfor (i = start + 1; i < end; i += count)\n\t{\n\t if (pages[outpages[i].pages[0]].width != pages[0].width ||\n\t pages[outpages[i].pages[0]].length != pages[0].length ||\n\t strcmp(pages[outpages[i].pages[0]].media_type,\n\t pages[0].media_type) != 0 ||\n\t strcmp(pages[outpages[i].pages[0]].media_color,\n\t pages[0].media_color) != 0 ||\n\t pages[outpages[i].pages[0]].duplex != pages[0].duplex)\n\t {\n\t for (count = 1; (i + count) <= end; count ++)\n\t if (pages[outpages[i].pages[0]].width !=\n\t pages[outpages[i + count].pages[0]].width ||\n\t\t pages[outpages[i].pages[0]].length !=\n\t\t pages[outpages[i + count].pages[0]].length ||\n\t\t strcmp(pages[outpages[i].pages[0]].media_type,\n\t\t pages[outpages[i + count].pages[0]].media_type) != 0 ||\n\t\t strcmp(pages[outpages[i].pages[0]].media_color,\n\t\t pages[outpages[i + count].pages[0]].media_color) != 0 ||\n\t\t pages[outpages[i].pages[0]].duplex !=\n\t\t pages[outpages[i + count].pages[0]].duplex)\n\t\tbreak;", "\t fprintf(out, \"%%XRXpageExceptions: %d %d %.0f %.0f %c%s opaque %s 0 0\\n\",\n\t i + 1, i + count,\n\t\t pages[outpages[i].pages[0]].width * 25.4f / 72.0f,\n\t\t pages[outpages[i].pages[0]].length * 25.4f / 72.0f,\n\t\t tolower(pages[outpages[i].pages[0]].media_color[0]),\n\t\t pages[outpages[i].pages[0]].media_color + 1,\n\t\t pages[outpages[i].pages[0]].media_type[0] ?\n\t\t pages[outpages[i].pages[0]].media_type : \"Plain\");", "\t if (pages[outpages[i].pages[0]].duplex &&\n\t pages[outpages[i].pages[0]].landscape)\n\t fprintf(out, \"%%XRXpageExceptions-plex: %d %d duplex(tumble)\\n\",\n\t i + 1, i + count);\n\t else if (pages[outpages[i].pages[0]].duplex)\n\t fprintf(out, \"%%XRXpageExceptions-plex: %d %d duplex\\n\",\n\t i + 1, i + count);\n else\n\t fprintf(out, \"%%XRXpageExceptions-plex: %d %d simplex\\n\",\n\t i + 1, i + count);\n\t }\n\t else\n\t count = 1;\n }\n }\n else\n {\n // All pages are in a single file...\n for (j = (TocLevels == 0); j <= TocDocCount; j ++)\n\t{\n\t start = chapter_outstarts[j];\n\t end = chapter_outends[j];", "\t for (i = start + 1; i < end; i += count)\n\t {\n\t if (pages[outpages[i].pages[0]].width != pages[0].width ||\n\t\tpages[outpages[i].pages[0]].length != pages[0].length ||\n\t\tstrcmp(pages[outpages[i].pages[0]].media_type,\n\t\t pages[0].media_type) != 0 ||\n\t\tstrcmp(pages[outpages[i].pages[0]].media_color,\n\t\t pages[0].media_color) != 0 ||\n\t\tpages[outpages[i].pages[0]].duplex != pages[0].duplex)\n\t {\n\t for (count = 1; (i + count) < end; count ++)\n\t\tif (pages[outpages[i].pages[0]].width !=\n\t\t pages[outpages[i + count].pages[0]].width ||\n\t\t pages[outpages[i].pages[0]].length !=\n\t\t pages[outpages[i + count].pages[0]].length ||\n\t\t strcmp(pages[outpages[i].pages[0]].media_type,\n\t\t pages[outpages[i + count].pages[0]].media_type) != 0 ||\n\t\t strcmp(pages[outpages[i].pages[0]].media_color,\n\t\t pages[outpages[i + count].pages[0]].media_color) != 0 ||\n\t\t pages[outpages[i].pages[0]].duplex !=\n\t\t pages[outpages[i + count].pages[0]].duplex)\n\t\t break;", "\t fprintf(out, \"%%XRXpageExceptions: %d %d %.0f %.0f %c%s opaque %s 0 0\\n\",\n\t i + 1, i + count,\n\t\t pages[outpages[i].pages[0]].width * 25.4f / 72.0f,\n\t\t pages[outpages[i].pages[0]].length * 25.4f / 72.0f,\n\t\t tolower(pages[outpages[i].pages[0]].media_color[0]),\n\t\t pages[outpages[i].pages[0]].media_color + 1,\n\t\t pages[outpages[i].pages[0]].media_type[0] ?\n\t\t pages[outpages[i].pages[0]].media_type : \"Plain\");", "\t if (pages[outpages[i].pages[0]].duplex && pages[outpages[i].pages[0]].landscape)\n\t\tfprintf(out, \"%%XRXpageExceptions-plex: %d %d duplex(tumble)\\n\",\n\t \ti + 1, i + count);\n\t else if (pages[outpages[i].pages[0]].duplex)\n\t\tfprintf(out, \"%%XRXpageExceptions-plex: %d %d duplex\\n\",\n\t \ti + 1, i + count);\n else\n\t\tfprintf(out, \"%%XRXpageExceptions-plex: %d %d simplex\\n\",\n\t \ti + 1, i + count);\n\t }\n\t else\n\t count = 1;\n }\n\t}\n }", " fputs(\"%XRXend\\n\", out);\n }", " fputs(\"%!PS-Adobe-3.0\\n\", out);\n if (Landscape)\n fprintf(out, \"%%%%BoundingBox: 0 0 %d %d\\n\", PageLength, PageWidth);\n else\n fprintf(out, \"%%%%BoundingBox: 0 0 %d %d\\n\", PageWidth, PageLength);\n fprintf(out,\"%%%%LanguageLevel: %d\\n\", PSLevel);\n fputs(\"%%Creator: \" HTMLDOC_PRODUCER \"\\n\", out);\n fprintf(out, \"%%%%CreationDate: D:%04d%02d%02d%02d%02d%02d+0000\\n\",\n doc_date.tm_year + 1900, doc_date.tm_mon + 1, doc_date.tm_mday,\n doc_date.tm_hour, doc_date.tm_min, doc_date.tm_sec);\n if (doc_title != NULL)\n fprintf(out, \"%%%%Title: %s\\n\", doc_title);\n if (author != NULL)\n fprintf(out, \"%%%%Author: %s\\n\", author);\n if (creator != NULL)\n fprintf(out, \"%%%%Generator: %s\\n\", creator);\n if (copyright != NULL)\n fprintf(out, \"%%%%Copyright: %s\\n\", copyright);\n if (keywords != NULL)\n fprintf(out, \"%%%%Keywords: %s\\n\", keywords);\n if (subject != NULL)\n fprintf(out, \"%%%%Subject: %s\\n\", keywords);\n if (page_count > 0)\n fprintf(out, \"%%%%Pages: %d\\n\", page_count);\n else\n fputs(\"%%Pages: (atend)\\n\", out);", " if (!EmbedFonts)\n {\n fputs(\"%%DocumentNeededResources:\\n\", out);", " for (i = 0; i < TYPE_MAX; i ++)\n for (j = 0; j < STYLE_MAX; j ++)\n if (fonts_used[i][j] && _htmlStandardFonts[i])\n fprintf(out, \"%%%%+ font %s\\n\", _htmlFonts[i][j]);\n }", " fputs(\"%%DocumentProvidedResources:\\n\", out);", " for (i = 0; i < TYPE_MAX; i ++)\n for (j = 0; j < STYLE_MAX; j ++)\n if (fonts_used[i][j] && (EmbedFonts || !_htmlStandardFonts[i]))\n fprintf(out, \"%%%%+ font %s\\n\", _htmlFonts[i][j]);\n fputs(\"%%DocumentData: Clean7bit\\n\", out);\n fputs(\"%%EndComments\\n\", out);", " fputs(\"%%BeginProlog\\n\", out);", " /*\n * Embed fonts?\n */", " for (i = 0; i < TYPE_MAX; i ++)\n {\n if (EmbedFonts || !_htmlStandardFonts[i])\n\tfor (j = 0; j < STYLE_MAX; j ++)\n if (fonts_used[i][j])\n\t write_type1(out, (typeface_t)i, (style_t)j);\n }", " /*\n * Procedures used throughout the document...\n */", " const char *version = SVERSION;", " fprintf(out, \"%%%%BeginResource: procset htmldoc-page 1.8 %s\\n\", version + 4);\n fputs(\"/BD{bind def}bind def\", out);\n fputs(\"/B{dup 0 exch rlineto exch 0 rlineto neg 0 exch rlineto\\n\"\n \"closepath stroke}BD\", out);\n fputs(\"/C{setrgbcolor}BD\\n\", out);\n fputs(\"/CM{concat}BD\", out);\n fputs(\"/DF{findfont dup length dict begin{1 index/FID ne{def}{pop pop}\\n\"\n \"ifelse}forall/Encoding fontencoding def currentdict end definefont pop}BD\\n\", out);\n fputs(\"/F{dup 0 exch rlineto exch 0 rlineto neg 0 exch rlineto closepath fill}BD\\n\", out);\n fputs(\"/FS{/hdFontSize exch def}BD\", out);\n fputs(\"/G{setgray}BD\\n\", out);\n fputs(\"/GS{gsave}BD\", out);\n fputs(\"/GR{grestore}BD\", out);\n fputs(\"/J{0 exch ashow}BD\\n\", out);\n fputs(\"/L{0 rlineto stroke}BD\", out);\n fputs(\"/M{moveto}BD\", out);\n fputs(\"/re{4 2 roll moveto 1 index 0 rlineto 0 exch rlineto neg 0 rlineto closepath}BD\\n\", out);\n fputs(\"/RO{rotate}BD\", out);\n fputs(\"/S{show}BD\", out);\n fputs(\"/SC{dup scale}BD\\n\", out);\n fputs(\"/SF{findfont hdFontSize scalefont setfont}BD\", out);\n fputs(\"/SP{showpage}BD\", out);\n fputs(\"/T{translate}BD\\n\", out);\n fputs(\"%%EndResource\\n\", out);", " /*\n * Output the font encoding for the current character set... For now we\n * just support 8-bit fonts since true Unicode support needs a very large\n * number of extra fonts that aren't normally available on a PS printer.\n */", " fputs(\"/fontencoding[\\n\", out);\n for (i = 0, j = 0; i < 256; i ++)\n {\n if (_htmlGlyphs[i])\n j += strlen(_htmlGlyphs[i]) + 1;\n else\n j += 8;", " if (j > 80)\n {\n\tif (_htmlGlyphs[i])\n j = strlen(_htmlGlyphs[i]) + 1;\n\telse\n j = 8;", " putc('\\n', out);\n }", " putc('/', out);\n if (_htmlGlyphs[i])\n fputs(_htmlGlyphs[i], out);\n else\n fputs(\".notdef\", out);\n }", " fputs(\"]def\\n\", out);", " /*\n * Fonts...\n */", " for (i = 0; i < TYPE_MAX; i ++)\n for (j = 0; j < STYLE_MAX; j ++)\n if (fonts_used[i][j])\n {\n\t if (i < TYPE_SYMBOL)\n\t fprintf(out, \"/F%x/%s DF\\n\", i * 4 + j, _htmlFonts[i][j]);\n\t else\n\t fprintf(out, \"/F%x/%s findfont definefont pop\\n\", i * 4 + j,\n\t _htmlFonts[i][j]);\n }", " if (PSCommands)\n {\n snprintf(temp, sizeof(temp), \"%s/data/prolog.ps\", _htmlData);\n if ((prolog = fopen(temp, \"rb\")) != NULL)\n {\n\twhile (fgets(temp, sizeof(temp), prolog) != NULL)\n fputs(temp, out);", "\tfclose(prolog);\n }\n else\n {\n\tprogress_error(HD_ERROR_FILE_NOT_FOUND,\n \"Unable to open data file \\\"%s\\\" - %s\", temp,\n strerror(errno));", "\tfprintf(out, \"%%%%BeginResource: procset htmldoc-device 1.8 %s\\n\", version + 4);\n\tfputs(\"languagelevel 1 eq{/setpagedevice{pop}BD}if\\n\", out);\n\tfputs(\"/SetDuplexMode{<</Duplex 3 index/Tumble 5 index>>setpagedevice \"\n \"pop pop}BD\\n\", out);\n\tfputs(\"/SetMediaColor{pop}BD\\n\", out);\n\tfputs(\"/SetMediaType{pop}BD\\n\", out);\n\tfputs(\"/SetMediaPosition{pop}BD\\n\", out);\n\tfputs(\"/SetPageSize{2 array astore<</PageSize 2 index/ImageableArea \"\n \"null>>setpagedevice pop}BD\\n\", out);\n\tfputs(\"%%EndResource\\n\", out);\n }\n }", " if (background_image != NULL)\n ps_write_background(out);", " fputs(\"%%EndProlog\\n\", out);\n }\n else\n {\n /*\n * Write PDF prolog stuff...\n */", " fprintf(out, \"%%PDF-%.1f\\n\", 0.1 * PDFVersion);\n fputs(\"%\\342\\343\\317\\323\\n\", out);\n num_objects = 0;", " /*\n * Compute the file ID...\n */", " md5_init(&md5);\n md5_append(&md5, (md5_byte_t *)OutputPath, sizeof(OutputPath));\n md5_append(&md5, (md5_byte_t *)&doc_time, sizeof(doc_time));\n md5_finish(&md5, file_id);", " /*\n * Setup encryption stuff as necessary...\n */", " if (Encryption)\n {\n /*\n * Copy and pad the user password...\n */", " strlcpy((char *)user_pad, UserPassword, sizeof(user_pad));", " if ((i = strlen(UserPassword)) < 32)\n\tmemcpy(user_pad + i, pad, (size_t)(32 - i));", " if (OwnerPassword[0])\n {\n /*\n * Copy and pad the owner password...\n\t*/", " strlcpy((char *)owner_pad, OwnerPassword, sizeof(owner_pad));", "\tif ((i = strlen(OwnerPassword)) < 32)\n\t memcpy(owner_pad + i, pad, (size_t)(32 - i));\n }\n else\n {\n /*\n * Generate a pseudo-random owner password...\n\t*/", "\tsrand(time(NULL));", "\tfor (i = 0; i < 32; i ++)\n\t owner_pad[i] = (uchar)rand();\n }", " /*\n * What is the key length?\n *\n * Acrobat 4.0 and earlier (PDF 1.3 and earlier) allow a maximum of\n * 40-bits. Acrobat 5.0 and newer support 128-bits.\n */", " if (PDFVersion > 13)\n encrypt_len = 16;\t// 128 bits\n else\n encrypt_len = 5;\t// 40 bits", " /*\n * Compute the owner key...\n */", " md5_init(&md5);\n md5_append(&md5, owner_pad, 32);\n md5_finish(&md5, digest);", " if (encrypt_len > 5)\n {\n // MD5 the result 50 more times...\n\tfor (i = 0; i < 50; i ++)\n\t{\n md5_init(&md5);\n md5_append(&md5, digest, 16);\n md5_finish(&md5, digest);\n\t}", " // Copy the padded user password...\n memcpy(owner_key, user_pad, 32);", " // Encrypt the result 20 times...\n\tfor (i = 0; i < 20; i ++)\n\t{\n\t // XOR each byte in the key with the loop counter...\n\t for (j = 0; j < encrypt_len; j ++)\n\t encrypt_key[j] = (uchar)(digest[j] ^ i);", " rc4_init(&rc4, encrypt_key, (size_t)encrypt_len);\n rc4_encrypt(&rc4, owner_key, owner_key, 32);\n\t}\n }\n else\n {\n rc4_init(&rc4, digest, (size_t)encrypt_len);\n rc4_encrypt(&rc4, user_pad, owner_key, 32);\n }", " /*\n * Figure out the permissions word; the new N-bit security\n * handler adds several new permission bits, which we must\n * simulate...\n */", " perm_value = (unsigned)Permissions;", " if (encrypt_len > 5)\n {\n // N-bit encryption...\n\tif (!(perm_value & PDF_PERM_COPY))\n\t perm_value &= (unsigned)~0x00240000;\t// Mask additional copy perms...\n }", " /*\n * Compute the encryption key...\n */", " md5_init(&md5);\n md5_append(&md5, user_pad, 32);\n md5_append(&md5, owner_key, 32);", " perm_bytes[0] = (uchar)perm_value;\n perm_bytes[1] = (uchar)(perm_value >> 8);\n perm_bytes[2] = (uchar)(perm_value >> 16);\n perm_bytes[3] = (uchar)(perm_value >> 24);", " md5_append(&md5, perm_bytes, 4);\n md5_append(&md5, file_id, 16);\n md5_finish(&md5, digest);", " if (encrypt_len > 5)\n {\n // MD5 the result 50 times..\n for (i = 0; i < 50; i ++)\n\t{\n\t md5_init(&md5);\n\t md5_append(&md5, digest, 16);\n\t md5_finish(&md5, digest);\n\t}\n }", " memcpy(encrypt_key, digest, (size_t)encrypt_len);", " /*\n * Compute the user key...\n */", " if (encrypt_len > 5)\n {\n md5_init(&md5);\n md5_append(&md5, pad, 32);\n md5_append(&md5, file_id, 16);\n md5_finish(&md5, user_key);", " memset(user_key + 16, 0, 16);", " // Encrypt the result 20 times...\n for (i = 0; i < 20; i ++)\n\t{\n\t // XOR each byte in the key with the loop counter...\n\t for (j = 0; j < encrypt_len; j ++)\n\t digest[j] = (uchar)(encrypt_key[j] ^ i);", " rc4_init(&rc4, digest, (size_t)encrypt_len);\n rc4_encrypt(&rc4, user_key, user_key, 16);\n\t}\n }\n else\n {\n rc4_init(&rc4, encrypt_key, (size_t)encrypt_len);\n rc4_encrypt(&rc4, pad, user_key, 32);\n }", " /*\n * Write the encryption dictionary...\n */", " encrypt_object = pdf_start_object(out);", " fputs(\"/Filter/Standard/O<\", out);\n for (i = 0; i < 32; i ++)\n fprintf(out, \"%02x\", owner_key[i]);\n fputs(\">/U<\", out);\n for (i = 0; i < 32; i ++)\n fprintf(out, \"%02x\", user_key[i]);\n fputs(\">\", out);", " if (encrypt_len > 5)\n {\n // N-bit encryption...\n fprintf(out, \"/P %d/V 2/R 3/Length %d\", (int)perm_value, encrypt_len * 8);\n }\n else\n fprintf(out, \"/P %d/V 1/R 2\", (int)perm_value);", " pdf_end_object(out);\n }\n else\n encrypt_object = 0;", " /*\n * Write info object...\n */", " info_object = pdf_start_object(out);", " fputs(\"/Producer\", out);\n write_string(out, (uchar *)HTMLDOC_PRODUCER, 0);\n fputs(\"/CreationDate\", out);\n snprintf(temp, sizeof(temp), \"D:%04d%02d%02d%02d%02d%02d+0000\",\n doc_date.tm_year + 1900, doc_date.tm_mon + 1, doc_date.tm_mday,\n doc_date.tm_hour, doc_date.tm_min, doc_date.tm_sec);\n write_string(out, (uchar *)temp, 0);", " if (doc_title != NULL)\n {\n fputs(\"/Title\", out);\n write_utf16(out, doc_title);\n }", " if (author != NULL || copyright != NULL)\n {\n if (author && copyright)\n snprintf(temp, sizeof(temp), \"%s, %s\", author, copyright);\n else if (author)\n strlcpy(temp, (const char *)author, sizeof(temp));\n else\n strlcpy(temp, (const char *)copyright, sizeof(temp));", " fputs(\"/Author\", out);\n write_utf16(out, (uchar *)temp);\n }", " if (creator != NULL)\n {\n fputs(\"/Creator\", out);\n write_utf16(out, creator);\n }", " if (keywords != NULL)\n {\n fputs(\"/Keywords\", out);\n write_utf16(out, keywords);\n }", " if (subject != NULL)\n {\n fputs(\"/Subject\", out);\n write_utf16(out, subject);\n }", " pdf_end_object(out);", " /*\n * Write the font encoding for the selected character set. Note that\n * we *should* be able to use the WinAnsiEncoding value for ISO-8859-1\n * to make smaller files, however Acrobat Exchange does not like it\n * despite the fact that it is defined in the PDF specification...\n */", " encoding_object = pdf_start_object(out);", " fputs(\"/Type/Encoding\", out);\n fputs(\"/Differences[\", out);\n for (i = 0, j = -1; i < 256; i ++)\n if (_htmlGlyphs[i])\n {\n /*\n * Output a character index if we had blank ones...\n\t*/", " if (j != (i - 1))\n\t fprintf(out, \" %d\", i);", " fprintf(out, \"/%s\", _htmlGlyphs[i]);\n\tj = i;\n }", " fputs(\"]\", out);\n pdf_end_object(out);", " memset(font_desc, 0, sizeof(font_desc));", " /*\n * Build font descriptors for the EmbedFonts fonts...\n */", " for (i = 0; i < TYPE_MAX; i ++)\n if (EmbedFonts || !_htmlStandardFonts[i])\n\tfor (j = 0; j < STYLE_MAX; j ++)\n if (fonts_used[i][j])\n\t font_desc[i][j] = write_type1(out, (typeface_t )i, (style_t)j);", " for (i = 0; i < TYPE_MAX; i ++)\n for (j = 0; j < STYLE_MAX; j ++)\n if (fonts_used[i][j])\n {\n\t font_objects[i * STYLE_MAX + j] = pdf_start_object(out);", "\t fputs(\"/Type/Font\", out);\n\t fputs(\"/Subtype/Type1\", out);\n\t fprintf(out, \"/BaseFont/%s\", _htmlFonts[i][j]);", " if (font_desc[i][j])\n\t {\n\t // Embed Type1 font...\n\t fputs(\"/FirstChar 0\", out);\n\t fputs(\"/LastChar 255\", out);\n\t fprintf(out, \"/Widths %d 0 R\", font_desc[i][j] + 1);\n\t fprintf(out, \"/FontDescriptor %d 0 R\", font_desc[i][j]);\n\t }", "\t if (i < TYPE_SYMBOL) /* Use native encoding for symbols */\n\t fprintf(out, \"/Encoding %d 0 R\", encoding_object);", " pdf_end_object(out);\n }\n }\n}", "\n/*\n * 'write_string()' - Write a text entity.\n */", "static void\nwrite_string(FILE *out,\t\t/* I - Output file */\n uchar *s,\t\t\t/* I - String */\n\t int compress)\t\t/* I - Compress output? */\n{\n int\ti;\t\t\t\t/* Looping var */", "\n if (Encryption && !compress && PSLevel == 0)\n {\n int\t\tlen,\t\t\t// Length of string\n\t\tbytes;\t\t\t// Current bytes encrypted\n uchar\tnews[1024];\t\t// New string", "\n /*\n * Write an encrypted string...\n */", " putc('<', out);\n encrypt_init();", " for (len = strlen((char *)s); len > 0; len -= bytes, s += bytes)\n {\n if (len > (int)sizeof(news))\n bytes = (int)sizeof(news);\n else\n bytes = len;", " rc4_encrypt(&encrypt_state, s, news, (size_t)bytes);", " for (i = 0; i < bytes; i ++)\n fprintf(out, \"%02x\", news[i]);\n }", " putc('>', out);\n }\n else\n {\n uchar nbsp = 160;\t\t\t// Non-breaking space char", " if (compress)\n flate_write(out, (uchar *)\"(\", 1);\n else\n putc('(', out);", " if (_htmlUTF8)\n nbsp = _htmlCharacters[160];", " while (*s != '\\0')\n {\n if (*s == nbsp)\n {\n /* &nbsp; */\n\tif (compress)\n\t flate_write(out, (uchar *)\" \", 1);\n\telse\n\t putc(' ', out);\n }\n else if (*s < 32 || *s > 126)\n {\n\tif (compress)\n\t flate_printf(out, \"\\\\%o\", *s);\n\telse\n\t fprintf(out, \"\\\\%o\", *s);\n }\n else if (compress)\n {\n\tif (*s == '(' || *s == ')' || *s == '\\\\')\n\t flate_write(out, (uchar *)\"\\\\\", 1);", "\tflate_write(out, s, 1);\n }\n else\n {\n\tif (*s == '(' || *s == ')' || *s == '\\\\')\n\t putc('\\\\', out);", "\tputc(*s, out);\n }", " s ++;\n }", " if (compress)\n flate_write(out, (uchar *)\")\", 1);\n else\n putc(')', out);\n }\n}", "\n/*\n * 'write_text()' - Write a text entity.\n */", "static void\nwrite_text(FILE *out,\t/* I - Output file */\n render_t *r)\t\t/* I - Text entity */\n{\n uchar\t*ptr;\t\t\t/* Pointer into text */", "\n // Quick optimization - don't output spaces...\n for (ptr = r->data.text.buffer; *ptr; ptr ++)\n if (!isspace(*ptr) && *ptr != 0xa0)\n break;", " if (!*ptr)\n return;", " // Not just whitespace - send it out...\n set_color(out, r->data.text.rgb);\n set_font(out, r->data.text.typeface, r->data.text.style, r->data.text.size);\n set_pos(out, r->x, r->y);", " if (PSLevel > 0)\n {\n if (r->data.text.spacing > 0.0f)\n fprintf(out, \" %.3f\", r->data.text.spacing);\n }\n else if (r->data.text.spacing != render_spacing)\n flate_printf(out, \" %.3f Tc\", render_spacing = r->data.text.spacing);", " write_string(out, r->data.text.buffer, PSLevel == 0);", " if (PSLevel > 0)\n {\n if (r->data.text.spacing > 0.0f)\n fputs(\"J\\n\", out);\n else\n fputs(\"S\\n\", out);\n }\n else\n flate_puts(\"Tj\\n\", out);", " render_x += r->width;\n}", "\n/*\n * 'write_trailer()' - Write the file trailer.\n */", "static void\nwrite_trailer(FILE *out,\t\t/* I - Output file */\n int num_file_pages,\t/* I - Number of pages in file */\n\t uchar *lang)\t\t/* I - Language */\n{\n int\t\ti, j, k,\t\t/* Looping vars */\n\t\ttype,\t\t\t/* Type of number */\n\t\toffset,\t\t\t/* Offset to xref table in PDF file */\n\t\tstart;\t\t\t/* Start page number */\n page_t\t*page;\t\t\t/* Start page of chapter */\n char\t\tprefix[64],\t\t/* Prefix string */\n\t\t*prefptr;\t\t/* Pointer into prefix string */\n static const char *modes[] =\t\t/* Page modes */\n\t\t{\n\t\t \"UseNone\",\n\t\t \"UseOutlines\",\n\t\t \"FullScreen\"\n\t\t};\n static const char *layouts[] =\t/* Page layouts */\n\t\t{\n\t\t \"SinglePage\",\n\t\t \"OneColumn\",\n\t\t \"TwoColumnLeft\",\n\t\t \"TwoColumnRight\"\n\t\t};", "\n if (PSLevel > 0)\n {\n /*\n * PostScript...\n */", " fputs(\"%%Trailer\\n\", out);\n if (num_file_pages > 0)\n fprintf(out, \"%%%%Pages: %d\\n\", num_file_pages);", " fputs(\"%%EOF\\n\", out);\n }\n else\n {\n /*\n * PDF...\n */", " root_object = pdf_start_object(out);", " fputs(\"/Type/Catalog\", out);\n fprintf(out, \"/Pages %d 0 R\", pages_object);", " if (PDFVersion >= 12)\n {\n if (names_object)\n fprintf(out, \"/Names %d 0 R\", names_object);", " fprintf(out, \"/PageLayout/%s\", layouts[PDFPageLayout]);\n }", " if (lang)\n fprintf(out, \"/Lang(%s)\", (char *)lang);", " if (outline_object > 0)\n fprintf(out, \"/Outlines %d 0 R\", outline_object);", " switch (PDFFirstPage)\n {\n case PDF_PAGE_1 :\n if (TitlePage)\n\t {\n fprintf(out, \"/OpenAction[%d 0 R/XYZ null null 0]\",\n pages_object + 1);\n break;\n\t }\n break;\n case PDF_TOC :\n if (TocLevels > 0)\n\t {\n fprintf(out, \"/OpenAction[%d 0 R/XYZ null null 0]\",\n pages_object + 2 * chapter_outstarts[0] + 1);\n\t break;\n\t }\n break;\n case PDF_CHAPTER_1 :\n fprintf(out, \"/OpenAction[%d 0 R/XYZ null null 0]\",\n pages_object + 2 * chapter_outstarts[1] + 1);\n break;\n }", " fprintf(out, \"/PageMode/%s\", modes[PDFPageMode]);", " if (PDFVersion > 12 && NumberUp == 1)\n {\n // Output the PageLabels tree...\n fputs(\"/PageLabels<</Nums[\", out);", " for (i = 0; i < chapter_starts[1]; i ++)\n {\n fprintf(out, \"%d<</P\", i);\n if (i & 1)\n\t write_string(out, (uchar *)\"eltit\", 0);\n\telse\n\t write_string(out, (uchar *)\"title\", 0);\n\tfputs(\">>\", out);\n }", " if (TocLevels > 0 && OutputType == OUTPUT_BOOK)\n {\n type = 'r';", " for (j = 0; j < 3; j ++)\n\t if ((TocHeader[j] && strstr(TocHeader[j], \"$PAGE(1)\")) ||\n\t (TocFooter[j] && strstr(TocFooter[j], \"$PAGE(1)\")))\n\t type = 'D';\n\t else if ((TocHeader[j] && strstr(TocHeader[j], \"$PAGE(I)\")) ||\n\t (TocFooter[j] && strstr(TocFooter[j], \"$PAGE(I)\")))\n\t type = 'R';\n\t else if ((TocHeader[j] && strstr(TocHeader[j], \"$PAGE(a)\")) ||\n\t (TocFooter[j] && strstr(TocFooter[j], \"$PAGE(a)\")))\n\t type = 'a';\n\t else if ((TocHeader[j] && strstr(TocHeader[j], \"$PAGE(A)\")) ||\n\t (TocFooter[j] && strstr(TocFooter[j], \"$PAGE(A)\")))\n\t type = 'A';", " fprintf(out, \"%d<</S/%c>>\", i, type);", " i += chapter_ends[0] - chapter_starts[0] + 1;\n }", " for (j = 1; j <= TocDocCount; j ++)\n {\n if (chapter_starts[j] < 0)\n continue;", " page = pages + chapter_starts[j];\n\tstart = chapter_starts[j] - chapter_starts[1] + 1;\n\ttype = 'D';", " prefix[0] = '\\0';", "\tfor (k = 0; k < 3; k ++)\n\t{\n\t if (page->header[k] && strstr((char *)page->header[k], \"PAGE\"))\n\t strlcpy(prefix, (char *)page->header[k], sizeof(prefix));\n\t else if (page->footer[k] && strstr((char *)page->footer[k], \"PAGE\"))\n\t strlcpy(prefix, (char *)page->footer[k], sizeof(prefix));", "\t if ((page->header[k] && strstr((char *)page->header[k], \"PAGE(i)\")) ||\n\t (page->footer[k] && strstr((char *)page->footer[k], \"PAGE(i)\")))\n\t type = 'r';\n\t else if ((page->header[k] && strstr((char *)page->header[k], \"PAGE(I)\")) ||\n\t (page->footer[k] && strstr((char *)page->footer[k], \"PAGE(I)\")))\n\t type = 'R';\n\t else if ((page->header[k] && strstr((char *)page->header[k], \"PAGE(a)\")) ||\n\t (page->footer[k] && strstr((char *)page->footer[k], \"PAGE(a)\")))\n\t type = 'a';\n\t else if ((page->header[k] && strstr((char *)page->header[k], \"PAGE(A)\")) ||\n\t (page->footer[k] && strstr((char *)page->footer[k], \"PAGE(A)\")))\n\t type = 'A';", "\t if ((page->header[k] && strstr((char *)page->header[k], \"$CHAPTERPAGE\")) ||\n\t (page->footer[k] && strstr((char *)page->footer[k], \"$CHAPTERPAGE\")))\n\t start = 1;\n }", " if ((prefptr = strstr(prefix, \"$PAGE\")) == NULL)\n\t prefptr = strstr(prefix, \"$CHAPTERPAGE\");\n\tfprintf(out, \"%d<</S/%c/St %d\", i, type, start);\n\tif (prefptr)\n\t{\n\t *prefptr = '\\0';\n\t fputs(\"/P\", out);\n\t write_string(out, (uchar *)prefix, 0);\n\t}\n\tfputs(\">>\", out);", " i += chapter_ends[j] - chapter_starts[j] + 1;\n }", " fputs(\"]>>\", out);\n }", " pdf_end_object(out);", " offset = ftell(out);", " fputs(\"xref\\n\", out);\n fprintf(out, \"0 %d \\n\", (int)num_objects + 1);\n fputs(\"0000000000 65535 f \\n\", out);\n for (i = 1; i <= (int)num_objects; i ++)\n fprintf(out, \"%010d 00000 n \\n\", objects[i]);", " fputs(\"trailer\\n\", out);\n fputs(\"<<\", out);\n fprintf(out, \"/Size %d\", (int)num_objects + 1);\n fprintf(out, \"/Root %d 0 R\", root_object);\n fprintf(out, \"/Info %d 0 R\", info_object);\n fputs(\"/ID[<\", out);\n for (i = 0; i < 16; i ++)\n fprintf(out, \"%02x\", file_id[i]);\n fputs(\"><\", out);\n for (i = 0; i < 16; i ++)\n fprintf(out, \"%02x\", file_id[i]);\n fputs(\">]\", out);", " if (Encryption)\n fprintf(out, \"/Encrypt %d 0 R\", encrypt_object);", " fputs(\">>\\n\", out);\n fputs(\"startxref\\n\", out);\n fprintf(out, \"%d\\n\", offset);\n fputs(\"%%EOF\\n\", out);\n }\n}", "\n/*\n * 'write_type1()' - Write an embedded Type 1 font.\n */", "static int\t\t\t\t/* O - Object number */\nwrite_type1(FILE *out,\t\t/* I - File to write to */\n typeface_t typeface,\t/* I - Typeface */\n\t style_t style)\t\t/* I - Style */\n{\n char\t\tfilename[1024];\t\t/* PFA filename */\n FILE\t\t*fp;\t\t\t/* PFA file */\n int\t\tch;\t\t\t/* Character value */\n int\t\twidth;\t\t\t/* Width value */\n char\t\tglyph[64],\t\t/* Glyph name */\n\t\tline[1024],\t\t/* Line from AFM file */\n\t\t*lineptr,\t\t/* Pointer into line */\n\t\t*dataptr;\t\t/* Pointer for data */\n int\t\tascent,\t\t\t/* Ascent above baseline */\n\t\tcap_height,\t\t/* Ascent of CAPITALS */\n\t\tx_height,\t\t/* Ascent of lowercase */\n\t\tdescent,\t\t/* Decent below baseline */\n\t\tbbox[4],\t\t/* Bounding box */\n\t\titalic_angle;\t\t/* Angle for italics */\n int\t\twidths[256];\t\t/* Character widths */\n int\t\tlength1,\t\t/* Length1 value for font */\n\t\tlength2,\t\t/* Length2 value for font */\n\t\tlength3;\t\t/* Length3 value for font */\n static int\ttflags[] =\t\t/* PDF typeface flags */\n\t\t{\n\t\t 33,\t\t\t/* Courier */\n\t\t 34,\t\t\t/* Times-Roman */\n\t\t 32,\t\t\t/* Helvetica */\n\t\t 33,\t\t\t/* Monospace */\n\t\t 34,\t\t\t/* Serif */\n\t\t 32,\t\t\t/* Sans */\n\t\t 4,\t\t\t/* Symbol */\n\t\t 4\t\t\t/* Dingbats */\n\t\t};\n static int\tsflags[] =\t\t/* PDF style flags */\n\t\t{\n\t\t 0,\t\t\t/* Normal */\n\t\t 0,\t\t\t/* Bold */\n\t\t 64,\t\t\t/* Italic */\n\t\t 64\t\t\t/* Bold-Italic */\n\t\t};", "\n /*\n * This function writes a Type1 font, either as an object for PDF\n * output or as an in-line font in PostScript output. This is useful\n * because the Type1 fonts that Adobe ships typically do not include\n * the full set of characters required by some of the ISO character\n * sets.\n */", " /*\n * Try to open the PFA file for the Type1 font...\n */", " snprintf(filename, sizeof(filename), \"%s/fonts/%s.pfa\", _htmlData,\n _htmlFonts[typeface][style]);\n if ((fp = fopen(filename, \"r\")) == NULL)\n {\n#ifndef DEBUG\n progress_error(HD_ERROR_FILE_NOT_FOUND,\n \"Unable to open font file %s!\", filename);\n#endif /* !DEBUG */\n return (0);\n }", " /*\n * Write the font (object)...\n */", " if (PSLevel)\n {\n /*\n * Embed a Type1 font in the PostScript output...\n */", " fprintf(out, \"%%%%BeginResource: font %s\\n\", _htmlFonts[typeface][style]);", " line[0] = '\\0';", " while (fgets(line, sizeof(line), fp) != NULL)\n fputs(line, out);", " if (line[strlen(line) - 1] != '\\n')\n fputs(\"\\n\", out);", " fputs(\"%%EndResource\\n\", out);", " fclose(fp);\n }\n else\n {\n /*\n * Embed a Type1 font object in the PDF output...\n */", " length1 = 0;\n length2 = 0;\n length3 = 0;", " while (fgets(line, sizeof(line), fp) != NULL)\n {\n length1 += strlen(line);\n if (strstr(line, \"currentfile eexec\") != NULL)\n break;\n }", " while (fgets(line, sizeof(line), fp) != NULL)\n {\n if (!strcmp(line, \"00000000000000000000000000000000\"\n \"00000000000000000000000000000000\\n\"))\n break;", " length2 += (strlen(line) - 1) / 2;\n }", " length3 = strlen(line);\n while (fgets(line, sizeof(line), fp) != NULL)\n length3 += strlen(line);", " rewind(fp);", " pdf_start_object(out);\n fprintf(out, \"/Length1 %d\", length1);\n fprintf(out, \"/Length2 %d\", length2);\n fprintf(out, \"/Length3 %d\", length3);\n if (Compression)\n fputs(\"/Filter/FlateDecode\", out);\n pdf_start_stream(out);\n flate_open_stream(out);", " while (fgets(line, sizeof(line), fp) != NULL)\n {\n flate_puts(line, out);", " if (strstr(line, \"currentfile eexec\") != NULL)\n break;\n }", " while (fgets(line, sizeof(line), fp) != NULL)\n {\n if (!strcmp(line, \"00000000000000000000000000000000\"\n \"00000000000000000000000000000000\\n\"))\n break;", " for (lineptr = line, dataptr = line; isxdigit(*lineptr); lineptr += 2)\n {\n if (isdigit(lineptr[0]))\n\t ch = (lineptr[0] - '0') << 4;\n\telse\n\t ch = (tolower(lineptr[0] & 255) - 'a' + 10) << 4;", " if (isdigit(lineptr[1]))\n\t ch |= lineptr[1] - '0';\n\telse\n\t ch |= tolower(lineptr[1] & 255) - 'a' + 10;", " *dataptr++ = (char)ch;\n }", " flate_write(out, (uchar *)line, dataptr - line);\n }", " flate_puts(line, out);\n while (fgets(line, sizeof(line), fp) != NULL)\n flate_puts(line, out);", " flate_close_stream(out);", " pdf_end_object(out);", " fclose(fp);", " /*\n * Try to open the AFM file for the Type1 font...\n */", " snprintf(filename, sizeof(filename), \"%s/fonts/%s.afm\", _htmlData,\n _htmlFonts[typeface][style]);\n if ((fp = fopen(filename, \"r\")) == NULL)\n {\n#ifndef DEBUG\n progress_error(HD_ERROR_FILE_NOT_FOUND,\n \"Unable to open font width file %s!\", filename);\n#endif /* !DEBUG */\n return (0);\n }", " /*\n * Set the default values (Courier)...\n */", " for (ch = 0; ch < 256; ch ++)\n widths[ch] = 600;", " ascent = 629;\n cap_height = 562;\n x_height = 426;\n descent = -157;\n bbox[0] = -28;\n bbox[1] = -250;\n bbox[2] = 628;\n bbox[3] = 805;\n italic_angle = 0;", " /*\n * Read the AFM file...\n */", " while (fgets(line, sizeof(line), fp) != NULL)\n {\n if (strncmp(line, \"ItalicAngle \", 12) == 0)\n\titalic_angle = atoi(line + 12);\n else if (strncmp(line, \"FontBBox \", 9) == 0)\n\tsscanf(line + 9, \"%d%d%d%d\", bbox + 0, bbox + 1, bbox + 2, bbox + 3);\n else if (strncmp(line, \"CapHeight \", 10) == 0)\n\tcap_height = atoi(line + 10);\n else if (strncmp(line, \"XHeight \", 8) == 0)\n\tx_height = atoi(line + 8);\n else if (strncmp(line, \"Ascender \", 9) == 0)\n\tascent = atoi(line + 9);\n else if (strncmp(line, \"Descender \", 10) == 0)\n\tdescent = atoi(line + 10);\n else if (strncmp(line, \"C \", 2) == 0)\n {\n\tif (typeface < TYPE_SYMBOL)\n\t{\n\t /*\n\t * Handle encoding of Courier, Times, and Helvetica using\n\t * assigned charset...\n\t */", "\t if (sscanf(line, \"%*s%*s%*s%*s%d%*s%*s%63s\", &width, glyph) != 2)\n\t continue;", "\t for (ch = 0; ch < 256; ch ++)\n\t if (_htmlGlyphs[ch] && strcmp(_htmlGlyphs[ch], glyph) == 0)\n\t break;", "\t if (ch < 256)\n\t widths[ch] = width;\n\t}\n\telse\n\t{\n\t /*\n\t * Symbol font uses its own encoding...\n\t */", "\t if (sscanf(line, \"%*s%d%*s%*s%d\", &ch, &width) != 2)\n\t continue;", "\t if (ch >= 0 && ch < 256)\n\t widths[ch] = width;\n\t}\n }\n }", " fclose(fp);", " /*\n * Write the font descriptor...\n */", " pdf_start_object(out);\n fputs(\"/Type/FontDescriptor\", out);\n fprintf(out, \"/Ascent %d\", ascent);\n fprintf(out, \"/Descent %d\", descent);\n fprintf(out, \"/CapHeight %d\", cap_height);\n fprintf(out, \"/XHeight %d\", x_height);\n fprintf(out, \"/FontBBox[%d %d %d %d]\", bbox[0], bbox[1], bbox[2], bbox[3]);\n fprintf(out, \"/ItalicAngle %d\", italic_angle);\n fprintf(out, \"/StemV %d\", widths['v']);\n fprintf(out, \"/Flags %d\", tflags[typeface] | sflags[style]);\n fprintf(out, \"/FontName/%s\", _htmlFonts[typeface][style]);\n fprintf(out, \"/FontFile %d 0 R\", (int)num_objects - 1);\n pdf_end_object(out);", " /*\n * Write the character widths...\n */", " pdf_start_object(out, 1);\n fprintf(out, \"%d\", widths[0]);\n for (ch = 1; ch < 256; ch ++)\n fprintf(out, \" %d\", widths[ch]);\n pdf_end_object(out);\n }", " /*\n * Return the font descriptor...\n */", " return (num_objects - 1);\n}", "\n/*\n * 'write_utf16()' - Write a UTF-16 string...\n */", "static void\nwrite_utf16(FILE *out,\t\t\t// I - File to write to\n uchar *s)\t\t\t// I - String to write\n{\n uchar *sptr;\t\t\t\t// Pointer into string", "\n /*\n * We start by checking to see if the string is composed only of\n * ASCII characters; if so, we can just write a normal string...\n */", " for (sptr = s; *sptr && !(*sptr & 0x80); sptr ++);\n if (!*sptr)\n {\n /*\n * Write an ASCII string...\n */", " write_string(out, s, 0);\n }\n else if (Encryption)\n {\n /*\n * Convert the string to Unicode and encrypt...\n */", " int\t\tch;\t\t\t// Character value\n uchar\tunicode[2],\t\t// Unicode character\n\t\tenicode[2];\t\t// Encrypted unicode character", "\n putc('<', out);\n encrypt_init();", " unicode[0] = 0xfe;\t\t\t// Start with BOM\n unicode[1] = 0xff;", " rc4_encrypt(&encrypt_state, unicode, enicode, 2);", " fprintf(out, \"%02x%02x\", enicode[0], enicode[1]);", " for (sptr = s; *sptr; sptr ++)\n {\n ch = _htmlUnicode[*sptr];\n unicode[0] = (uchar)(ch >> 8);\n unicode[1] = (uchar)ch;", " rc4_encrypt(&encrypt_state, unicode, enicode, 2);", " fprintf(out, \"%02x%02x\", enicode[0], enicode[1]);\n }", " putc('>', out);\n }\n else\n {\n /*\n * Convert the string to Unicode...\n */", " fputs(\"<feff\", out);\t\t// Start with BOM\n for (sptr = s; *sptr; sptr ++)\n fprintf(out, \"%04x\", _htmlUnicode[*sptr]);\n putc('>', out);\n }\n}", "\n/*\n * 'encrypt_init()' - Initialize the RC4 encryption context for the current\n * object.\n */", "static void\nencrypt_init(void)\n{\n int\t\ti;\t\t\t/* Looping var */\n uchar\t\tdata[21],\t\t/* Key data */\n\t\t*dataptr;\t\t/* Pointer to key data */\n md5_state_t\tmd5;\t\t\t/* MD5 state */\n md5_byte_t\tdigest[16];\t\t/* MD5 digest value */", "\n /*\n * Compute the key data for the MD5 hash.\n */", " for (i = 0, dataptr = data; i < encrypt_len; i ++)\n *dataptr++ = encrypt_key[i];", " *dataptr++ = (uchar)num_objects;\n *dataptr++ = (uchar)(num_objects >> 8);\n *dataptr++ = (uchar)(num_objects >> 16);\n *dataptr++ = 0;\n *dataptr++ = 0;", " /*\n * Hash it...\n */", " md5_init(&md5);\n md5_append(&md5, data, encrypt_len + 5);\n md5_finish(&md5, digest);", " /*\n * Initialize the RC4 context using the first N+5 bytes of the digest...\n */", " if (encrypt_len > 11)\n rc4_init(&encrypt_state, digest, 16);\n else\n rc4_init(&encrypt_state, digest, (size_t)(encrypt_len + 5));\n}", "\n/*\n * 'flate_open_stream()' - Open a deflated output stream.\n */", "static void\nflate_open_stream(FILE *out)\t\t/* I - Output file */\n{\n if (Encryption && !PSLevel)\n encrypt_init();", " if (!Compression)\n return;", " compressor_active = 1;\n compressor.zalloc = (alloc_func)0;\n compressor.zfree = (free_func)0;\n compressor.opaque = (voidpf)0;", " deflateInit(&compressor, Compression);", " compressor.next_out = (Bytef *)comp_buffer;\n compressor.avail_out = sizeof(comp_buffer);\n}", "\n/*\n * 'flate_close_stream()' - Close a deflated output stream.\n */", "static void\nflate_close_stream(FILE *out)\t\t/* I - Output file */\n{\n int\tstatus;\t\t\t\t/* Deflate status */", "\n if (!Compression)\n {\n#ifdef HTMLDOC_ASCII85\n if (PSLevel)\n ps_ascii85(out, (uchar *)\"\", 0, 1);\n#endif // HTMLDOC_ASCII85", " return;\n }", " while ((status = deflate(&compressor, Z_FINISH)) != Z_STREAM_END)\n {\n if (status < Z_OK && status != Z_BUF_ERROR)\n {\n progress_error(HD_ERROR_OUT_OF_MEMORY, \"deflate() failed (%d)\", status);\n return;\n }", " if (PSLevel)\n#ifdef HTMLDOC_ASCII85\n ps_ascii85(out, comp_buffer,\n (uchar *)compressor.next_out - (uchar *)comp_buffer);\n#else\n ps_hex(out, comp_buffer,\n (uchar *)compressor.next_out - (uchar *)comp_buffer);\n#endif // HTMLDOC_ASCII85\n else\n {\n if (Encryption)\n rc4_encrypt(&encrypt_state, comp_buffer, comp_buffer,\n\t (uchar *)compressor.next_out - (uchar *)comp_buffer);", " fwrite(comp_buffer, (size_t)((uchar *)compressor.next_out - (uchar *)comp_buffer), 1, out);\n }", " compressor.next_out = (Bytef *)comp_buffer;\n compressor.avail_out = sizeof(comp_buffer);\n }", " if ((uchar *)compressor.next_out > (uchar *)comp_buffer)\n {\n if (PSLevel)\n#ifdef HTMLDOC_ASCII85\n ps_ascii85(out, comp_buffer,\n (uchar *)compressor.next_out - (uchar *)comp_buffer);\n#else\n ps_hex(out, comp_buffer,\n (uchar *)compressor.next_out - (uchar *)comp_buffer);\n#endif // HTMLDOC_ASCII85\n else\n {\n if (Encryption)\n rc4_encrypt(&encrypt_state, comp_buffer, comp_buffer,\n\t (uchar *)compressor.next_out - (uchar *)comp_buffer);", " fwrite(comp_buffer, (size_t)((uchar *)compressor.next_out - (uchar *)comp_buffer), 1, out);\n }", " }", " deflateEnd(&compressor);", " compressor_active = 0;", "#ifdef HTMLDOC_ASCII85\n if (PSLevel)\n ps_ascii85(out, (uchar *)\"\", 0, 1);\n#else\n if (PSLevel)\n {\n // End of data marker...\n fputs(\">\\n\", out);\n }\n#endif // HTMLDOC_ASCII85\n}", "\n/*\n * 'flate_puts()' - Write a character string to a compressed stream.\n */", "static void\nflate_puts(const char *s,\t\t/* I - String to write */\n FILE *out)\t\t/* I - Output file */\n{\n flate_write(out, (uchar *)s, strlen(s));\n}", "\n/*\n * 'flate_printf()' - Write a formatted character string to a compressed stream.\n */", "static void\nflate_printf(FILE *out,\t\t/* I - Output file */\n const char *format,\t/* I - Format string */\n ...)\t\t\t/* I - Additional args as necessary */\n{\n int\t\tlength;\t\t\t/* Length of output string */\n char\t\tbuf[10240];\t\t/* Output buffer */\n va_list\tap;\t\t\t/* Argument pointer */", "\n va_start(ap, format);\n length = vsnprintf(buf, sizeof(buf), format, ap);\n va_end(ap);", " flate_write(out, (uchar *)buf, length);\n}", "\n/*\n * 'flate_write()' - Write data to a compressed stream.\n */", "static void\nflate_write(FILE *out,\t\t\t/* I - Output file */\n uchar *buf,\t\t\t/* I - Buffer */\n int length,\t\t/* I - Number of bytes to write */\n\t int flush)\t\t/* I - Flush when writing data? */\n{\n int\tstatus;\t\t\t\t/* Deflate status */", "\n if (compressor_active)\n {\n compressor.next_in = buf;\n compressor.avail_in = (unsigned)length;", " while (compressor.avail_in > 0)\n {\n if (compressor.avail_out < (int)(sizeof(comp_buffer) / 8))\n {\n\tif (PSLevel)\n#ifdef HTMLDOC_ASCII85\n\t ps_ascii85(out, comp_buffer,\n (uchar *)compressor.next_out - (uchar *)comp_buffer);\n#else\n\t ps_hex(out, comp_buffer,\n (uchar *)compressor.next_out - (uchar *)comp_buffer);\n#endif // HTMLDOC_ASCII85\n\telse\n\t{\n\t if (Encryption)\n rc4_encrypt(&encrypt_state, comp_buffer, comp_buffer,\n\t \t(uchar *)compressor.next_out - (uchar *)comp_buffer);", "\t fwrite(comp_buffer, (size_t)((uchar *)compressor.next_out - (uchar *)comp_buffer), 1, out);\n\t}", "\tcompressor.next_out = (Bytef *)comp_buffer;\n\tcompressor.avail_out = sizeof(comp_buffer);\n }", " status = deflate(&compressor, flush ? Z_FULL_FLUSH : Z_NO_FLUSH);", " if (status < Z_OK && status != Z_BUF_ERROR)\n {\n\tprogress_error(HD_ERROR_OUT_OF_MEMORY, \"deflate() failed (%d)\", status);\n\treturn;\n }", " flush = 0;\n }\n }\n else if (Encryption && !PSLevel)\n {\n int\t\ti,\t\t// Looping var\n\t\tbytes;\t\t// Number of bytes to encrypt/write\n uchar\tnewbuf[1024];\t// New encrypted data buffer", "\n for (i = 0; i < length; i += sizeof(newbuf))\n {\n if ((bytes = length - i) > (int)sizeof(newbuf))\n bytes = sizeof(newbuf);", " rc4_encrypt(&encrypt_state, buf + i, newbuf, (size_t)bytes);\n fwrite(newbuf, (size_t)bytes, 1, out);\n }\n }\n else if (PSLevel)\n#ifdef HTMLDOC_ASCII85\n ps_ascii85(out, buf, length);\n#else\n ps_hex(out, buf, length);\n#endif // HTMLDOC_ASCII85\n else\n fwrite(buf, (size_t)length, 1, out);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [5, 1322], "buggy_code_start_loc": [4, 1321], "filenames": ["CHANGES.md", "htmldoc/ps-pdf.cxx"], "fixing_code_end_loc": [6, 1322], "fixing_code_start_loc": [4, 1321], "message": "A flaw was found in htmldoc before v1.9.12. Heap buffer overflow in pspdf_prepare_outpages(), in ps-pdf.cxx may lead to execute arbitrary code and denial of service.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:htmldoc_project:htmldoc:*:*:*:*:*:*:*:*", "matchCriteriaId": "8D1CE1F4-17A1-430E-9C8B-0CE88A07514B", "versionEndExcluding": "1.9.12", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:htmldoc_project:htmldoc:1.9.12:*:*:*:*:*:*:*", "matchCriteriaId": "645554AD-DA7C-4B11-864A-89F423B08291", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A flaw was found in htmldoc before v1.9.12. Heap buffer overflow in pspdf_prepare_outpages(), in ps-pdf.cxx may lead to execute arbitrary code and denial of service."}, {"lang": "es", "value": "Se ha encontrado un fallo en htmldoc versiones anteriores av1.9.12. Un desbordamiento del b\u00fafer de la pila en la funci\u00f3n pspdf_prepare_outpages(), en el archivo ps-pdf.cxx puede conllevar a una ejecuci\u00f3n de c\u00f3digo arbitrario y a una denegaci\u00f3n de servicio"}], "evaluatorComment": null, "id": "CVE-2021-23165", "lastModified": "2022-03-22T17:01:58.600", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 10.0, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:L/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-03-16T15:15:10.157", "references": [{"source": "secalert@redhat.com", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1967014"}, {"source": "secalert@redhat.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/michaelrsweet/htmldoc/commit/6e8a95561988500b5b5ae4861b3b0cbf4fba517f"}, {"source": "secalert@redhat.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://github.com/michaelrsweet/htmldoc/commit/6e8a95561988500b5b5ae4861b3b0cbf4fba517f.patch"}, {"source": "secalert@redhat.com", "tags": ["Exploit", "Issue Tracking", "Third Party Advisory"], "url": "https://github.com/michaelrsweet/htmldoc/issues/413"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-787"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-122"}], "source": "secalert@redhat.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/michaelrsweet/htmldoc/commit/6e8a95561988500b5b5ae4861b3b0cbf4fba517f"}, "type": "CWE-787"}
201
Determine whether the {function_name} code is vulnerable or not.
[ "=== woo-popup ===\nContributors: Guillaume Kanoufi\nDonate link: http://lostwebdesigns.com/\nTags: pop up, woocommerce, woopopup, modal window, display info after a product is added\nRequires at least: 3.5.1", "Tested up to: 3.9\nStable tag: 1.2.2", "License: GPLv2 or later\nLicense URI: http://www.gnu.org/licenses/gpl-2.0.html", "Display a pop up window after the chosen page is loaded.", "== Description ==", "A plugin to show a pop up window with any text, links, images, and even shortcodes when on the chosen page or all pages. Useful to present your customers with possible shipping delays if using woocommerce or anything else you can think about.\nYou can use it permanently or between 2 defined dates.\nWas made for woocommerce, late shipping or important info at the begining, but can be used on any wordpress installation.", "== Installation ==", "= Using The WordPress Dashboard =", "1. Navigate to the 'Add New' in the plugins dashboard\n2. Search for 'woo-popup'\n3. Click 'Install Now'\n4. Activate the plugin on the Plugin dashboard\n5. Customize the setting by clicking on the \"Woo Popup Settings\" menu tab", "= Uploading in WordPress Dashboard =", "1. Navigate to the 'Add New' in the plugins dashboard\n2. Navigate to the 'Upload' area\n3. Select `woo-popup.zip` from your computer\n4. Click 'Install Now'\n5. Activate the plugin in the Plugin dashboard", "= Using FTP =", "1. Download `woo-popup.zip`\n2. Extract the `woo-popup` directory to your computer\n3. Upload the `woo-popup` directory to the `/wp-content/plugins/` directory\n4. Activate the plugin in the Plugin dashboard", "\n== Frequently Asked Questions ==", "= A question that someone might have =", "An answer to that question.", "= How to use woo-popup? =", "Just activate the plugin then go to the woo-popup menu and customize to your needs(text to show begining and end dates) and that's pretty much it.", "== Screenshots ==", "1. No screenshots yet", "== Changelog ==", "= 1.2.2 =\nFixed fatal error with is_shop", "= 1.2.1 =\nFix a fatal error due to timezone list", "= 1.2 =\nAdded option to display the popup permanently(no dates then need to be selected) and possibility to choose the timezone you are in.\nAlso possibility to display the popup on all pages.", "= 1.1 =\nAdded wpaoutop for formatting and possibility to add a class to the content.", "= 1.0 =\n* First Version of this plugin.", "\n== Updates ==", "= 1.2 =\nAdded option to display the popup permanently(no dates would then need to be selected) and possibility to choose the timezone you are in.\nAlso possibility to display the popup on all pages.", "= 1.1 =\nAdded wpaoutop for formatting and possibility to add a class to the content." ]
[ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [8, 242, 71, 2, 10, 379, 21, 19], "buggy_code_start_loc": [6, 196, 31, 1, 1, 31, 19, 18], "filenames": ["README.txt", "admin/class-woo-popup-admin.php", "admin/views/admin.php", "public/assets/css/prettyPhoto.css", "public/assets/js/public.js", "public/class-woo-popup.php", "public/views/public.php", "woo-popup.php"], "fixing_code_end_loc": [8, 251, 109, 171, 30, 384, 23, 19], "fixing_code_start_loc": [6, 197, 32, 1, 1, 31, 19, 18], "message": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:woo-popup_project:woo-popup:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "FDF073CD-7548-4114-B554-A83685981B77", "versionEndExcluding": "1.3.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327."}], "evaluatorComment": null, "id": "CVE-2015-10095", "lastModified": "2023-03-13T15:18:44.873", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-03-06T21:15:10.150", "references": [{"source": "cna@vuldb.com", "tags": ["Patch"], "url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, {"source": "cna@vuldb.com", "tags": ["Release Notes"], "url": "https://github.com/wp-plugins/woo-popup/releases/tag/1.3.0"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?ctiid.222327"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?id.222327"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, "type": "CWE-79"}
202
Determine whether the {function_name} code is vulnerable or not.
[ "=== woo-popup ===\nContributors: Guillaume Kanoufi\nDonate link: http://lostwebdesigns.com/\nTags: pop up, woocommerce, woopopup, modal window, display info after a product is added\nRequires at least: 3.5.1", "Tested up to: 4.2\nStable tag: 1.3.0", "License: GPLv2 or later\nLicense URI: http://www.gnu.org/licenses/gpl-2.0.html", "Display a pop up window after the chosen page is loaded.", "== Description ==", "A plugin to show a pop up window with any text, links, images, and even shortcodes when on the chosen page or all pages. Useful to present your customers with possible shipping delays if using woocommerce or anything else you can think about.\nYou can use it permanently or between 2 defined dates.\nWas made for woocommerce, late shipping or important info at the begining, but can be used on any wordpress installation.", "== Installation ==", "= Using The WordPress Dashboard =", "1. Navigate to the 'Add New' in the plugins dashboard\n2. Search for 'woo-popup'\n3. Click 'Install Now'\n4. Activate the plugin on the Plugin dashboard\n5. Customize the setting by clicking on the \"Woo Popup Settings\" menu tab", "= Uploading in WordPress Dashboard =", "1. Navigate to the 'Add New' in the plugins dashboard\n2. Navigate to the 'Upload' area\n3. Select `woo-popup.zip` from your computer\n4. Click 'Install Now'\n5. Activate the plugin in the Plugin dashboard", "= Using FTP =", "1. Download `woo-popup.zip`\n2. Extract the `woo-popup` directory to your computer\n3. Upload the `woo-popup` directory to the `/wp-content/plugins/` directory\n4. Activate the plugin in the Plugin dashboard", "\n== Frequently Asked Questions ==", "= A question that someone might have =", "An answer to that question.", "= How to use woo-popup? =", "Just activate the plugin then go to the woo-popup menu and customize to your needs(text to show begining and end dates) and that's pretty much it.", "== Screenshots ==", "1. No screenshots yet", "== Changelog ==", "= 1.2.2 =\nFixed fatal error with is_shop", "= 1.2.1 =\nFix a fatal error due to timezone list", "= 1.2 =\nAdded option to display the popup permanently(no dates then need to be selected) and possibility to choose the timezone you are in.\nAlso possibility to display the popup on all pages.", "= 1.1 =\nAdded wpaoutop for formatting and possibility to add a class to the content.", "= 1.0 =\n* First Version of this plugin.", "\n== Updates ==", "= 1.2 =\nAdded option to display the popup permanently(no dates would then need to be selected) and possibility to choose the timezone you are in.\nAlso possibility to display the popup on all pages.", "= 1.1 =\nAdded wpaoutop for formatting and possibility to add a class to the content." ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [8, 242, 71, 2, 10, 379, 21, 19], "buggy_code_start_loc": [6, 196, 31, 1, 1, 31, 19, 18], "filenames": ["README.txt", "admin/class-woo-popup-admin.php", "admin/views/admin.php", "public/assets/css/prettyPhoto.css", "public/assets/js/public.js", "public/class-woo-popup.php", "public/views/public.php", "woo-popup.php"], "fixing_code_end_loc": [8, 251, 109, 171, 30, 384, 23, 19], "fixing_code_start_loc": [6, 197, 32, 1, 1, 31, 19, 18], "message": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:woo-popup_project:woo-popup:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "FDF073CD-7548-4114-B554-A83685981B77", "versionEndExcluding": "1.3.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327."}], "evaluatorComment": null, "id": "CVE-2015-10095", "lastModified": "2023-03-13T15:18:44.873", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-03-06T21:15:10.150", "references": [{"source": "cna@vuldb.com", "tags": ["Patch"], "url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, {"source": "cna@vuldb.com", "tags": ["Release Notes"], "url": "https://github.com/wp-plugins/woo-popup/releases/tag/1.3.0"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?ctiid.222327"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?id.222327"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, "type": "CWE-79"}
202
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * woo-popup\n *\n * @package WooPopupAdmin\n * @author Guillaume Kanoufi <guillaume@lostwebdesigns.com>\n * @license GPL-2.0+\n * @link http://lostwebdesigns.com\n * @copyright 2014 woocommerce, popup, woopopup\n */", "/**\n * Plugin class. This class should ideally be used to work with the\n * administrative side of the WordPress site.\n *\n * If you're interested in introducing public-facing\n * functionality, then refer to `class-woo-popup.php`\n *\n * @package WooPopupAdmin\n * @author Guillaume Kanoufi <guillaume@lostwebdesigns.com>\n */\nclass WooPopupAdmin {", "\t/**\n\t * Instance of this class.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @var object\n\t */\n\tprotected static $instance = null;", "\t/**\n\t * Slug of the plugin screen.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @var string\n\t */\n\tprotected $plugin_screen_hook_suffix = null;", "\t/**\n\t * Initialize the plugin by loading admin scripts & styles and adding a\n\t * settings page and menu.\n\t *\n\t * @since 1.0.0\n\t */\n\tprivate function __construct() {", "\n\t\t$plugin = WooPopup::get_instance();\n\t\t$this->plugin_slug = $plugin->get_plugin_slug();\n\t\t$this->options_slug = $plugin->get_plugin_options_slug();\n\t\t$this->options_data = $plugin->get_plugin_options_data();", "\t\t// Load admin style sheet and JavaScript.\n\t\tadd_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_styles' ) );\n\t\tadd_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );", "\t\t// Add the options page and menu item.\n\t\tadd_action( 'admin_menu', array( $this, 'add_plugin_admin_menu' ) );", "\t\t// Add an action link pointing to the options page.\n\t\t$plugin_basename = plugin_basename( plugin_dir_path( __DIR__ ) . $this->plugin_slug . '.php' );\n\t\tadd_filter( 'plugin_action_links_' . $plugin_basename, array( $this, 'add_action_links' ) );", "\t\t// Add the options update action\n\t\tadd_action('admin_init', array($this, 'options_update'));", "\t}", "\t/**\n\t * Return an instance of this class.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @return object A single instance of this class.\n\t */\n\tpublic static function get_instance() {", "\t\t// If the single instance hasn't been set, set it now.\n\t\tif ( null == self::$instance ) {\n\t\t\tself::$instance = new self;\n\t\t}", "\t\treturn self::$instance;\n\t}", "\t/**\n\t * Register and enqueue admin-specific style sheet.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @return null Return early if no settings page is registered.\n\t */\n\tpublic function enqueue_admin_styles() {", "\t\tif ( ! isset( $this->plugin_screen_hook_suffix ) ) {\n\t\t\treturn;\n\t\t}", "\t\t$screen = get_current_screen();\n\t\tif ( $this->plugin_screen_hook_suffix == $screen->id ) {\n\t\t\twp_enqueue_style( $this->plugin_slug .'-admin-styles', plugins_url( 'assets/css/admin.css', __FILE__ ), array(), WooPopup::VERSION );\n\t\t\twp_enqueue_style('jquery-ui-css', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css');\n\t\t}", "\t}", "\t/**\n\t * Register and enqueue admin-specific JavaScript.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @return null Return early if no settings page is registered.\n\t */\n\tpublic function enqueue_admin_scripts() {", "\t\tif ( ! isset( $this->plugin_screen_hook_suffix ) ) {\n\t\t\treturn;\n\t\t}", "\t\t$screen = get_current_screen();\n\t\tif ( $this->plugin_screen_hook_suffix == $screen->id ) {\n\t\t\twp_enqueue_script( 'jquery-ui-datepicker' );\n\t\t\twp_enqueue_script( $this->plugin_slug . '-admin-script', plugins_url( 'assets/js/admin.js', __FILE__ ), array( 'jquery' ), WooPopup::VERSION );\n\t\t}", "\t}", "\t/**\n\t * Register the administration menu for this plugin into the WordPress Dashboard menu.\n\t *\n\t * @since 1.0.0\n\t */\n\tpublic function add_plugin_admin_menu() {", "\t\t/*\n\t\t * Add a settings page for this plugin to the Settings menu.\n\t\t *\n\t\t * NOTE: Alternative menu locations are available via WordPress administration menu functions.\n\t\t *\n\t\t * Administration Menus: http://codex.wordpress.org/Administration_Menus\n\t\t *\n\t\t */\n\t\t$this->plugin_screen_hook_suffix = add_menu_page(\n\t\t\t__( 'Woo Pop Up', $this->plugin_slug ),\n\t\t\t__( 'Woo Pop Up Settings', $this->plugin_slug ),\n\t\t\t'manage_options',\n\t\t\t$this->options_slug,\n\t\t\tarray( $this, 'display_plugin_admin_page' )\n\t\t);", "\t}", "\t/**\n\t * Render the settings page for this plugin.\n\t *\n\t * @since 1.0.0\n\t */\n\tpublic function display_plugin_admin_page() {\n\t\tinclude_once( 'views/admin.php' );\n\t}", "\t/**\n\t * Add settings action link to the plugins page.\n\t *\n\t * @since 1.0.0\n\t */\n\tpublic function add_action_links( $links ) {", "\n\t\treturn array_merge(\n\t\t\tarray(\n\t\t\t\t'settings' => '<a href=\"' . admin_url( 'admin.php?page=' . $this->options_slug ) . '\">' . __( 'Settings', $this->plugin_slug ) . '</a>'\n\t\t\t),\n\t\t\t$links\n\t\t);", "\t}", "\t/**\n\t * \tSave the plugin options\n\t *\n\t *\n\t * @since 1.0.0\n\t */\n\tpublic function options_update() {\n\t\tregister_setting( $this->options_slug, $this->options_slug, array($this, 'validate') );\n\t}", "\tpublic function validate($input) {\n\t $valid = array();\n\t $valid['popup_content'] = wp_kses_post($input['popup_content']);\n\t $valid['popup_page'] = sanitize_text_field($input['popup_page']);\n\t $valid['popup_class'] = sanitize_text_field($input['popup_class']);", "", "\t $valid['start_date'] = sanitize_text_field($input['start_date']);\n\t $valid['end_date'] = sanitize_text_field($input['end_date']);\n\t $valid['popup_timezone'] = sanitize_text_field($input['popup_timezone']);", "\t if(isset($input['popup_permanent'])){\n\t \t $valid['popup_permanent'] = sanitize_text_field($input['popup_permanent']);\n\t }else{\n\t \t $valid['popup_permanent'] = '0';\n\t }", "\n\t if (strlen($valid['popup_content']) == 0) {\n\t add_settings_error(\n\t 'popup_content', // Setting title\n\t 'popup_content_texterror', // Error ID\n\t 'Please enter a text to show on the pop up', // Error message\n\t 'error' // Type of message\n\t );", "\t // Set it to the default value\n\t $valid['popup_content'] = $this->data['popup_content'];\n\t }", "\t if (strlen($valid['popup_page']) == 0) {\n\t add_settings_error(\n\t 'popup_page',\n\t 'popup_page_texterror',\n\t 'Please choose a page to display the pop up to',\n\t 'error'\n\t );", "\t $valid['popup_page'] = $this->data['popup_page'];\n\t }\n\t if (strlen($valid['popup_class']) == 0) {\n\t add_settings_error(\n\t 'popup_class',\n\t 'popup_class_texterror',\n\t 'Please choose a class to display the pop up to',\n\t 'error'\n\t );", "\t $valid['popup_class'] = $this->data['popup_class'];\n\t }", "\n", "\t if (strlen($valid['start_date']) == 0) {\n\t add_settings_error(\n\t 'start_date',\n\t 'start_date_texterror',\n\t 'Please enter a beginning date',\n\t 'error'\n\t );", "\t $valid['start_date'] = $this->data['start_date'];\n\t }", "\t if (strlen($valid['end_date']) == 0) {\n\t add_settings_error(\n\t 'end_date',\n\t 'end_date_texterror',\n\t 'Please enter a beginning date',\n\t 'error'\n\t );", "\t $valid['end_date'] = $this->data['end_date'];\n\t }", "\t return $valid;\n\t}", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [8, 242, 71, 2, 10, 379, 21, 19], "buggy_code_start_loc": [6, 196, 31, 1, 1, 31, 19, 18], "filenames": ["README.txt", "admin/class-woo-popup-admin.php", "admin/views/admin.php", "public/assets/css/prettyPhoto.css", "public/assets/js/public.js", "public/class-woo-popup.php", "public/views/public.php", "woo-popup.php"], "fixing_code_end_loc": [8, 251, 109, 171, 30, 384, 23, 19], "fixing_code_start_loc": [6, 197, 32, 1, 1, 31, 19, 18], "message": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:woo-popup_project:woo-popup:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "FDF073CD-7548-4114-B554-A83685981B77", "versionEndExcluding": "1.3.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327."}], "evaluatorComment": null, "id": "CVE-2015-10095", "lastModified": "2023-03-13T15:18:44.873", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-03-06T21:15:10.150", "references": [{"source": "cna@vuldb.com", "tags": ["Patch"], "url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, {"source": "cna@vuldb.com", "tags": ["Release Notes"], "url": "https://github.com/wp-plugins/woo-popup/releases/tag/1.3.0"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?ctiid.222327"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?id.222327"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, "type": "CWE-79"}
202
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * woo-popup\n *\n * @package WooPopupAdmin\n * @author Guillaume Kanoufi <guillaume@lostwebdesigns.com>\n * @license GPL-2.0+\n * @link http://lostwebdesigns.com\n * @copyright 2014 woocommerce, popup, woopopup\n */", "/**\n * Plugin class. This class should ideally be used to work with the\n * administrative side of the WordPress site.\n *\n * If you're interested in introducing public-facing\n * functionality, then refer to `class-woo-popup.php`\n *\n * @package WooPopupAdmin\n * @author Guillaume Kanoufi <guillaume@lostwebdesigns.com>\n */\nclass WooPopupAdmin {", "\t/**\n\t * Instance of this class.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @var object\n\t */\n\tprotected static $instance = null;", "\t/**\n\t * Slug of the plugin screen.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @var string\n\t */\n\tprotected $plugin_screen_hook_suffix = null;", "\t/**\n\t * Initialize the plugin by loading admin scripts & styles and adding a\n\t * settings page and menu.\n\t *\n\t * @since 1.0.0\n\t */\n\tprivate function __construct() {", "\n\t\t$plugin = WooPopup::get_instance();\n\t\t$this->plugin_slug = $plugin->get_plugin_slug();\n\t\t$this->options_slug = $plugin->get_plugin_options_slug();\n\t\t$this->options_data = $plugin->get_plugin_options_data();", "\t\t// Load admin style sheet and JavaScript.\n\t\tadd_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_styles' ) );\n\t\tadd_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );", "\t\t// Add the options page and menu item.\n\t\tadd_action( 'admin_menu', array( $this, 'add_plugin_admin_menu' ) );", "\t\t// Add an action link pointing to the options page.\n\t\t$plugin_basename = plugin_basename( plugin_dir_path( __DIR__ ) . $this->plugin_slug . '.php' );\n\t\tadd_filter( 'plugin_action_links_' . $plugin_basename, array( $this, 'add_action_links' ) );", "\t\t// Add the options update action\n\t\tadd_action('admin_init', array($this, 'options_update'));", "\t}", "\t/**\n\t * Return an instance of this class.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @return object A single instance of this class.\n\t */\n\tpublic static function get_instance() {", "\t\t// If the single instance hasn't been set, set it now.\n\t\tif ( null == self::$instance ) {\n\t\t\tself::$instance = new self;\n\t\t}", "\t\treturn self::$instance;\n\t}", "\t/**\n\t * Register and enqueue admin-specific style sheet.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @return null Return early if no settings page is registered.\n\t */\n\tpublic function enqueue_admin_styles() {", "\t\tif ( ! isset( $this->plugin_screen_hook_suffix ) ) {\n\t\t\treturn;\n\t\t}", "\t\t$screen = get_current_screen();\n\t\tif ( $this->plugin_screen_hook_suffix == $screen->id ) {\n\t\t\twp_enqueue_style( $this->plugin_slug .'-admin-styles', plugins_url( 'assets/css/admin.css', __FILE__ ), array(), WooPopup::VERSION );\n\t\t\twp_enqueue_style('jquery-ui-css', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css');\n\t\t}", "\t}", "\t/**\n\t * Register and enqueue admin-specific JavaScript.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @return null Return early if no settings page is registered.\n\t */\n\tpublic function enqueue_admin_scripts() {", "\t\tif ( ! isset( $this->plugin_screen_hook_suffix ) ) {\n\t\t\treturn;\n\t\t}", "\t\t$screen = get_current_screen();\n\t\tif ( $this->plugin_screen_hook_suffix == $screen->id ) {\n\t\t\twp_enqueue_script( 'jquery-ui-datepicker' );\n\t\t\twp_enqueue_script( $this->plugin_slug . '-admin-script', plugins_url( 'assets/js/admin.js', __FILE__ ), array( 'jquery' ), WooPopup::VERSION );\n\t\t}", "\t}", "\t/**\n\t * Register the administration menu for this plugin into the WordPress Dashboard menu.\n\t *\n\t * @since 1.0.0\n\t */\n\tpublic function add_plugin_admin_menu() {", "\t\t/*\n\t\t * Add a settings page for this plugin to the Settings menu.\n\t\t *\n\t\t * NOTE: Alternative menu locations are available via WordPress administration menu functions.\n\t\t *\n\t\t * Administration Menus: http://codex.wordpress.org/Administration_Menus\n\t\t *\n\t\t */\n\t\t$this->plugin_screen_hook_suffix = add_menu_page(\n\t\t\t__( 'Woo Pop Up', $this->plugin_slug ),\n\t\t\t__( 'Woo Pop Up Settings', $this->plugin_slug ),\n\t\t\t'manage_options',\n\t\t\t$this->options_slug,\n\t\t\tarray( $this, 'display_plugin_admin_page' )\n\t\t);", "\t}", "\t/**\n\t * Render the settings page for this plugin.\n\t *\n\t * @since 1.0.0\n\t */\n\tpublic function display_plugin_admin_page() {\n\t\tinclude_once( 'views/admin.php' );\n\t}", "\t/**\n\t * Add settings action link to the plugins page.\n\t *\n\t * @since 1.0.0\n\t */\n\tpublic function add_action_links( $links ) {", "\n\t\treturn array_merge(\n\t\t\tarray(\n\t\t\t\t'settings' => '<a href=\"' . admin_url( 'admin.php?page=' . $this->options_slug ) . '\">' . __( 'Settings', $this->plugin_slug ) . '</a>'\n\t\t\t),\n\t\t\t$links\n\t\t);", "\t}", "\t/**\n\t * \tSave the plugin options\n\t *\n\t *\n\t * @since 1.0.0\n\t */\n\tpublic function options_update() {\n\t\tregister_setting( $this->options_slug, $this->options_slug, array($this, 'validate') );\n\t}", "\tpublic function validate($input) {\n\t $valid = array();\n\t $valid['popup_content'] = wp_kses_post($input['popup_content']);\n\t $valid['popup_page'] = sanitize_text_field($input['popup_page']);\n\t $valid['popup_class'] = sanitize_text_field($input['popup_class']);", "\t $valid['popup_theme'] = sanitize_text_field($input['popup_theme']);", "\t $valid['start_date'] = sanitize_text_field($input['start_date']);\n\t $valid['end_date'] = sanitize_text_field($input['end_date']);\n\t $valid['popup_timezone'] = sanitize_text_field($input['popup_timezone']);", "\t if(isset($input['popup_permanent'])){\n\t \t $valid['popup_permanent'] = sanitize_text_field($input['popup_permanent']);\n\t }else{\n\t \t $valid['popup_permanent'] = '0';\n\t }", "\n\t if (strlen($valid['popup_content']) == 0) {\n\t add_settings_error(\n\t 'popup_content', // Setting title\n\t 'popup_content_texterror', // Error ID\n\t 'Please enter a text to show on the pop up', // Error message\n\t 'error' // Type of message\n\t );", "\t // Set it to the default value\n\t $valid['popup_content'] = $this->data['popup_content'];\n\t }", "\t if (strlen($valid['popup_page']) == 0) {\n\t add_settings_error(\n\t 'popup_page',\n\t 'popup_page_texterror',\n\t 'Please choose a page to display the pop up to',\n\t 'error'\n\t );", "\t $valid['popup_page'] = $this->data['popup_page'];\n\t }\n\t if (strlen($valid['popup_class']) == 0) {\n\t add_settings_error(\n\t 'popup_class',\n\t 'popup_class_texterror',\n\t 'Please choose a class to display the pop up to',\n\t 'error'\n\t );", "\t $valid['popup_class'] = $this->data['popup_class'];\n\t }", "\t if (strlen($valid['popup_theme']) == 0) {\n\t add_settings_error(\n\t 'popup_theme',\n\t 'popup_theme_texterror',\n\t 'Please choose a theme to display the pop up to',\n\t 'error'\n\t );", "\t $valid['popup_class'] = $this->data['popup_class'];\n\t }", "\t if (strlen($valid['start_date']) == 0) {\n\t add_settings_error(\n\t 'start_date',\n\t 'start_date_texterror',\n\t 'Please enter a beginning date',\n\t 'error'\n\t );", "\t $valid['start_date'] = $this->data['start_date'];\n\t }", "\t if (strlen($valid['end_date']) == 0) {\n\t add_settings_error(\n\t 'end_date',\n\t 'end_date_texterror',\n\t 'Please enter a beginning date',\n\t 'error'\n\t );", "\t $valid['end_date'] = $this->data['end_date'];\n\t }", "\t return $valid;\n\t}", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [8, 242, 71, 2, 10, 379, 21, 19], "buggy_code_start_loc": [6, 196, 31, 1, 1, 31, 19, 18], "filenames": ["README.txt", "admin/class-woo-popup-admin.php", "admin/views/admin.php", "public/assets/css/prettyPhoto.css", "public/assets/js/public.js", "public/class-woo-popup.php", "public/views/public.php", "woo-popup.php"], "fixing_code_end_loc": [8, 251, 109, 171, 30, 384, 23, 19], "fixing_code_start_loc": [6, 197, 32, 1, 1, 31, 19, 18], "message": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:woo-popup_project:woo-popup:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "FDF073CD-7548-4114-B554-A83685981B77", "versionEndExcluding": "1.3.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327."}], "evaluatorComment": null, "id": "CVE-2015-10095", "lastModified": "2023-03-13T15:18:44.873", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-03-06T21:15:10.150", "references": [{"source": "cna@vuldb.com", "tags": ["Patch"], "url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, {"source": "cna@vuldb.com", "tags": ["Release Notes"], "url": "https://github.com/wp-plugins/woo-popup/releases/tag/1.3.0"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?ctiid.222327"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?id.222327"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, "type": "CWE-79"}
202
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * Represents the view for the administration dashboard.\n *\n * This includes the header, options, and other information that should provide\n * The User Interface to the end user.\n *\n * @package WooPopup\n * @author Guillaume Kanoufi <guillaume@lostwebdesigns.com>\n * @license GPL-2.0+\n * @link http://example.com\n * @copyright 2014 woocommerce, popup, woopopup\n */\n?>", "<div class=\"wrap\">", "\n\t<h2><?php echo esc_html( get_admin_page_title() ); ?></h2>", "\t<div class=\"wrap metabox-holder columns-2\">\n\t <form method=\"post\" name=\"options\" action=\"options.php\">\n\t\t\t<?php\n\t\t\t\t$options = get_option($this->options_slug);\n\t\t\t\t/*\n\t\t\t\t* Grab all value if already set\n\t\t\t\t*\n\t\t\t\t*/\n\t\t\t\t$content = $options['popup_content'];\n\t\t\t\t$page = $options['popup_page'];\n\t\t\t\t$class = $options['popup_class'];", "", "\t\t\t\t$permanent = $options['popup_permanent'];\n\t\t\t\t$start_date = $options['start_date'];\n\t\t\t\t$end_date = $options['end_date'];\n\t\t\t\t$timezone = $options['popup_timezone'];", "\t\t\t\t/*\n\t\t\t\t* Set up hidden fields\n\t\t\t\t*\n\t\t\t\t*/\n\t\t\t\tsettings_fields($this->options_slug);\n\t\t\t?>", "", "\t\t\t<?php wp_editor( $content, $this->options_slug.'[popup_content]'); ?>", "\t <table width=\"100%\" cellpadding=\"10\" class=\"form-table\">\n\t \t<tr>\n\t \t\t<th scope=\"row\">\n\t \t\t\t<label><?php _e('Choose the page you want to display your popup window (default is cart page)', $this->plugin_slug);?>:</label>\n\t \t\t</th>\n\t \t\t<td>\n\t \t\t\t<?php\n\t \t\t\t\t$args = array(\n\t \t\t\t\t\t'show_option_none' => 'All',\n\t \t\t\t\t\t'option_none_value' => 'all',\n\t \t\t\t\t\t'selected' => $page,\n\t \t\t\t\t\t'name' => $this->options_slug.'[popup_page]',\n\t \t\t\t\t);\n\t \t\t\t\t$pages = wp_dropdown_pages($args);\n\t \t\t\t?>\n\t \t\t</td>", "\t \t</tr>\n\t \t<tr>\n\t \t\t<th scope=\"row\">", "", "\t \t\t\t<label><?php _e('If using woocommerce, you can choose from woocommerce-message classes (message, info or error) else it will add a custom class of woopopup-yourchoice (your choice being: message, info or error) so you will be able to style it in your css', $this->plugin_slug);?>:</label>\n\t \t\t</th>\n\t \t\t<td>\n\t \t\t\t<select name=\"<?php echo $this->options_slug;?>[popup_class]\" >", "\t \t\t\t\t<option value=\"notice\">Notice (default non woocommerce class)</option>", "\t\t\t\t\t\t\t<option value=\"message\" <?php if($class == 'message') echo 'selected';?>>Message</option>\n\t\t\t\t\t\t\t<option value=\"info\" <?php if($class == 'info') echo 'selected';?>>Info</option>\n\t\t\t\t\t\t\t<option value=\"error\" <?php if($class == 'error') echo 'selected';?>>Error</option>\n\t \t\t\t</select>\n\t \t\t</td>", "\t \t</tr>\n\t \t<tr>\n\t <th scope=\"row\">\n\t\t <label><?php _e('Make the popup permanent (no dates selections)', $this->plugin_slug);?>:</label>\n\t\t </th>\n\t\t <td>\n\t\t <input type=\"checkbox\" id=\"woo-popup_permanent\" name=\"<?php echo $this->options_slug;?>[popup_permanent]\" value=\"1\" <?php if($permanent == '1') echo 'checked';?>/>\n\t </td>\n\t </tr>\n\t <tr class=\"woo-popup_dates\">\n\t <th scope=\"row\">\n\t\t <label><?php _e('Begining Date', $this->plugin_slug);?>:</label>\n\t\t </th>\n\t\t <td>\n\t\t <input type=\"text\" id=\"woo-popup-from\" class=\"wpopup_date\" name=\"<?php echo $this->options_slug;?>[start_date]\" value=\"<?php echo $start_date;?>\"/>\n\t </td>\n\t </tr>\n\t <tr class=\"woo-popup_dates\">\n\t <th scope=\"row\">\n\t\t <label><?php _e('End Date', $this->plugin_slug);?>:</label>\n\t\t </th>\n\t\t <td>\n\t\t <input type=\"text\" id=\"woo-popup-to\" class=\"wpopup_date\" name=\"<?php echo $this->options_slug;?>[end_date]\" value=\"<?php echo $end_date;?>\"/>\n\t </td>\n\t </tr>\n\t <tr class=\"woo-popup_dates\">\n\t \t\t<?php $tzl = DateTimeZone::listIdentifiers();?>\n\t <th scope=\"row\">\n\t\t <label><?php _e('Choose your Timezone', $this->plugin_slug);?>:</label>\n\t\t </th>\n\t\t <td>\n\t\t <select name=\"<?php echo $this->options_slug;?>[popup_timezone]\" >\n\t \t\t\t\t<?php foreach ($tzl as $tz) :?>\n\t \t\t\t\t\t<option value=\"<?php echo $tz;?>\" <?php if($timezone == $tz) echo 'selected';?>><?php echo $tz;?></option>\n\t \t\t\t\t<?php endforeach;?>\n\t \t\t\t</select>\n\t </td>\n\t </tr>\n\t </table>", "\t <p class=\"submit\">\n\t <input type=\"submit\" class=\"button-primary\" name=\"Submit\" value=\"Save Changes\" />\n\t </p>\n </form>", " </div>\n</div>" ]
[ 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [8, 242, 71, 2, 10, 379, 21, 19], "buggy_code_start_loc": [6, 196, 31, 1, 1, 31, 19, 18], "filenames": ["README.txt", "admin/class-woo-popup-admin.php", "admin/views/admin.php", "public/assets/css/prettyPhoto.css", "public/assets/js/public.js", "public/class-woo-popup.php", "public/views/public.php", "woo-popup.php"], "fixing_code_end_loc": [8, 251, 109, 171, 30, 384, 23, 19], "fixing_code_start_loc": [6, 197, 32, 1, 1, 31, 19, 18], "message": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:woo-popup_project:woo-popup:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "FDF073CD-7548-4114-B554-A83685981B77", "versionEndExcluding": "1.3.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327."}], "evaluatorComment": null, "id": "CVE-2015-10095", "lastModified": "2023-03-13T15:18:44.873", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-03-06T21:15:10.150", "references": [{"source": "cna@vuldb.com", "tags": ["Patch"], "url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, {"source": "cna@vuldb.com", "tags": ["Release Notes"], "url": "https://github.com/wp-plugins/woo-popup/releases/tag/1.3.0"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?ctiid.222327"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?id.222327"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, "type": "CWE-79"}
202
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * Represents the view for the administration dashboard.\n *\n * This includes the header, options, and other information that should provide\n * The User Interface to the end user.\n *\n * @package WooPopup\n * @author Guillaume Kanoufi <guillaume@lostwebdesigns.com>\n * @license GPL-2.0+\n * @link http://example.com\n * @copyright 2014 woocommerce, popup, woopopup\n */\n?>", "<div class=\"wrap\">", "\n\t<h2><?php echo esc_html( get_admin_page_title() ); ?></h2>", "\t<div class=\"wrap metabox-holder columns-2\">\n\t <form method=\"post\" name=\"options\" action=\"options.php\">\n\t\t\t<?php\n\t\t\t\t$options = get_option($this->options_slug);\n\t\t\t\t/*\n\t\t\t\t* Grab all value if already set\n\t\t\t\t*\n\t\t\t\t*/\n\t\t\t\t$content = $options['popup_content'];\n\t\t\t\t$page = $options['popup_page'];\n\t\t\t\t$class = $options['popup_class'];", "\t\t\t\t$theme = $options['popup_theme'];\n\t\t\t\t// $use_button = $options['popup_use_button'];", "\t\t\t\t$permanent = $options['popup_permanent'];\n\t\t\t\t$start_date = $options['start_date'];\n\t\t\t\t$end_date = $options['end_date'];\n\t\t\t\t$timezone = $options['popup_timezone'];", "\t\t\t\t/*\n\t\t\t\t* Set up hidden fields\n\t\t\t\t*\n\t\t\t\t*/\n\t\t\t\tsettings_fields($this->options_slug);\n\t\t\t?>", "", "\t\t\t<?php\n\t\t\t// editor_id cannot have brackets and must be lowercase\n\t\t\t$editor_id = 'popup_content';\n\t\t\t// textarea_name in array can have brackets!\n\t\t\t$settings = array(\n\t\t\t\t'wpautop' => true, // use wpautop?\n\t\t\t\t'media_buttons' => true, // show insert/upload button(s)\n\t\t\t\t'textarea_name' => $this->options_slug.'[popup_content]', // set the textarea name to something different, square brackets [] can be used here\n\t\t\t\t'textarea_rows' => get_option('default_post_edit_rows', 10), // rows=\"...\"\n\t\t\t\t'tabindex' => '',\n\t\t\t\t'editor_css' => '', // intended for extra styles for both visual and HTML editors buttons, needs to include the <style> tags, can use \"scoped\".\n\t\t\t\t'editor_class' => '', // add extra class(es) to the editor textarea\n\t\t\t\t'teeny' => false, // output the minimal editor config used in Press This\n\t\t\t\t'dfw' => true, // replace the default fullscreen with DFW (supported on the front-end in WordPress 3.4)\n\t\t\t\t'tinymce' => true, // load TinyMCE, can be used to pass settings directly to TinyMCE using an array()\n\t\t\t\t'quicktags' => true\n\t\t\t);\n\t\t\twp_editor($content, $editor_id, $settings);?>\n", "\t <table width=\"100%\" cellpadding=\"10\" class=\"form-table\">\n\t \t<tr>\n\t \t\t<th scope=\"row\">\n\t \t\t\t<label><?php _e('Choose the page you want to display your popup window (default is cart page)', $this->plugin_slug);?>:</label>\n\t \t\t</th>\n\t \t\t<td>\n\t \t\t\t<?php\n\t \t\t\t\t$args = array(\n\t \t\t\t\t\t'show_option_none' => 'All',\n\t \t\t\t\t\t'option_none_value' => 'all',\n\t \t\t\t\t\t'selected' => $page,\n\t \t\t\t\t\t'name' => $this->options_slug.'[popup_page]',\n\t \t\t\t\t);\n\t \t\t\t\t$pages = wp_dropdown_pages($args);\n\t \t\t\t?>\n\t \t\t</td>", "\t \t</tr>\n\t \t<tr>\n\t \t\t<th scope=\"row\">", "\t \t\t\t<label><?php _e('Choose the prettyPhoto Modal theme color', $this->plugin_slug);?>:</label>\n\t \t\t</th>\n\t \t\t<td>\n\t \t\t\t<select name=\"<?php echo $this->options_slug;?>[popup_theme]\" >\n\t \t\t\t\tlight_rounded / dark_rounded / light_square / dark_square / facebook\n\t \t\t\t\t<option value=\"pp_default\" <?php if($theme == 'pp_default') echo 'selected';?>>Default</option>\n\t\t\t\t\t\t<option value=\"light_rounded\" <?php if($theme == 'light_rounded') echo 'selected';?>>Light Rounded</option>\n\t\t\t\t\t\t<option value=\"dark_rounded\" <?php if($theme == 'dark_rounded') echo 'selected';?>>Dark Rounded</option>\n\t\t\t\t\t\t<option value=\"light_square\" <?php if($theme == 'light_square') echo 'selected';?>>Light Square</option>\n\t\t\t\t\t\t<option value=\"dark_square\" <?php if($theme == 'dark_square') echo 'selected';?>>Dark Square</option>\n\t\t\t\t\t\t<option value=\"facebook\" <?php if($theme == 'facebook') echo 'selected';?>>Facebook</option>\n\t \t\t\t</select>\n\t \t\t</td>", "\t \t</tr>\n\t \t<tr>\n\t \t<tr>\n\t \t\t<th scope=\"row\">", "\t \t\t\t<label><?php _e('If using woocommerce, you can choose from woocommerce-message classes (message, info or error) else it will add a custom class of woopopup-yourchoice (your choice being: message, info or error) so you will be able to style it in your css', $this->plugin_slug);?>:</label>\n\t \t\t</th>\n\t \t\t<td>\n\t \t\t\t<select name=\"<?php echo $this->options_slug;?>[popup_class]\" >", "\t \t\t\t\t<option value=\"notice\" <?php if($class == 'notice') echo 'selected';?>>Notice (default non woocommerce class)</option>", "\t\t\t\t\t\t\t<option value=\"message\" <?php if($class == 'message') echo 'selected';?>>Message</option>\n\t\t\t\t\t\t\t<option value=\"info\" <?php if($class == 'info') echo 'selected';?>>Info</option>\n\t\t\t\t\t\t\t<option value=\"error\" <?php if($class == 'error') echo 'selected';?>>Error</option>\n\t \t\t\t</select>\n\t \t\t</td>", "\t \t</tr>\n\t \t<tr>\n\t <th scope=\"row\">\n\t\t <label><?php _e('Make the popup permanent (no dates selections)', $this->plugin_slug);?>:</label>\n\t\t </th>\n\t\t <td>\n\t\t <input type=\"checkbox\" id=\"woo-popup_permanent\" name=\"<?php echo $this->options_slug;?>[popup_permanent]\" value=\"1\" <?php if($permanent == '1') echo 'checked';?>/>\n\t </td>\n\t </tr>\n\t <tr class=\"woo-popup_dates\">\n\t <th scope=\"row\">\n\t\t <label><?php _e('Begining Date', $this->plugin_slug);?>:</label>\n\t\t </th>\n\t\t <td>\n\t\t <input type=\"text\" id=\"woo-popup-from\" class=\"wpopup_date\" name=\"<?php echo $this->options_slug;?>[start_date]\" value=\"<?php echo $start_date;?>\"/>\n\t </td>\n\t </tr>\n\t <tr class=\"woo-popup_dates\">\n\t <th scope=\"row\">\n\t\t <label><?php _e('End Date', $this->plugin_slug);?>:</label>\n\t\t </th>\n\t\t <td>\n\t\t <input type=\"text\" id=\"woo-popup-to\" class=\"wpopup_date\" name=\"<?php echo $this->options_slug;?>[end_date]\" value=\"<?php echo $end_date;?>\"/>\n\t </td>\n\t </tr>\n\t <tr class=\"woo-popup_dates\">\n\t \t\t<?php $tzl = DateTimeZone::listIdentifiers();?>\n\t <th scope=\"row\">\n\t\t <label><?php _e('Choose your Timezone', $this->plugin_slug);?>:</label>\n\t\t </th>\n\t\t <td>\n\t\t <select name=\"<?php echo $this->options_slug;?>[popup_timezone]\" >\n\t \t\t\t\t<?php foreach ($tzl as $tz) :?>\n\t \t\t\t\t\t<option value=\"<?php echo $tz;?>\" <?php if($timezone == $tz) echo 'selected';?>><?php echo $tz;?></option>\n\t \t\t\t\t<?php endforeach;?>\n\t \t\t\t</select>\n\t </td>\n\t </tr>\n\t </table>", "\t <p class=\"submit\">\n\t <input type=\"submit\" class=\"button-primary\" name=\"Submit\" value=\"Save Changes\" />\n\t </p>\n </form>", " </div>\n</div>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [8, 242, 71, 2, 10, 379, 21, 19], "buggy_code_start_loc": [6, 196, 31, 1, 1, 31, 19, 18], "filenames": ["README.txt", "admin/class-woo-popup-admin.php", "admin/views/admin.php", "public/assets/css/prettyPhoto.css", "public/assets/js/public.js", "public/class-woo-popup.php", "public/views/public.php", "woo-popup.php"], "fixing_code_end_loc": [8, 251, 109, 171, 30, 384, 23, 19], "fixing_code_start_loc": [6, 197, 32, 1, 1, 31, 19, 18], "message": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:woo-popup_project:woo-popup:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "FDF073CD-7548-4114-B554-A83685981B77", "versionEndExcluding": "1.3.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327."}], "evaluatorComment": null, "id": "CVE-2015-10095", "lastModified": "2023-03-13T15:18:44.873", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-03-06T21:15:10.150", "references": [{"source": "cna@vuldb.com", "tags": ["Patch"], "url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, {"source": "cna@vuldb.com", "tags": ["Release Notes"], "url": "https://github.com/wp-plugins/woo-popup/releases/tag/1.3.0"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?ctiid.222327"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?id.222327"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, "type": "CWE-79"}
202
Determine whether the {function_name} code is vulnerable or not.
[ ".clear{clear:both}.nobr{white-space:nowrap}@font-face{font-family:WooCommerce;src:url(../fonts/WooCommerce.eot);src:url(../fonts/WooCommerce.eot?#iefix) format('embedded-opentype'),url(../fonts/WooCommerce.woff) format('woff'),url(../fonts/WooCommerce.ttf) format('truetype'),url(../fonts/WooCommerce.svg#WooCommerce) format('svg');font-weight:400;font-style:normal}div.pp_woocommerce .pp_content_container{background:#fff;-webkit-border-radius:3px;border-radius:3px;box-shadow:0 1px 30px 0 rgba(0,0,0,.25);-webkit-box-shadow:0 1px 30px 0 rgba(0,0,0,.25);padding:20px 0;*zoom:1}div.pp_woocommerce .pp_content_container:after,div.pp_woocommerce .pp_content_container:before{content:\" \";display:table}div.pp_woocommerce .pp_content_container:after{clear:both}div.pp_woocommerce .pp_loaderIcon{background:url(../images/ajax-loader.gif) center no-repeat}div.pp_woocommerce div.ppt{color:#000}div.pp_woocommerce .pp_gallery ul li a{border:1px solid rgba(0,0,0,.5);background:#fff;box-shadow:0 1px 2px 0 rgba(0,0,0,.2);-webkit-box-shadow:0 1px 2px 0 rgba(0,0,0,.2);-webkit-border-radius:2px;border-radius:2px;display:block}div.pp_woocommerce .pp_gallery ul li a:hover,div.pp_woocommerce .pp_gallery ul li.selected a{border-color:#000}div.pp_woocommerce .pp_next:before,div.pp_woocommerce .pp_previous:before{-webkit-border-radius:100%;border-radius:100%;height:1em;width:1em;text-shadow:0 1px 2px rgba(0,0,0,.5);background-color:#444;color:#fff!important;font-size:16px!important;line-height:1em;-webkit-transition:all ease-in-out .2s;-moz-transition:all ease-in-out .2s;-o-transition:all ease-in-out .2s;transition:all ease-in-out .2s;font-family:WooCommerce;content:\"\\e00b\";text-indent:0;display:none;position:absolute;top:50%;margin-top:-10px;text-align:center}div.pp_woocommerce .pp_next:before:hover,div.pp_woocommerce .pp_previous:before:hover{background-color:#000}div.pp_woocommerce .pp_next:hover:before,div.pp_woocommerce .pp_previous:hover:before{display:block}div.pp_woocommerce .pp_previous:before{left:1em}div.pp_woocommerce .pp_next:before{right:1em;font-family:WooCommerce;content:\"\\e008\"}div.pp_woocommerce .pp_details{margin:0;padding-top:1em}div.pp_woocommerce .pp_description,div.pp_woocommerce .pp_nav{font-size:14px}div.pp_woocommerce .pp_arrow_next,div.pp_woocommerce .pp_arrow_previous,div.pp_woocommerce .pp_nav,div.pp_woocommerce .pp_nav .pp_pause,div.pp_woocommerce .pp_nav p,div.pp_woocommerce .pp_play{margin:0}div.pp_woocommerce .pp_nav{margin-right:1em;position:relative}div.pp_woocommerce .pp_close{-webkit-border-radius:100%;border-radius:100%;height:1em;width:1em;text-shadow:0 1px 2px rgba(0,0,0,.5);background-color:#444;color:#fff!important;line-height:1em;-webkit-transition:all ease-in-out .2s;-moz-transition:all ease-in-out .2s;-o-transition:all ease-in-out .2s;transition:all ease-in-out .2s;top:-.5em;right:-.5em;font-size:1.618em!important}div.pp_woocommerce .pp_close:hover{background-color:#000}div.pp_woocommerce .pp_close:before{font-family:WooCommerce;content:\"\\e013\";display:block;position:absolute;top:0;left:0;right:0;bottom:0;text-align:center;text-indent:0}div.pp_woocommerce .pp_arrow_next,div.pp_woocommerce .pp_arrow_previous{-webkit-border-radius:100%;border-radius:100%;height:1em;width:1em;text-shadow:0 1px 2px rgba(0,0,0,.5);background-color:#444;color:#fff!important;font-size:16px!important;line-height:1em;-webkit-transition:all ease-in-out .2s;-moz-transition:all ease-in-out .2s;-o-transition:all ease-in-out .2s;transition:all ease-in-out .2s;position:relative;margin-top:-1px}div.pp_woocommerce .pp_arrow_next:hover,div.pp_woocommerce .pp_arrow_previous:hover{background-color:#000}div.pp_woocommerce .pp_arrow_next:before,div.pp_woocommerce .pp_arrow_previous:before{font-family:WooCommerce;content:\"\\e00b\";display:block;position:absolute;top:0;left:0;right:0;bottom:0;text-align:center;text-indent:0}div.pp_woocommerce .pp_arrow_previous{margin-right:.5em}div.pp_woocommerce .pp_arrow_next{margin-left:.5em}div.pp_woocommerce .pp_arrow_next:before{content:\"\\e008\"}div.pp_woocommerce a.pp_contract,div.pp_woocommerce a.pp_expand{-webkit-border-radius:100%;border-radius:100%;height:1em;width:1em;text-shadow:0 1px 2px rgba(0,0,0,.5);background-color:#444;color:#fff!important;line-height:1em;-webkit-transition:all ease-in-out .2s;-moz-transition:all ease-in-out .2s;-o-transition:all ease-in-out .2s;transition:all ease-in-out .2s;right:auto;left:-.5em;top:-.5em;font-size:1.618em!important}div.pp_woocommerce a.pp_contract:hover,div.pp_woocommerce a.pp_expand:hover{background-color:#000}div.pp_woocommerce a.pp_contract:before,div.pp_woocommerce a.pp_expand:before{font-family:WooCommerce;content:\"\\e005\";display:block;position:absolute;top:0;left:0;right:0;bottom:0;text-align:center;text-indent:0}div.pp_woocommerce a.pp_contract:before{content:\"\\e004\"}div.pp_woocommerce #respond{margin:0;width:100%;background:0 0;border:0;padding:0}div.pp_woocommerce #respond .form-submit{margin-top:0;float:none}div.pp_woocommerce .pp_inline{padding:0!important}@media only screen and (max-width:768px){div.pp_woocommerce{left:5%!important;right:5%!important;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;width:90%!important}div.pp_woocommerce .pp_contract,div.pp_woocommerce .pp_expand,div.pp_woocommerce .pp_gallery,div.pp_woocommerce .pp_next,div.pp_woocommerce .pp_previous{display:none!important}div.pp_woocommerce .pp_arrow_next,div.pp_woocommerce .pp_arrow_previous,div.pp_woocommerce .pp_close{height:44px;width:44px;font-size:44px;line-height:44px}div.pp_woocommerce .pp_arrow_next:before,div.pp_woocommerce .pp_arrow_previous:before,div.pp_woocommerce .pp_close:before{font-size:44px}div.pp_woocommerce .pp_description{display:none!important}.pp_content,div.pp_woocommerce .pp_details{width:100%!important}.pp_content img{width:100%!important;height:auto!important}.currentTextHolder{line-height:3}}div.pp_pic_holder a:focus{outline:0}div.pp_overlay{background:#000;display:none;left:0;position:absolute;top:0;width:100%;z-index:9999}div.pp_pic_holder{display:none;position:absolute;width:100px;z-index:10000}.pp_top{height:20px;position:relative}* html .pp_top{padding:0 20px}.pp_top .pp_left{height:20px;left:0;position:absolute;width:20px}.pp_top .pp_middle{height:20px;left:20px;position:absolute;right:20px}* html .pp_top .pp_middle{left:0;position:static}.pp_top .pp_right{height:20px;left:auto;position:absolute;right:0;top:0;width:20px}.pp_content{height:40px;min-width:40px}* html .pp_content{width:40px}.pp_fade{display:none}.pp_content_container{position:relative;text-align:left;width:100%}.pp_content_container .pp_left{padding-left:20px}.pp_content_container .pp_right{padding-right:20px}.pp_content_container .pp_details{float:left;margin:10px 0 2px}.pp_description{display:none;margin:0}.pp_social{float:left;margin:0}.pp_social .facebook{float:left;margin-left:5px;width:55px;overflow:hidden}.pp_social .twitter{float:left}.pp_nav{clear:right;float:left;margin:3px 10px 0 0}.pp_nav p{float:left;margin:2px 4px;white-space:nowrap}.pp_nav .pp_pause,.pp_nav .pp_play{float:left;margin-right:4px;text-indent:-10000px}a.pp_arrow_next,a.pp_arrow_previous{display:block;float:left;height:15px;margin-top:3px;text-indent:-100000px;width:14px}.pp_hoverContainer{position:absolute;top:0;width:100%;z-index:2000}.pp_gallery{display:none;left:50%;margin-top:-50px;position:absolute;z-index:10000}.pp_gallery div{float:left;overflow:hidden;position:relative}.pp_gallery ul{float:left;height:35px;margin:0 0 0 5px;padding:0;position:relative;white-space:nowrap}.pp_gallery ul a{border:1px #000 solid;border:1px rgba(0,0,0,.5) solid;display:block;float:left;height:33px;overflow:hidden}.pp_gallery li.selected a,.pp_gallery ul a:hover{border-color:#fff}.pp_gallery ul a img{border:0}.pp_gallery li{display:block;float:left;margin:0 5px 0 0;padding:0}.pp_gallery li.default a{display:block;height:33px;width:50px}.pp_gallery li.default a img{display:none}.pp_gallery .pp_arrow_next,.pp_gallery .pp_arrow_previous{margin-top:7px!important}a.pp_next{display:block;float:right;height:100%;text-indent:-10000px;width:49%}a.pp_previous{display:block;float:left;height:100%;text-indent:-10000px;width:49%}a.pp_contract,a.pp_expand{cursor:pointer;display:none;height:20px;position:absolute;right:30px;text-indent:-10000px;top:10px;width:20px;z-index:20000}a.pp_close{position:absolute;right:0;top:0;display:block;text-indent:-10000px}.pp_bottom{height:20px;position:relative}* html .pp_bottom{padding:0 20px}.pp_bottom .pp_left{height:20px;left:0;position:absolute;width:20px}.pp_bottom .pp_middle{height:20px;left:20px;position:absolute;right:20px}* html .pp_bottom .pp_middle{left:0;position:static}.pp_bottom .pp_right{height:20px;left:auto;position:absolute;right:0;top:0;width:20px}.pp_loaderIcon{display:block;height:24px;left:50%;margin:-12px 0 0 -12px;position:absolute;top:50%;width:24px}#pp_full_res .pp_inline{text-align:left}div.ppt{color:#fff!important;font-weight:700;display:none;font-size:17px;margin:0 0 5px 15px;z-index:9999}" ]
[ 0 ]
PreciseBugs
{"buggy_code_end_loc": [8, 242, 71, 2, 10, 379, 21, 19], "buggy_code_start_loc": [6, 196, 31, 1, 1, 31, 19, 18], "filenames": ["README.txt", "admin/class-woo-popup-admin.php", "admin/views/admin.php", "public/assets/css/prettyPhoto.css", "public/assets/js/public.js", "public/class-woo-popup.php", "public/views/public.php", "woo-popup.php"], "fixing_code_end_loc": [8, 251, 109, 171, 30, 384, 23, 19], "fixing_code_start_loc": [6, 197, 32, 1, 1, 31, 19, 18], "message": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:woo-popup_project:woo-popup:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "FDF073CD-7548-4114-B554-A83685981B77", "versionEndExcluding": "1.3.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327."}], "evaluatorComment": null, "id": "CVE-2015-10095", "lastModified": "2023-03-13T15:18:44.873", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-03-06T21:15:10.150", "references": [{"source": "cna@vuldb.com", "tags": ["Patch"], "url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, {"source": "cna@vuldb.com", "tags": ["Release Notes"], "url": "https://github.com/wp-plugins/woo-popup/releases/tag/1.3.0"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?ctiid.222327"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?id.222327"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, "type": "CWE-79"}
202
Determine whether the {function_name} code is vulnerable or not.
[ "div.pp_default .pp_top,div.pp_default .pp_top .pp_middle,div.pp_default .pp_top .pp_left,div.pp_default .pp_top .pp_right,div.pp_default .pp_bottom,div.pp_default .pp_bottom .pp_left,div.pp_default .pp_bottom .pp_middle,div.pp_default .pp_bottom .pp_right{height:13px}\ndiv.pp_default .pp_top .pp_left{background:url(../images/prettyPhoto/default/sprite.png) -78px -93px no-repeat}\ndiv.pp_default .pp_top .pp_middle{background:url(../images/prettyPhoto/default/sprite_x.png) top left repeat-x}\ndiv.pp_default .pp_top .pp_right{background:url(../images/prettyPhoto/default/sprite.png) -112px -93px no-repeat}\ndiv.pp_default .pp_content .ppt{color:#f8f8f8}\ndiv.pp_default .pp_content_container .pp_left{background:url(../images/prettyPhoto/default/sprite_y.png) -7px 0 repeat-y;padding-left:13px}\ndiv.pp_default .pp_content_container .pp_right{background:url(../images/prettyPhoto/default/sprite_y.png) top right repeat-y;padding-right:13px}\ndiv.pp_default .pp_next:hover{background:url(../images/prettyPhoto/default/sprite_next.png) center right no-repeat;cursor:pointer}\ndiv.pp_default .pp_previous:hover{background:url(../images/prettyPhoto/default/sprite_prev.png) center left no-repeat;cursor:pointer}\ndiv.pp_default .pp_expand{background:url(../images/prettyPhoto/default/sprite.png) 0 -29px no-repeat;cursor:pointer;width:28px;height:28px}\ndiv.pp_default .pp_expand:hover{background:url(../images/prettyPhoto/default/sprite.png) 0 -56px no-repeat;cursor:pointer}\ndiv.pp_default .pp_contract{background:url(../images/prettyPhoto/default/sprite.png) 0 -84px no-repeat;cursor:pointer;width:28px;height:28px}\ndiv.pp_default .pp_contract:hover{background:url(../images/prettyPhoto/default/sprite.png) 0 -113px no-repeat;cursor:pointer}\ndiv.pp_default .pp_close{width:30px;height:30px;background:url(../images/prettyPhoto/default/sprite.png) 2px 1px no-repeat;cursor:pointer}\ndiv.pp_default .pp_gallery ul li a{background:url(../images/prettyPhoto/default/default_thumb.png) center center #f8f8f8;border:1px solid #aaa}\ndiv.pp_default .pp_social{margin-top:7px}\ndiv.pp_default .pp_gallery a.pp_arrow_previous,div.pp_default .pp_gallery a.pp_arrow_next{position:static;left:auto}\ndiv.pp_default .pp_nav .pp_play,div.pp_default .pp_nav .pp_pause{background:url(../images/prettyPhoto/default/sprite.png) -51px 1px no-repeat;height:30px;width:30px}\ndiv.pp_default .pp_nav .pp_pause{background-position:-51px -29px}\ndiv.pp_default a.pp_arrow_previous,div.pp_default a.pp_arrow_next{background:url(../images/prettyPhoto/default/sprite.png) -31px -3px no-repeat;height:20px;width:20px;margin:4px 0 0}\ndiv.pp_default a.pp_arrow_next{left:52px;background-position:-82px -3px}\ndiv.pp_default .pp_content_container .pp_details{margin-top:5px}\ndiv.pp_default .pp_nav{clear:none;height:30px;width:110px;position:relative}\ndiv.pp_default .pp_nav .currentTextHolder{font-family:Georgia;font-style:italic;color:#999;font-size:11px;left:75px;line-height:25px;position:absolute;top:2px;margin:0;padding:0 0 0 10px}\ndiv.pp_default .pp_close:hover,div.pp_default .pp_nav .pp_play:hover,div.pp_default .pp_nav .pp_pause:hover,div.pp_default .pp_arrow_next:hover,div.pp_default .pp_arrow_previous:hover{opacity:0.7}\ndiv.pp_default .pp_description{font-size:11px;font-weight:700;line-height:14px;margin:5px 50px 5px 0}\ndiv.pp_default .pp_bottom .pp_left{background:url(../images/prettyPhoto/default/sprite.png) -78px -127px no-repeat}\ndiv.pp_default .pp_bottom .pp_middle{background:url(../images/prettyPhoto/default/sprite_x.png) bottom left repeat-x}\ndiv.pp_default .pp_bottom .pp_right{background:url(../images/prettyPhoto/default/sprite.png) -112px -127px no-repeat}\ndiv.pp_default .pp_loaderIcon{background:url(../images/prettyPhoto/default/loader.gif) center center no-repeat}\ndiv.light_rounded .pp_top .pp_left{background:url(../images/prettyPhoto/light_rounded/sprite.png) -88px -53px no-repeat}\ndiv.light_rounded .pp_top .pp_right{background:url(../images/prettyPhoto/light_rounded/sprite.png) -110px -53px no-repeat}\ndiv.light_rounded .pp_next:hover{background:url(../images/prettyPhoto/light_rounded/btnNext.png) center right no-repeat;cursor:pointer}\ndiv.light_rounded .pp_previous:hover{background:url(../images/prettyPhoto/light_rounded/btnPrevious.png) center left no-repeat;cursor:pointer}\ndiv.light_rounded .pp_expand{background:url(../images/prettyPhoto/light_rounded/sprite.png) -31px -26px no-repeat;cursor:pointer}\ndiv.light_rounded .pp_expand:hover{background:url(../images/prettyPhoto/light_rounded/sprite.png) -31px -47px no-repeat;cursor:pointer}\ndiv.light_rounded .pp_contract{background:url(../images/prettyPhoto/light_rounded/sprite.png) 0 -26px no-repeat;cursor:pointer}\ndiv.light_rounded .pp_contract:hover{background:url(../images/prettyPhoto/light_rounded/sprite.png) 0 -47px no-repeat;cursor:pointer}\ndiv.light_rounded .pp_close{width:75px;height:22px;background:url(../images/prettyPhoto/light_rounded/sprite.png) -1px -1px no-repeat;cursor:pointer}\ndiv.light_rounded .pp_nav .pp_play{background:url(../images/prettyPhoto/light_rounded/sprite.png) -1px -100px no-repeat;height:15px;width:14px}\ndiv.light_rounded .pp_nav .pp_pause{background:url(../images/prettyPhoto/light_rounded/sprite.png) -24px -100px no-repeat;height:15px;width:14px}\ndiv.light_rounded .pp_arrow_previous{background:url(../images/prettyPhoto/light_rounded/sprite.png) 0 -71px no-repeat}\ndiv.light_rounded .pp_arrow_next{background:url(../images/prettyPhoto/light_rounded/sprite.png) -22px -71px no-repeat}\ndiv.light_rounded .pp_bottom .pp_left{background:url(../images/prettyPhoto/light_rounded/sprite.png) -88px -80px no-repeat}\ndiv.light_rounded .pp_bottom .pp_right{background:url(../images/prettyPhoto/light_rounded/sprite.png) -110px -80px no-repeat}\ndiv.dark_rounded .pp_top .pp_left{background:url(../images/prettyPhoto/dark_rounded/sprite.png) -88px -53px no-repeat}\ndiv.dark_rounded .pp_top .pp_right{background:url(../images/prettyPhoto/dark_rounded/sprite.png) -110px -53px no-repeat}\ndiv.dark_rounded .pp_content_container .pp_left{background:url(../images/prettyPhoto/dark_rounded/contentPattern.png) top left repeat-y}\ndiv.dark_rounded .pp_content_container .pp_right{background:url(../images/prettyPhoto/dark_rounded/contentPattern.png) top right repeat-y}\ndiv.dark_rounded .pp_next:hover{background:url(../images/prettyPhoto/dark_rounded/btnNext.png) center right no-repeat;cursor:pointer}\ndiv.dark_rounded .pp_previous:hover{background:url(../images/prettyPhoto/dark_rounded/btnPrevious.png) center left no-repeat;cursor:pointer}\ndiv.dark_rounded .pp_expand{background:url(../images/prettyPhoto/dark_rounded/sprite.png) -31px -26px no-repeat;cursor:pointer}\ndiv.dark_rounded .pp_expand:hover{background:url(../images/prettyPhoto/dark_rounded/sprite.png) -31px -47px no-repeat;cursor:pointer}\ndiv.dark_rounded .pp_contract{background:url(../images/prettyPhoto/dark_rounded/sprite.png) 0 -26px no-repeat;cursor:pointer}\ndiv.dark_rounded .pp_contract:hover{background:url(../images/prettyPhoto/dark_rounded/sprite.png) 0 -47px no-repeat;cursor:pointer}\ndiv.dark_rounded .pp_close{width:75px;height:22px;background:url(../images/prettyPhoto/dark_rounded/sprite.png) -1px -1px no-repeat;cursor:pointer}\ndiv.dark_rounded .pp_description{margin-right:85px;color:#fff}\ndiv.dark_rounded .pp_nav .pp_play{background:url(../images/prettyPhoto/dark_rounded/sprite.png) -1px -100px no-repeat;height:15px;width:14px}\ndiv.dark_rounded .pp_nav .pp_pause{background:url(../images/prettyPhoto/dark_rounded/sprite.png) -24px -100px no-repeat;height:15px;width:14px}\ndiv.dark_rounded .pp_arrow_previous{background:url(../images/prettyPhoto/dark_rounded/sprite.png) 0 -71px no-repeat}\ndiv.dark_rounded .pp_arrow_next{background:url(../images/prettyPhoto/dark_rounded/sprite.png) -22px -71px no-repeat}\ndiv.dark_rounded .pp_bottom .pp_left{background:url(../images/prettyPhoto/dark_rounded/sprite.png) -88px -80px no-repeat}\ndiv.dark_rounded .pp_bottom .pp_right{background:url(../images/prettyPhoto/dark_rounded/sprite.png) -110px -80px no-repeat}\ndiv.dark_rounded .pp_loaderIcon{background:url(../images/prettyPhoto/dark_rounded/loader.gif) center center no-repeat}\ndiv.dark_square .pp_left,div.dark_square .pp_middle,div.dark_square .pp_right,div.dark_square .pp_content{background:#000}\ndiv.dark_square .pp_description{color:#fff;margin:0 85px 0 0}\ndiv.dark_square .pp_loaderIcon{background:url(../images/prettyPhoto/dark_square/loader.gif) center center no-repeat}\ndiv.dark_square .pp_expand{background:url(../images/prettyPhoto/dark_square/sprite.png) -31px -26px no-repeat;cursor:pointer}\ndiv.dark_square .pp_expand:hover{background:url(../images/prettyPhoto/dark_square/sprite.png) -31px -47px no-repeat;cursor:pointer}\ndiv.dark_square .pp_contract{background:url(../images/prettyPhoto/dark_square/sprite.png) 0 -26px no-repeat;cursor:pointer}\ndiv.dark_square .pp_contract:hover{background:url(../images/prettyPhoto/dark_square/sprite.png) 0 -47px no-repeat;cursor:pointer}\ndiv.dark_square .pp_close{width:75px;height:22px;background:url(../images/prettyPhoto/dark_square/sprite.png) -1px -1px no-repeat;cursor:pointer}\ndiv.dark_square .pp_nav{clear:none}\ndiv.dark_square .pp_nav .pp_play{background:url(../images/prettyPhoto/dark_square/sprite.png) -1px -100px no-repeat;height:15px;width:14px}\ndiv.dark_square .pp_nav .pp_pause{background:url(../images/prettyPhoto/dark_square/sprite.png) -24px -100px no-repeat;height:15px;width:14px}\ndiv.dark_square .pp_arrow_previous{background:url(../images/prettyPhoto/dark_square/sprite.png) 0 -71px no-repeat}\ndiv.dark_square .pp_arrow_next{background:url(../images/prettyPhoto/dark_square/sprite.png) -22px -71px no-repeat}\ndiv.dark_square .pp_next:hover{background:url(../images/prettyPhoto/dark_square/btnNext.png) center right no-repeat;cursor:pointer}\ndiv.dark_square .pp_previous:hover{background:url(../images/prettyPhoto/dark_square/btnPrevious.png) center left no-repeat;cursor:pointer}\ndiv.light_square .pp_expand{background:url(../images/prettyPhoto/light_square/sprite.png) -31px -26px no-repeat;cursor:pointer}\ndiv.light_square .pp_expand:hover{background:url(../images/prettyPhoto/light_square/sprite.png) -31px -47px no-repeat;cursor:pointer}\ndiv.light_square .pp_contract{background:url(../images/prettyPhoto/light_square/sprite.png) 0 -26px no-repeat;cursor:pointer}\ndiv.light_square .pp_contract:hover{background:url(../images/prettyPhoto/light_square/sprite.png) 0 -47px no-repeat;cursor:pointer}\ndiv.light_square .pp_close{width:75px;height:22px;background:url(../images/prettyPhoto/light_square/sprite.png) -1px -1px no-repeat;cursor:pointer}\ndiv.light_square .pp_nav .pp_play{background:url(../images/prettyPhoto/light_square/sprite.png) -1px -100px no-repeat;height:15px;width:14px}\ndiv.light_square .pp_nav .pp_pause{background:url(../images/prettyPhoto/light_square/sprite.png) -24px -100px no-repeat;height:15px;width:14px}\ndiv.light_square .pp_arrow_previous{background:url(../images/prettyPhoto/light_square/sprite.png) 0 -71px no-repeat}\ndiv.light_square .pp_arrow_next{background:url(../images/prettyPhoto/light_square/sprite.png) -22px -71px no-repeat}\ndiv.light_square .pp_next:hover{background:url(../images/prettyPhoto/light_square/btnNext.png) center right no-repeat;cursor:pointer}\ndiv.light_square .pp_previous:hover{background:url(../images/prettyPhoto/light_square/btnPrevious.png) center left no-repeat;cursor:pointer}\ndiv.facebook .pp_top .pp_left{background:url(../images/prettyPhoto/facebook/sprite.png) -88px -53px no-repeat}\ndiv.facebook .pp_top .pp_middle{background:url(../images/prettyPhoto/facebook/contentPatternTop.png) top left repeat-x}\ndiv.facebook .pp_top .pp_right{background:url(../images/prettyPhoto/facebook/sprite.png) -110px -53px no-repeat}\ndiv.facebook .pp_content_container .pp_left{background:url(../images/prettyPhoto/facebook/contentPatternLeft.png) top left repeat-y}\ndiv.facebook .pp_content_container .pp_right{background:url(../images/prettyPhoto/facebook/contentPatternRight.png) top right repeat-y}\ndiv.facebook .pp_expand{background:url(../images/prettyPhoto/facebook/sprite.png) -31px -26px no-repeat;cursor:pointer}\ndiv.facebook .pp_expand:hover{background:url(../images/prettyPhoto/facebook/sprite.png) -31px -47px no-repeat;cursor:pointer}\ndiv.facebook .pp_contract{background:url(../images/prettyPhoto/facebook/sprite.png) 0 -26px no-repeat;cursor:pointer}\ndiv.facebook .pp_contract:hover{background:url(../images/prettyPhoto/facebook/sprite.png) 0 -47px no-repeat;cursor:pointer}\ndiv.facebook .pp_close{width:22px;height:22px;background:url(../images/prettyPhoto/facebook/sprite.png) -1px -1px no-repeat;cursor:pointer}\ndiv.facebook .pp_description{margin:0 37px 0 0}\ndiv.facebook .pp_loaderIcon{background:url(../images/prettyPhoto/facebook/loader.gif) center center no-repeat}\ndiv.facebook .pp_arrow_previous{background:url(../images/prettyPhoto/facebook/sprite.png) 0 -71px no-repeat;height:22px;margin-top:0;width:22px}\ndiv.facebook .pp_arrow_previous.disabled{background-position:0 -96px;cursor:default}\ndiv.facebook .pp_arrow_next{background:url(../images/prettyPhoto/facebook/sprite.png) -32px -71px no-repeat;height:22px;margin-top:0;width:22px}\ndiv.facebook .pp_arrow_next.disabled{background-position:-32px -96px;cursor:default}\ndiv.facebook .pp_nav{margin-top:0}\ndiv.facebook .pp_nav p{font-size:15px;padding:0 3px 0 4px}\ndiv.facebook .pp_nav .pp_play{background:url(../images/prettyPhoto/facebook/sprite.png) -1px -123px no-repeat;height:22px;width:22px}\ndiv.facebook .pp_nav .pp_pause{background:url(../images/prettyPhoto/facebook/sprite.png) -32px -123px no-repeat;height:22px;width:22px}\ndiv.facebook .pp_next:hover{background:url(../images/prettyPhoto/facebook/btnNext.png) center right no-repeat;cursor:pointer}\ndiv.facebook .pp_previous:hover{background:url(../images/prettyPhoto/facebook/btnPrevious.png) center left no-repeat;cursor:pointer}\ndiv.facebook .pp_bottom .pp_left{background:url(../images/prettyPhoto/facebook/sprite.png) -88px -80px no-repeat}\ndiv.facebook .pp_bottom .pp_middle{background:url(../images/prettyPhoto/facebook/contentPatternBottom.png) top left repeat-x}\ndiv.facebook .pp_bottom .pp_right{background:url(../images/prettyPhoto/facebook/sprite.png) -110px -80px no-repeat}\ndiv.pp_pic_holder a:focus{outline:none}\ndiv.pp_overlay{background:#000;display:none;left:0;position:absolute;top:0;width:100%;z-index:9500}\ndiv.pp_pic_holder{display:none;position:absolute;width:100px;z-index:10000}\n.pp_content{height:40px;min-width:40px}\n* html .pp_content{width:40px}\n.pp_content_container{position:relative;text-align:left;width:100%}\n.pp_content_container .pp_left{padding-left:20px}\n.pp_content_container .pp_right{padding-right:20px}\n.pp_content_container .pp_details{float:left;margin:10px 0 2px}\n.pp_description{display:none;margin:0}\n.pp_social{float:left;margin:0}\n.pp_social .facebook{float:left;margin-left:5px;width:55px;overflow:hidden}\n.pp_social .twitter{float:left}\n.pp_nav{clear:right;float:left;margin:3px 10px 0 0}\n.pp_nav p{float:left;white-space:nowrap;margin:2px 4px}\n.pp_nav .pp_play,.pp_nav .pp_pause{float:left;margin-right:4px;text-indent:-10000px}\na.pp_arrow_previous,a.pp_arrow_next{display:block;float:left;height:15px;margin-top:3px;overflow:hidden;text-indent:-10000px;width:14px}\n.pp_hoverContainer{position:absolute;top:0;width:100%;z-index:2000}\n.pp_gallery{display:none;left:50%;margin-top:-50px;position:absolute;z-index:10000}\n.pp_gallery div{float:left;overflow:hidden;position:relative}\n.pp_gallery ul{float:left;height:35px;position:relative;white-space:nowrap;margin:0 0 0 5px;padding:0}\n.pp_gallery ul a{border:1px rgba(0,0,0,0.5) solid;display:block;float:left;height:33px;overflow:hidden}\n.pp_gallery ul a img{border:0}\n.pp_gallery li{display:block;float:left;margin:0 5px 0 0;padding:0}\n.pp_gallery li.default a{background:url(../images/prettyPhoto/facebook/default_thumbnail.gif) 0 0 no-repeat;display:block;height:33px;width:50px}\n.pp_gallery .pp_arrow_previous,.pp_gallery .pp_arrow_next{margin-top:7px!important}\na.pp_next{background:url(../images/prettyPhoto/light_rounded/btnNext.png) 10000px 10000px no-repeat;display:block;float:right;height:100%;text-indent:-10000px;width:49%}\na.pp_previous{background:url(../images/prettyPhoto/light_rounded/btnNext.png) 10000px 10000px no-repeat;display:block;float:left;height:100%;text-indent:-10000px;width:49%}\na.pp_expand,a.pp_contract{cursor:pointer;display:none;height:20px;position:absolute;right:30px;text-indent:-10000px;top:10px;width:20px;z-index:20000}\na.pp_close{position:absolute;right:0;top:0;display:block;line-height:22px;text-indent:-10000px}\n.pp_loaderIcon{display:block;height:24px;left:50%;position:absolute;top:50%;width:24px;margin:-12px 0 0 -12px}\n#pp_full_res{line-height:1!important}\n#pp_full_res .pp_inline{text-align:left}\n#pp_full_res .pp_inline p{margin:0 0 15px}\ndiv.ppt{color:#fff;display:none;font-size:17px;z-index:9999;margin:0 0 5px 15px}\ndiv.pp_default .pp_content,div.light_rounded .pp_content{background-color:#fff}\ndiv.pp_default #pp_full_res .pp_inline,div.light_rounded .pp_content .ppt,div.light_rounded #pp_full_res .pp_inline,div.light_square .pp_content .ppt,div.light_square #pp_full_res .pp_inline,div.facebook .pp_content .ppt,div.facebook #pp_full_res .pp_inline{color:#000}\ndiv.pp_default .pp_gallery ul li a:hover,div.pp_default .pp_gallery ul li.selected a,.pp_gallery ul a:hover,.pp_gallery li.selected a{border-color:#fff}\ndiv.pp_default .pp_details,div.light_rounded .pp_details,div.dark_rounded .pp_details,div.dark_square .pp_details,div.light_square .pp_details,div.facebook .pp_details{position:relative}\ndiv.light_rounded .pp_top .pp_middle,div.light_rounded .pp_content_container .pp_left,div.light_rounded .pp_content_container .pp_right,div.light_rounded .pp_bottom .pp_middle,div.light_square .pp_left,div.light_square .pp_middle,div.light_square .pp_right,div.light_square .pp_content,div.facebook .pp_content{background:#fff}\ndiv.light_rounded .pp_description,div.light_square .pp_description{margin-right:85px}\ndiv.light_rounded .pp_gallery a.pp_arrow_previous,div.light_rounded .pp_gallery a.pp_arrow_next,div.dark_rounded .pp_gallery a.pp_arrow_previous,div.dark_rounded .pp_gallery a.pp_arrow_next,div.dark_square .pp_gallery a.pp_arrow_previous,div.dark_square .pp_gallery a.pp_arrow_next,div.light_square .pp_gallery a.pp_arrow_previous,div.light_square .pp_gallery a.pp_arrow_next{margin-top:12px!important}\ndiv.light_rounded .pp_arrow_previous.disabled,div.dark_rounded .pp_arrow_previous.disabled,div.dark_square .pp_arrow_previous.disabled,div.light_square .pp_arrow_previous.disabled{background-position:0 -87px;cursor:default}\ndiv.light_rounded .pp_arrow_next.disabled,div.dark_rounded .pp_arrow_next.disabled,div.dark_square .pp_arrow_next.disabled,div.light_square .pp_arrow_next.disabled{background-position:-22px -87px;cursor:default}\ndiv.light_rounded .pp_loaderIcon,div.light_square .pp_loaderIcon{background:url(../images/prettyPhoto/light_rounded/loader.gif) center center no-repeat}\ndiv.dark_rounded .pp_top .pp_middle,div.dark_rounded .pp_content,div.dark_rounded .pp_bottom .pp_middle{background:url(../images/prettyPhoto/dark_rounded/contentPattern.png) top left repeat}\ndiv.dark_rounded .currentTextHolder,div.dark_square .currentTextHolder{color:#c4c4c4}\ndiv.dark_rounded #pp_full_res .pp_inline,div.dark_square #pp_full_res .pp_inline{color:#fff}\n.pp_top,.pp_bottom{height:20px;position:relative}\n* html .pp_top,* html .pp_bottom{padding:0 20px}\n.pp_top .pp_left,.pp_bottom .pp_left{height:20px;left:0;position:absolute;width:20px}\n.pp_top .pp_middle,.pp_bottom .pp_middle{height:20px;left:20px;position:absolute;right:20px}\n* html .pp_top .pp_middle,* html .pp_bottom .pp_middle{left:0;position:static}\n.pp_top .pp_right,.pp_bottom .pp_right{height:20px;left:auto;position:absolute;right:0;top:0;width:20px}\n.pp_fade,.pp_gallery li.default a img{display:none}" ]
[ 1 ]
PreciseBugs
{"buggy_code_end_loc": [8, 242, 71, 2, 10, 379, 21, 19], "buggy_code_start_loc": [6, 196, 31, 1, 1, 31, 19, 18], "filenames": ["README.txt", "admin/class-woo-popup-admin.php", "admin/views/admin.php", "public/assets/css/prettyPhoto.css", "public/assets/js/public.js", "public/class-woo-popup.php", "public/views/public.php", "woo-popup.php"], "fixing_code_end_loc": [8, 251, 109, 171, 30, 384, 23, 19], "fixing_code_start_loc": [6, 197, 32, 1, 1, 31, 19, 18], "message": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:woo-popup_project:woo-popup:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "FDF073CD-7548-4114-B554-A83685981B77", "versionEndExcluding": "1.3.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327."}], "evaluatorComment": null, "id": "CVE-2015-10095", "lastModified": "2023-03-13T15:18:44.873", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-03-06T21:15:10.150", "references": [{"source": "cna@vuldb.com", "tags": ["Patch"], "url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, {"source": "cna@vuldb.com", "tags": ["Release Notes"], "url": "https://github.com/wp-plugins/woo-popup/releases/tag/1.3.0"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?ctiid.222327"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?id.222327"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, "type": "CWE-79"}
202
Determine whether the {function_name} code is vulnerable or not.
[ "jQuery(document).ready(function ( ) {\n\t\"use strict\";\n\t//Append the inline content to the body\n\tjQuery(woo_popup['popup_content']).appendTo('body');", "", "\t//Open that content on load with prettyPhoto\n\tjQuery.prettyPhoto.open('#woopopup');", "", "});" ]
[ 0, 1, 0, 1, 0 ]
PreciseBugs
{"buggy_code_end_loc": [8, 242, 71, 2, 10, 379, 21, 19], "buggy_code_start_loc": [6, 196, 31, 1, 1, 31, 19, 18], "filenames": ["README.txt", "admin/class-woo-popup-admin.php", "admin/views/admin.php", "public/assets/css/prettyPhoto.css", "public/assets/js/public.js", "public/class-woo-popup.php", "public/views/public.php", "woo-popup.php"], "fixing_code_end_loc": [8, 251, 109, 171, 30, 384, 23, 19], "fixing_code_start_loc": [6, 197, 32, 1, 1, 31, 19, 18], "message": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:woo-popup_project:woo-popup:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "FDF073CD-7548-4114-B554-A83685981B77", "versionEndExcluding": "1.3.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327."}], "evaluatorComment": null, "id": "CVE-2015-10095", "lastModified": "2023-03-13T15:18:44.873", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-03-06T21:15:10.150", "references": [{"source": "cna@vuldb.com", "tags": ["Patch"], "url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, {"source": "cna@vuldb.com", "tags": ["Release Notes"], "url": "https://github.com/wp-plugins/woo-popup/releases/tag/1.3.0"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?ctiid.222327"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?id.222327"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, "type": "CWE-79"}
202
Determine whether the {function_name} code is vulnerable or not.
[ "(function($){\n\t$(function(){\n\t\t\"use strict\";", "", "\t\t//Append the inline content to the body\n\t\t$(woo_popup['popup_content']).appendTo('body');", "", "\t\tvar popupTheme = plugin_options_vars.theme;", "\t\t// Init Lightbox\n\t\t$().prettyPhoto({\n\t\t\topacity: 0.80, /* Value between 0 and 1 */\n\t\t\tshow_title: true, /* true/false */\n\t\t\tallow_resize: true, /* Resize the photos bigger than viewport. true/false */\n\t\t\ttheme: popupTheme, /* light_rounded / dark_rounded / light_square / dark_square / facebook */\n\t\t\thorizontal_padding: 20, /* The padding on each side of the picture */\n\t\t\tautoplay: true, /* Automatically start videos: True/False */\n\t\t\tmodal: false, /* If set to true, only the close button will close the window */\n\t\t\tdeeplinking: true, /* Allow prettyPhoto to update the url to enable deeplinking. */\n\t\t\tkeyboard_shortcuts: true, /* Set to false if you open forms inside prettyPhoto */\n\t\t\tcallback: function(){}, /* Called when prettyPhoto is closed */\n\t\t\tsocial_tools: '<div class=\"pp_social\"><div class=\"twitter\"><a href=\"http://twitter.com/share\" class=\"twitter-share-button\" data-count=\"none\">Tweet</a><script type=\"text/javascript\" src=\"http://platform.twitter.com/widgets.js\"></script></div><div class=\"facebook\"><iframe src=\"http://www.facebook.com/plugins/like.php?locale=en_US&href='+location.href+'&amp;layout=button_count&amp;show_faces=true&amp;width=500&amp;action=like&amp;font&amp;colorscheme=light&amp;height=23\" scrolling=\"no\" frameborder=\"0\" style=\"border:none; overflow:hidden; width:500px; height:23px;\" allowTransparency=\"true\"></iframe></div></div>' /* html or false to disable */\n\t\t});", "\t\t//Open that content on load with prettyPhoto\n\t\t$.prettyPhoto.open('#woopopup');\n\t});\n})(jQuery);" ]
[ 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [8, 242, 71, 2, 10, 379, 21, 19], "buggy_code_start_loc": [6, 196, 31, 1, 1, 31, 19, 18], "filenames": ["README.txt", "admin/class-woo-popup-admin.php", "admin/views/admin.php", "public/assets/css/prettyPhoto.css", "public/assets/js/public.js", "public/class-woo-popup.php", "public/views/public.php", "woo-popup.php"], "fixing_code_end_loc": [8, 251, 109, 171, 30, 384, 23, 19], "fixing_code_start_loc": [6, 197, 32, 1, 1, 31, 19, 18], "message": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:woo-popup_project:woo-popup:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "FDF073CD-7548-4114-B554-A83685981B77", "versionEndExcluding": "1.3.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327."}], "evaluatorComment": null, "id": "CVE-2015-10095", "lastModified": "2023-03-13T15:18:44.873", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-03-06T21:15:10.150", "references": [{"source": "cna@vuldb.com", "tags": ["Patch"], "url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, {"source": "cna@vuldb.com", "tags": ["Release Notes"], "url": "https://github.com/wp-plugins/woo-popup/releases/tag/1.3.0"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?ctiid.222327"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?id.222327"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, "type": "CWE-79"}
202
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * woo-popup\n *\n * @package WooPopup\n * @author Guillaume Kanoufi <guillaume@lostwebdesigns.com>\n * @license GPL-2.0+\n * @link http://lostwebdesigns.com\n * @copyright 2014 woocommerce, popup, woopopup\n */", "/**\n * Plugin class. This class should ideally be used to work with the\n * public-facing side of the WordPress site.\n *\n * If you're interested in introducing administrative or dashboard\n * functionality, then refer to `class-woo-popup-admin.php`\n *\n * @package WooPopup\n * @author Guillaume Kanoufi <guillaume@lostwebdesigns.com>\n */\nclass WooPopup {", "\t/**\n\t * Plugin version, used for cache-busting of style and script file references.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @var string\n\t */", "\tconst VERSION = '1.2.0';", "\n\t/**\n\t * Unique identifier for your plugin.\n\t *\n\t *\n\t * The variable name is used as the text domain when internationalizing strings\n\t * of text. Its value should match the Text Domain file header in the main\n\t * plugin file.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @var string\n\t */\n\tprotected $plugin_slug = 'woo-popup';", "\t/**\n\t * Unique identifier for your plugin options.\n\t *\n\t *\n\t *\n\t * @since 1.0.0\n\t *\n\t * @var string\n\t */\n\tprivate $options_slug = 'woo-popup_options';", "\n\t/**\n\t * Default Settings Values.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @var string\n\t */\n\tprivate $options_data = array(\n\t\t'popup_content' => 'This will be your pop up content',\n\t\t'popup_page' => ' ',\n\t\t'popup_class' => 'notice',\n\t\t'popup_permanent' => '0', //Default set to 0 so date are apparant\n\t\t'start_date' => '2014-02-02', //Set up an old date so if default the pop up won't be fired\n\t\t'end_date' => '2014-02-04', //Set up an old date so if default the pop up won't be fired\n\t\t'popup_timezone' => 'Europe/Paris'\n\t);", "\t/**\n\t * Instance of this class.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @var object\n\t */\n\tprotected static $instance = null;", "\t/**\n\t * Initialize the plugin by setting localization and loading public scripts\n\t * and styles.\n\t *\n\t * @since 1.0.0\n\t */\n\tprivate function __construct() {", "\t\t// Load plugin text domain\n\t\tadd_action( 'init', array( $this, 'load_plugin_textdomain' ) );", "\t\t// Activate plugin when new blog is added\n\t\tadd_action( 'wpmu_new_blog', array( $this, 'activate_new_site' ) );", "\t\t// Load public-facing style sheet and JavaScript.\n\t\tadd_action( 'wp_enqueue_scripts', array( $this, 'enqueue_styles' ) );\n\t\tadd_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );", "\t\t// Pass the php variable through wp_localize_script\n\t\tadd_action( 'wp_enqueue_scripts', array( $this, 'pass_php_vars' ) );", "\t}", "\t/**\n\t * Return the plugin slug.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @return Plugin slug variable.\n\t */\n\tpublic function get_plugin_slug() {\n\t\treturn $this->plugin_slug;\n\t}", "\t/**\n\t * Return the plugin options slug.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @return Plugin slug variable.\n\t */\n\tpublic function get_plugin_options_slug() {\n\t\treturn $this->options_slug;\n\t}", "\n\t/**\n\t * Return the plugin options default data.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @return Plugin options variable.\n\t */\n\tpublic function get_plugin_options_data() {\n\t\treturn $this->options_data;\n\t}", "\n\t/**\n\t * Return an instance of this class.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @return object A single instance of this class.\n\t */\n\tpublic static function get_instance() {", "\t\t// If the single instance hasn't been set, set it now.\n\t\tif ( null == self::$instance ) {\n\t\t\tself::$instance = new self;\n\t\t}", "\t\treturn self::$instance;\n\t}", "\t/**\n\t * Fired when the plugin is activated.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @param boolean $network_wide True if WPMU superadmin uses\n\t * \"Network Activate\" action, false if\n\t * WPMU is disabled or plugin is\n\t * activated on an individual blog.\n\t */\n\tpublic static function activate( $network_wide ) {", "\t\tif ( function_exists( 'is_multisite' ) && is_multisite() ) {", "\t\t\tif ( $network_wide ) {", "\t\t\t\t// Get all blog ids\n\t\t\t\t$blog_ids = self::get_blog_ids();", "\t\t\t\tforeach ( $blog_ids as $blog_id ) {", "\t\t\t\t\tswitch_to_blog( $blog_id );\n\t\t\t\t\tself::single_activate();\n\t\t\t\t}", "\t\t\t\trestore_current_blog();", "\t\t\t} else {\n\t\t\t\tself::single_activate();\n\t\t\t}", "\t\t} else {\n\t\t\tself::single_activate();\n\t\t}", "\t}", "\t/**\n\t * Fired when the plugin is deactivated.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @param boolean $network_wide True if WPMU superadmin uses\n\t * \"Network Deactivate\" action, false if\n\t * WPMU is disabled or plugin is\n\t * deactivated on an individual blog.\n\t */\n\tpublic static function deactivate( $network_wide ) {", "\t\tif ( function_exists( 'is_multisite' ) && is_multisite() ) {", "\t\t\tif ( $network_wide ) {", "\t\t\t\t// Get all blog ids\n\t\t\t\t$blog_ids = self::get_blog_ids();", "\t\t\t\tforeach ( $blog_ids as $blog_id ) {", "\t\t\t\t\tswitch_to_blog( $blog_id );\n\t\t\t\t\tself::single_deactivate();", "\t\t\t\t}", "\t\t\t\trestore_current_blog();", "\t\t\t} else {\n\t\t\t\tself::single_deactivate();\n\t\t\t}", "\t\t} else {\n\t\t\tself::single_deactivate();\n\t\t}", "\t}", "\t/**\n\t * Fired when a new site is activated with a WPMU environment.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @param int $blog_id ID of the new blog.\n\t */\n\tpublic function activate_new_site( $blog_id ) {", "\t\tif ( 1 !== did_action( 'wpmu_new_blog' ) ) {\n\t\t\treturn;\n\t\t}", "\t\tswitch_to_blog( $blog_id );\n\t\tself::single_activate();\n\t\trestore_current_blog();", "\t}", "\t/**\n\t * Get all blog ids of blogs in the current network that are:\n\t * - not archived\n\t * - not spam\n\t * - not deleted\n\t *\n\t * @since 1.0.0\n\t *\n\t * @return array|false The blog ids, false if no matches.\n\t */\n\tprivate static function get_blog_ids() {", "\t\tglobal $wpdb;", "\t\t// get an array of blog ids\n\t\t$sql = \"SELECT blog_id FROM $wpdb->blogs\n\t\t\tWHERE archived = '0' AND spam = '0'\n\t\t\tAND deleted = '0'\";", "\t\treturn $wpdb->get_col( $sql );", "\t}", "\t/**\n\t * Fired for each blog when the plugin is activated.\n\t *\n\t * @since 1.0.0\n\t */\n\tprivate static function single_activate() {", "\t\tupdate_option('woo-popup_options', array( 'popup_content' => 'This will be your pop up content', 'popup_page' => ' ', 'popup_class' => 'notice', 'popup_permanent' => '0', 'start_date' => date('Y-m-d', time()), 'end_date' => date('Y-m-d', time()), 'popup_timezone' => 'Europe/Paris' ));", "\t}", "\t/**\n\t * Fired for each blog when the plugin is deactivated.\n\t *\n\t * @since 1.0.0\n\t */\n\tprivate static function single_deactivate() {\n\t\tdelete_option('woo-popup_options');\n\t}", "\t/**\n\t * Load the plugin text domain for translation.\n\t *\n\t * @since 1.0.0\n\t */\n\tpublic function load_plugin_textdomain() {", "\t\t$domain = $this->plugin_slug;\n\t\t$locale = apply_filters( 'plugin_locale', get_locale(), $domain );", "\t\tload_textdomain( $domain, trailingslashit( WP_LANG_DIR ) . $domain . '/' . $domain . '-' . $locale . '.mo' );\n\t\tload_plugin_textdomain( $domain, FALSE, basename( plugin_dir_path( dirname( __FILE__ ) ) ) . '/languages/' );", "\t}", "\tpublic function trigger_plugin(){", "\t\tglobal $post;", "\t\t$options = get_option($this->options_slug);\n\t\t$tz = $options['popup_timezone'];\n\t\tdate_default_timezone_set($tz);\n\t\t$page = $options['popup_page'];\n\t\t$today = date('Y-m-d', time());\n\t\t$permanent = $options['popup_permanent'];\n\t\t$start_date = $options['start_date'];\n\t\t$end_date = $options['end_date'];", "", "\t\t$diff_start = strtotime($today) - strtotime($start_date);\n\t\t$diff_end = strtotime($end_date) - strtotime($today);\n\t\tif ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) && is_shop()){\n\t\t\t$page_id = get_option( 'woocommerce_shop_page_id' );\n\t\t}else{\n\t\t\t$page_id = $post->ID;\n\t\t}", "\t\tif(($permanent == 1 || $diff_start >= 0 && $diff_end >= 0) && ($page == 'all' || $page_id == $page)){\n\t\t\treturn true;\n\t\t}else{\n\t\t\treturn false;\n\t\t}\n\t}", "\tpublic function activated_woocommerce(){", "\t\t$suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';\n\t\tif ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {\n\t\t\tglobal $woocommerce;", "\t\t\t$pp_dir['base'] = $woocommerce->plugin_url() . '/assets/js/prettyPhoto/jquery.prettyPhoto' . $suffix . '.js';\n\t\t\t$pp_dir['init'] = $woocommerce->plugin_url() . '/assets/js/prettyPhoto/jquery.prettyPhoto.init' . $suffix . '.js';", "\t\t\t$pp_dir['style'] = $woocommerce->plugin_url() . '/assets/css/prettyPhoto.css';\n\t\t\t$pp_dir['ver'] = $woocommerce->version;\n\t\t}else{", "\t\t\t$pp_dir['base'] = plugins_url( '/assets/js/prettyPhoto/jquery.prettyPhoto' . $suffix . '.js', __FILE__ );\n\t\t\t$pp_dir['init'] = plugins_url( '/assets/js/prettyPhoto/jquery.prettyPhoto.init' . $suffix . '.js', __FILE__ );", "\t\t\t$pp_dir['style'] = plugins_url( '/assets/css/prettyPhoto.css', __FILE__ );\n\t\t\t$pp_dir['ver'] = '';\n\t\t}\n\t\treturn $pp_dir;\n\t}", "\t/**\n\t * Register and enqueue public-facing style sheet.\n\t *\n\t * @since 1.0.0\n\t */\n\tpublic function enqueue_styles() {\n\t\tif($this->trigger_plugin() == true){\n\t\t\t$pp_dir = $this->activated_woocommerce();", "\t\t\twp_enqueue_style( $this->plugin_slug . '-plugin-styles', plugins_url( 'assets/css/public.css', __FILE__ ), array(), self::VERSION );\n\t\t\twp_enqueue_style( 'woocommerce_prettyPhoto_css', $pp_dir['style'] );", "\t\t}\n\t}", "\t/**\n\t * Register and enqueues public-facing JavaScript files.\n\t *\n\t * @since 1.0.0\n\t */\n\tpublic function enqueue_scripts() {\n\t\tif($this->trigger_plugin() == true){", "\t\t\tglobal $woocommerce;", "\t\t\t$pp_dir = $this->activated_woocommerce();", "\t\t\twp_enqueue_script( 'prettyPhoto', $pp_dir['base'] , array( 'jquery' ), $pp_dir['ver'], true );\n\t\t\twp_enqueue_script( 'prettyPhoto-init', $pp_dir['init'], array( 'jquery' ), $pp_dir['ver'], true );", "\t\t\twp_enqueue_script( $this->plugin_slug . '-plugin-script', plugins_url( 'assets/js/public.js', __FILE__ ), array( 'prettyPhoto-init' ), self::VERSION );", "\t\t}\n\t}", "\tpublic function pass_php_vars() {\n\t\tinclude_once( 'views/public.php' );\n\t}", "}" ]
[ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [8, 242, 71, 2, 10, 379, 21, 19], "buggy_code_start_loc": [6, 196, 31, 1, 1, 31, 19, 18], "filenames": ["README.txt", "admin/class-woo-popup-admin.php", "admin/views/admin.php", "public/assets/css/prettyPhoto.css", "public/assets/js/public.js", "public/class-woo-popup.php", "public/views/public.php", "woo-popup.php"], "fixing_code_end_loc": [8, 251, 109, 171, 30, 384, 23, 19], "fixing_code_start_loc": [6, 197, 32, 1, 1, 31, 19, 18], "message": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:woo-popup_project:woo-popup:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "FDF073CD-7548-4114-B554-A83685981B77", "versionEndExcluding": "1.3.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327."}], "evaluatorComment": null, "id": "CVE-2015-10095", "lastModified": "2023-03-13T15:18:44.873", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-03-06T21:15:10.150", "references": [{"source": "cna@vuldb.com", "tags": ["Patch"], "url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, {"source": "cna@vuldb.com", "tags": ["Release Notes"], "url": "https://github.com/wp-plugins/woo-popup/releases/tag/1.3.0"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?ctiid.222327"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?id.222327"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, "type": "CWE-79"}
202
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * woo-popup\n *\n * @package WooPopup\n * @author Guillaume Kanoufi <guillaume@lostwebdesigns.com>\n * @license GPL-2.0+\n * @link http://lostwebdesigns.com\n * @copyright 2014 woocommerce, popup, woopopup\n */", "/**\n * Plugin class. This class should ideally be used to work with the\n * public-facing side of the WordPress site.\n *\n * If you're interested in introducing administrative or dashboard\n * functionality, then refer to `class-woo-popup-admin.php`\n *\n * @package WooPopup\n * @author Guillaume Kanoufi <guillaume@lostwebdesigns.com>\n */\nclass WooPopup {", "\t/**\n\t * Plugin version, used for cache-busting of style and script file references.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @var string\n\t */", "\tconst VERSION = '1.3.0';", "\n\t/**\n\t * Unique identifier for your plugin.\n\t *\n\t *\n\t * The variable name is used as the text domain when internationalizing strings\n\t * of text. Its value should match the Text Domain file header in the main\n\t * plugin file.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @var string\n\t */\n\tprotected $plugin_slug = 'woo-popup';", "\t/**\n\t * Unique identifier for your plugin options.\n\t *\n\t *\n\t *\n\t * @since 1.0.0\n\t *\n\t * @var string\n\t */\n\tprivate $options_slug = 'woo-popup_options';", "\n\t/**\n\t * Default Settings Values.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @var string\n\t */\n\tprivate $options_data = array(\n\t\t'popup_content' => 'This will be your pop up content',\n\t\t'popup_page' => ' ',\n\t\t'popup_class' => 'notice',\n\t\t'popup_permanent' => '0', //Default set to 0 so date are apparant\n\t\t'start_date' => '2014-02-02', //Set up an old date so if default the pop up won't be fired\n\t\t'end_date' => '2014-02-04', //Set up an old date so if default the pop up won't be fired\n\t\t'popup_timezone' => 'Europe/Paris'\n\t);", "\t/**\n\t * Instance of this class.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @var object\n\t */\n\tprotected static $instance = null;", "\t/**\n\t * Initialize the plugin by setting localization and loading public scripts\n\t * and styles.\n\t *\n\t * @since 1.0.0\n\t */\n\tprivate function __construct() {", "\t\t// Load plugin text domain\n\t\tadd_action( 'init', array( $this, 'load_plugin_textdomain' ) );", "\t\t// Activate plugin when new blog is added\n\t\tadd_action( 'wpmu_new_blog', array( $this, 'activate_new_site' ) );", "\t\t// Load public-facing style sheet and JavaScript.\n\t\tadd_action( 'wp_enqueue_scripts', array( $this, 'enqueue_styles' ) );\n\t\tadd_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );", "\t\t// Pass the php variable through wp_localize_script\n\t\tadd_action( 'wp_enqueue_scripts', array( $this, 'pass_php_vars' ) );", "\t}", "\t/**\n\t * Return the plugin slug.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @return Plugin slug variable.\n\t */\n\tpublic function get_plugin_slug() {\n\t\treturn $this->plugin_slug;\n\t}", "\t/**\n\t * Return the plugin options slug.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @return Plugin slug variable.\n\t */\n\tpublic function get_plugin_options_slug() {\n\t\treturn $this->options_slug;\n\t}", "\n\t/**\n\t * Return the plugin options default data.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @return Plugin options variable.\n\t */\n\tpublic function get_plugin_options_data() {\n\t\treturn $this->options_data;\n\t}", "\n\t/**\n\t * Return an instance of this class.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @return object A single instance of this class.\n\t */\n\tpublic static function get_instance() {", "\t\t// If the single instance hasn't been set, set it now.\n\t\tif ( null == self::$instance ) {\n\t\t\tself::$instance = new self;\n\t\t}", "\t\treturn self::$instance;\n\t}", "\t/**\n\t * Fired when the plugin is activated.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @param boolean $network_wide True if WPMU superadmin uses\n\t * \"Network Activate\" action, false if\n\t * WPMU is disabled or plugin is\n\t * activated on an individual blog.\n\t */\n\tpublic static function activate( $network_wide ) {", "\t\tif ( function_exists( 'is_multisite' ) && is_multisite() ) {", "\t\t\tif ( $network_wide ) {", "\t\t\t\t// Get all blog ids\n\t\t\t\t$blog_ids = self::get_blog_ids();", "\t\t\t\tforeach ( $blog_ids as $blog_id ) {", "\t\t\t\t\tswitch_to_blog( $blog_id );\n\t\t\t\t\tself::single_activate();\n\t\t\t\t}", "\t\t\t\trestore_current_blog();", "\t\t\t} else {\n\t\t\t\tself::single_activate();\n\t\t\t}", "\t\t} else {\n\t\t\tself::single_activate();\n\t\t}", "\t}", "\t/**\n\t * Fired when the plugin is deactivated.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @param boolean $network_wide True if WPMU superadmin uses\n\t * \"Network Deactivate\" action, false if\n\t * WPMU is disabled or plugin is\n\t * deactivated on an individual blog.\n\t */\n\tpublic static function deactivate( $network_wide ) {", "\t\tif ( function_exists( 'is_multisite' ) && is_multisite() ) {", "\t\t\tif ( $network_wide ) {", "\t\t\t\t// Get all blog ids\n\t\t\t\t$blog_ids = self::get_blog_ids();", "\t\t\t\tforeach ( $blog_ids as $blog_id ) {", "\t\t\t\t\tswitch_to_blog( $blog_id );\n\t\t\t\t\tself::single_deactivate();", "\t\t\t\t}", "\t\t\t\trestore_current_blog();", "\t\t\t} else {\n\t\t\t\tself::single_deactivate();\n\t\t\t}", "\t\t} else {\n\t\t\tself::single_deactivate();\n\t\t}", "\t}", "\t/**\n\t * Fired when a new site is activated with a WPMU environment.\n\t *\n\t * @since 1.0.0\n\t *\n\t * @param int $blog_id ID of the new blog.\n\t */\n\tpublic function activate_new_site( $blog_id ) {", "\t\tif ( 1 !== did_action( 'wpmu_new_blog' ) ) {\n\t\t\treturn;\n\t\t}", "\t\tswitch_to_blog( $blog_id );\n\t\tself::single_activate();\n\t\trestore_current_blog();", "\t}", "\t/**\n\t * Get all blog ids of blogs in the current network that are:\n\t * - not archived\n\t * - not spam\n\t * - not deleted\n\t *\n\t * @since 1.0.0\n\t *\n\t * @return array|false The blog ids, false if no matches.\n\t */\n\tprivate static function get_blog_ids() {", "\t\tglobal $wpdb;", "\t\t// get an array of blog ids\n\t\t$sql = \"SELECT blog_id FROM $wpdb->blogs\n\t\t\tWHERE archived = '0' AND spam = '0'\n\t\t\tAND deleted = '0'\";", "\t\treturn $wpdb->get_col( $sql );", "\t}", "\t/**\n\t * Fired for each blog when the plugin is activated.\n\t *\n\t * @since 1.0.0\n\t */\n\tprivate static function single_activate() {", "\t\tupdate_option('woo-popup_options', array( 'popup_content' => 'This will be your pop up content', 'popup_page' => ' ', 'popup_class' => 'notice', 'popup_theme' => 'pp_default', 'popup_permanent' => '0', 'start_date' => date('Y-m-d', time()), 'end_date' => date('Y-m-d', time()), 'popup_timezone' => 'Europe/Paris' ));", "\t}", "\t/**\n\t * Fired for each blog when the plugin is deactivated.\n\t *\n\t * @since 1.0.0\n\t */\n\tprivate static function single_deactivate() {\n\t\tdelete_option('woo-popup_options');\n\t}", "\t/**\n\t * Load the plugin text domain for translation.\n\t *\n\t * @since 1.0.0\n\t */\n\tpublic function load_plugin_textdomain() {", "\t\t$domain = $this->plugin_slug;\n\t\t$locale = apply_filters( 'plugin_locale', get_locale(), $domain );", "\t\tload_textdomain( $domain, trailingslashit( WP_LANG_DIR ) . $domain . '/' . $domain . '-' . $locale . '.mo' );\n\t\tload_plugin_textdomain( $domain, FALSE, basename( plugin_dir_path( dirname( __FILE__ ) ) ) . '/languages/' );", "\t}", "\tpublic function trigger_plugin(){", "\t\tglobal $post, $popup_theme;", "\t\t$options = get_option($this->options_slug);\n\t\t$tz = $options['popup_timezone'];\n\t\tdate_default_timezone_set($tz);\n\t\t$page = $options['popup_page'];\n\t\t$today = date('Y-m-d', time());\n\t\t$permanent = $options['popup_permanent'];\n\t\t$start_date = $options['start_date'];\n\t\t$end_date = $options['end_date'];", "\t\t$popup_theme = $options['popup_theme'];", "\t\t$diff_start = strtotime($today) - strtotime($start_date);\n\t\t$diff_end = strtotime($end_date) - strtotime($today);\n\t\tif ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) && is_shop()){\n\t\t\t$page_id = get_option( 'woocommerce_shop_page_id' );\n\t\t}else{\n\t\t\t$page_id = $post->ID;\n\t\t}", "\t\tif(($permanent == 1 || $diff_start >= 0 && $diff_end >= 0) && ($page == 'all' || $page_id == $page)){\n\t\t\treturn true;\n\t\t}else{\n\t\t\treturn false;\n\t\t}\n\t}", "\tpublic function activated_woocommerce(){", "\t\t$suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';\n\t\tif ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {\n\t\t\tglobal $woocommerce;", "\t\t\t$pp_dir['base'] = $woocommerce->plugin_url() . '/assets/js/jquery.prettyPhoto.js';", "\t\t\t$pp_dir['style'] = $woocommerce->plugin_url() . '/assets/css/prettyPhoto.css';\n\t\t\t$pp_dir['ver'] = $woocommerce->version;\n\t\t}else{", "\t\t\t$pp_dir['base'] = plugins_url( '/assets/js/jquery.prettyPhoto.js', __FILE__ );", "\t\t\t$pp_dir['style'] = plugins_url( '/assets/css/prettyPhoto.css', __FILE__ );\n\t\t\t$pp_dir['ver'] = '';\n\t\t}\n\t\treturn $pp_dir;\n\t}", "\t/**\n\t * Register and enqueue public-facing style sheet.\n\t *\n\t * @since 1.0.0\n\t */\n\tpublic function enqueue_styles() {\n\t\tif($this->trigger_plugin() == true){\n\t\t\t$pp_dir = $this->activated_woocommerce();", "\t\t\twp_enqueue_style( 'prettyPhoto_css', $pp_dir['style']);\n\t\t\twp_enqueue_style( $this->plugin_slug . '-plugin-styles', plugins_url( 'assets/css/public.css', __FILE__ ), array('prettyPhoto_css'), self::VERSION );", "\t\t}\n\t}", "\t/**\n\t * Register and enqueues public-facing JavaScript files.\n\t *\n\t * @since 1.0.0\n\t */\n\tpublic function enqueue_scripts() {\n\t\tif($this->trigger_plugin() == true){", "\t\t\tglobal $woocommerce, $popup_theme;", "\t\t\t$pp_dir = $this->activated_woocommerce();", "\t\t\twp_enqueue_script( 'prettyPhoto', $pp_dir['base'] , array( 'jquery' ), $pp_dir['ver'] );", "\t\t\twp_enqueue_script( $this->plugin_slug . '-plugin-script', plugins_url( 'assets/js/public.js', __FILE__ ), array( 'prettyPhoto' ), self::VERSION, true );", "\n\t\t\t// Passing Plugin Options to js\n\t\t\t$plugin_data = array(\n\t\t\t 'theme' => $popup_theme,\n\t\t\t);\n\t\t\twp_localize_script( $this->plugin_slug . '-plugin-script', 'plugin_options_vars', $plugin_data );", "\t\t}\n\t}", "\tpublic function pass_php_vars() {\n\t\tinclude_once( 'views/public.php' );\n\t}", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [8, 242, 71, 2, 10, 379, 21, 19], "buggy_code_start_loc": [6, 196, 31, 1, 1, 31, 19, 18], "filenames": ["README.txt", "admin/class-woo-popup-admin.php", "admin/views/admin.php", "public/assets/css/prettyPhoto.css", "public/assets/js/public.js", "public/class-woo-popup.php", "public/views/public.php", "woo-popup.php"], "fixing_code_end_loc": [8, 251, 109, 171, 30, 384, 23, 19], "fixing_code_start_loc": [6, 197, 32, 1, 1, 31, 19, 18], "message": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:woo-popup_project:woo-popup:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "FDF073CD-7548-4114-B554-A83685981B77", "versionEndExcluding": "1.3.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327."}], "evaluatorComment": null, "id": "CVE-2015-10095", "lastModified": "2023-03-13T15:18:44.873", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-03-06T21:15:10.150", "references": [{"source": "cna@vuldb.com", "tags": ["Patch"], "url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, {"source": "cna@vuldb.com", "tags": ["Release Notes"], "url": "https://github.com/wp-plugins/woo-popup/releases/tag/1.3.0"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?ctiid.222327"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?id.222327"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, "type": "CWE-79"}
202
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * Represents the view for the public-facing component of the plugin.\n *\n * This typically includes any information, if any, that is rendered to the\n * frontend of the theme when the plugin is activated.\n *\n * @package WooPopup\n * @author Guillaume Kanoufi <guillaume@lostwebdesigns.com>\n * @license GPL-2.0+\n * @link http://example.com\n * @copyright 2014 woocommerce, popup, woopopup\n */\n?>", "<!-- This file is used to markup the public facing aspect of the plugin. -->\n<?php\n\t$woo_popup_vars = get_option($this->options_slug);", "\t$popup_content = do_shortcode($woo_popup_vars['popup_content']);\n\t$formatted_popup = wpautop(stripslashes($popup_content));", "\tif ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ){\n\t\t$class = 'woocommerce-'.$woo_popup_vars['popup_class'];\n\t}else{\n\t\t$class = 'woopopup-'.$woo_popup_vars['popup_class'];\n\t}\n\t$woo_popup_vars['popup_content'] = '<div id=\"woopopup\" style=\"display:none;\" aria-hidden=\"true\"><div class=\"'.$class.'\">'.$formatted_popup.'</div></div>';\n\twp_localize_script( $this->plugin_slug . '-plugin-script', 'woo_popup', $woo_popup_vars );" ]
[ 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [8, 242, 71, 2, 10, 379, 21, 19], "buggy_code_start_loc": [6, 196, 31, 1, 1, 31, 19, 18], "filenames": ["README.txt", "admin/class-woo-popup-admin.php", "admin/views/admin.php", "public/assets/css/prettyPhoto.css", "public/assets/js/public.js", "public/class-woo-popup.php", "public/views/public.php", "woo-popup.php"], "fixing_code_end_loc": [8, 251, 109, 171, 30, 384, 23, 19], "fixing_code_start_loc": [6, 197, 32, 1, 1, 31, 19, 18], "message": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:woo-popup_project:woo-popup:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "FDF073CD-7548-4114-B554-A83685981B77", "versionEndExcluding": "1.3.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327."}], "evaluatorComment": null, "id": "CVE-2015-10095", "lastModified": "2023-03-13T15:18:44.873", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-03-06T21:15:10.150", "references": [{"source": "cna@vuldb.com", "tags": ["Patch"], "url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, {"source": "cna@vuldb.com", "tags": ["Release Notes"], "url": "https://github.com/wp-plugins/woo-popup/releases/tag/1.3.0"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?ctiid.222327"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?id.222327"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, "type": "CWE-79"}
202
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * Represents the view for the public-facing component of the plugin.\n *\n * This typically includes any information, if any, that is rendered to the\n * frontend of the theme when the plugin is activated.\n *\n * @package WooPopup\n * @author Guillaume Kanoufi <guillaume@lostwebdesigns.com>\n * @license GPL-2.0+\n * @link http://example.com\n * @copyright 2014 woocommerce, popup, woopopup\n */\n?>", "<!-- This file is used to markup the public facing aspect of the plugin. -->\n<?php\n\t$woo_popup_vars = get_option($this->options_slug);", "\t// $popup_content = do_shortcode($woo_popup_vars['popupcontent']);", "\t// $formatted_popup = wpautop(stripslashes($popup_content));\n\t$formatted_popup = apply_filters( 'the_content', $woo_popup_vars['popup_content'] );", "\tif ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ){\n\t\t$class = 'woocommerce-'.$woo_popup_vars['popup_class'];\n\t}else{\n\t\t$class = 'woopopup-'.$woo_popup_vars['popup_class'];\n\t}\n\t$woo_popup_vars['popup_content'] = '<div id=\"woopopup\" style=\"display:none;\" aria-hidden=\"true\"><div class=\"'.$class.'\">'.$formatted_popup.'</div></div>';\n\twp_localize_script( $this->plugin_slug . '-plugin-script', 'woo_popup', $woo_popup_vars );" ]
[ 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [8, 242, 71, 2, 10, 379, 21, 19], "buggy_code_start_loc": [6, 196, 31, 1, 1, 31, 19, 18], "filenames": ["README.txt", "admin/class-woo-popup-admin.php", "admin/views/admin.php", "public/assets/css/prettyPhoto.css", "public/assets/js/public.js", "public/class-woo-popup.php", "public/views/public.php", "woo-popup.php"], "fixing_code_end_loc": [8, 251, 109, 171, 30, 384, 23, 19], "fixing_code_start_loc": [6, 197, 32, 1, 1, 31, 19, 18], "message": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:woo-popup_project:woo-popup:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "FDF073CD-7548-4114-B554-A83685981B77", "versionEndExcluding": "1.3.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327."}], "evaluatorComment": null, "id": "CVE-2015-10095", "lastModified": "2023-03-13T15:18:44.873", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-03-06T21:15:10.150", "references": [{"source": "cna@vuldb.com", "tags": ["Patch"], "url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, {"source": "cna@vuldb.com", "tags": ["Release Notes"], "url": "https://github.com/wp-plugins/woo-popup/releases/tag/1.3.0"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?ctiid.222327"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?id.222327"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, "type": "CWE-79"}
202
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * The WordPress Plugin Boilerplate.\n *\n * A foundation off of which to build well-documented WordPress plugins that\n * also follow WordPress Coding Standards and PHP best practices.\n *\n * @package WooPopup\n * @author Guillaume Kanoufi <guillaume@lostwebdesigns.com>\n * @license GPL-2.0+\n * @link http://lostwebdesigns.com\n * @copyright 2014 woocommerce, popup, woopopup\n *\n * @wordpress-plugin\n * Plugin Name: woo-popup\n * Plugin URI: http://wordpress.org/plugins/woo-popup/\n * Description: Display a pop up window on the page of your choice.", " * Version: 1.2.2", " * Author: Guillaume Kanoufi\n * Author URI: https://github.com/g-kanoufi\n * Text Domain: woo-popup-locale\n * License: GPL-2.0+\n * License URI: http://www.gnu.org/licenses/gpl-2.0.txt\n * Domain Path: /languages\n * GitHub Plugin URI: https://github.com/<owner>/<repo>\n * WordPress-Plugin-Boilerplate: v2.6.1\n */", "// If this file is called directly, abort.\nif ( ! defined( 'WPINC' ) ) {\n\tdie;\n}", "/*----------------------------------------------------------------------------*\n * Public-Facing Functionality\n *----------------------------------------------------------------------------*/", "require_once( plugin_dir_path( __FILE__ ) . 'public/class-woo-popup.php' );", "/*\n * Register hooks that are fired when the plugin is activated or deactivated.\n * When the plugin is deleted, the uninstall.php file is loaded.\n */\nregister_activation_hook( __FILE__, array( 'WooPopup', 'activate' ) );\nregister_deactivation_hook( __FILE__, array( 'WooPopup', 'deactivate' ) );", "\nadd_action( 'plugins_loaded', array( 'WooPopup', 'get_instance' ) );", "/*----------------------------------------------------------------------------*\n * Dashboard and Administrative Functionality\n *----------------------------------------------------------------------------*/", "if ( is_admin() && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) {", "\trequire_once( plugin_dir_path( __FILE__ ) . 'admin/class-woo-popup-admin.php' );\n\tadd_action( 'plugins_loaded', array( 'WooPopupAdmin', 'get_instance' ) );", "}" ]
[ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [8, 242, 71, 2, 10, 379, 21, 19], "buggy_code_start_loc": [6, 196, 31, 1, 1, 31, 19, 18], "filenames": ["README.txt", "admin/class-woo-popup-admin.php", "admin/views/admin.php", "public/assets/css/prettyPhoto.css", "public/assets/js/public.js", "public/class-woo-popup.php", "public/views/public.php", "woo-popup.php"], "fixing_code_end_loc": [8, 251, 109, 171, 30, 384, 23, 19], "fixing_code_start_loc": [6, 197, 32, 1, 1, 31, 19, 18], "message": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:woo-popup_project:woo-popup:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "FDF073CD-7548-4114-B554-A83685981B77", "versionEndExcluding": "1.3.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327."}], "evaluatorComment": null, "id": "CVE-2015-10095", "lastModified": "2023-03-13T15:18:44.873", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-03-06T21:15:10.150", "references": [{"source": "cna@vuldb.com", "tags": ["Patch"], "url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, {"source": "cna@vuldb.com", "tags": ["Release Notes"], "url": "https://github.com/wp-plugins/woo-popup/releases/tag/1.3.0"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?ctiid.222327"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?id.222327"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, "type": "CWE-79"}
202
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * The WordPress Plugin Boilerplate.\n *\n * A foundation off of which to build well-documented WordPress plugins that\n * also follow WordPress Coding Standards and PHP best practices.\n *\n * @package WooPopup\n * @author Guillaume Kanoufi <guillaume@lostwebdesigns.com>\n * @license GPL-2.0+\n * @link http://lostwebdesigns.com\n * @copyright 2014 woocommerce, popup, woopopup\n *\n * @wordpress-plugin\n * Plugin Name: woo-popup\n * Plugin URI: http://wordpress.org/plugins/woo-popup/\n * Description: Display a pop up window on the page of your choice.", " * Version: 1.3.0", " * Author: Guillaume Kanoufi\n * Author URI: https://github.com/g-kanoufi\n * Text Domain: woo-popup-locale\n * License: GPL-2.0+\n * License URI: http://www.gnu.org/licenses/gpl-2.0.txt\n * Domain Path: /languages\n * GitHub Plugin URI: https://github.com/<owner>/<repo>\n * WordPress-Plugin-Boilerplate: v2.6.1\n */", "// If this file is called directly, abort.\nif ( ! defined( 'WPINC' ) ) {\n\tdie;\n}", "/*----------------------------------------------------------------------------*\n * Public-Facing Functionality\n *----------------------------------------------------------------------------*/", "require_once( plugin_dir_path( __FILE__ ) . 'public/class-woo-popup.php' );", "/*\n * Register hooks that are fired when the plugin is activated or deactivated.\n * When the plugin is deleted, the uninstall.php file is loaded.\n */\nregister_activation_hook( __FILE__, array( 'WooPopup', 'activate' ) );\nregister_deactivation_hook( __FILE__, array( 'WooPopup', 'deactivate' ) );", "\nadd_action( 'plugins_loaded', array( 'WooPopup', 'get_instance' ) );", "/*----------------------------------------------------------------------------*\n * Dashboard and Administrative Functionality\n *----------------------------------------------------------------------------*/", "if ( is_admin() && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) {", "\trequire_once( plugin_dir_path( __FILE__ ) . 'admin/class-woo-popup-admin.php' );\n\tadd_action( 'plugins_loaded', array( 'WooPopupAdmin', 'get_instance' ) );", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [8, 242, 71, 2, 10, 379, 21, 19], "buggy_code_start_loc": [6, 196, 31, 1, 1, 31, 19, 18], "filenames": ["README.txt", "admin/class-woo-popup-admin.php", "admin/views/admin.php", "public/assets/css/prettyPhoto.css", "public/assets/js/public.js", "public/class-woo-popup.php", "public/views/public.php", "woo-popup.php"], "fixing_code_end_loc": [8, 251, 109, 171, 30, 384, 23, 19], "fixing_code_start_loc": [6, 197, 32, 1, 1, 31, 19, 18], "message": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:woo-popup_project:woo-popup:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "FDF073CD-7548-4114-B554-A83685981B77", "versionEndExcluding": "1.3.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as problematic has been found in woo-popup Plugin up to 1.2.2. This affects an unknown part of the file admin/class-woo-popup-admin.php. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. Upgrading to version 1.3.0 is able to address this issue. The name of the patch is 7c76ac78f3e16015991b612ff4fa616af4ce9292. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-222327."}], "evaluatorComment": null, "id": "CVE-2015-10095", "lastModified": "2023-03-13T15:18:44.873", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-03-06T21:15:10.150", "references": [{"source": "cna@vuldb.com", "tags": ["Patch"], "url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, {"source": "cna@vuldb.com", "tags": ["Release Notes"], "url": "https://github.com/wp-plugins/woo-popup/releases/tag/1.3.0"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?ctiid.222327"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "https://vuldb.com/?id.222327"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/wp-plugins/woo-popup/commit/7c76ac78f3e16015991b612ff4fa616af4ce9292"}, "type": "CWE-79"}
202
Determine whether the {function_name} code is vulnerable or not.
[ ".. This file should contain the changes for the last release only, which\n will be included on the package's page on pypi. All older entries are\n kept in HISTORY.txt", "Changelog\n=========", "5.0rc2 (unreleased)\n-------------------", "", "\n- Do not bother additional CRSF protection for addMember since all public\n users get same CSRF token and the method should be unpublished.\n See https://pypi.python.org/pypi/Products.PloneHotfix20150910\n [vangheem]", "- Remove site properties that have been migrated to the registry.\n [esteele]", "- fix #862: Profile listing on site creation has alignment issues\n [ichim-david]", "\n5.0rc1 (2015-09-08)\n-------------------", "- Remove deprecated global_defines.pt\n [esteele]", "- Remove no-longer-used properties from portal_properties\n [esteele]", "- Move footer and colophon out of skins\n [vangheem]", "- pre-cook resources so we do not write on read for resources generation\n [vangheem]", "- Turn robots.txt into a browser-view, fix link to sitemap.xml.gz, allow\n editing in site-controlpanel.\n Fixes https://github.com/plone/Products.CMFPlone/issues/604\n [pbauer]", "- Remove history_form, history_comparison templates.\n Remove now-empty plone_forms skins folder.\n [esteele]", "- Remove no-longer-used images from portal_images.\n [esteele]", "- Typo in delete modal configuration caused submission redirection errors\n [vangheem]", "- Upgrade known core packages at the end of the Plone migration.\n [maurits]", "- remove Products.CMFPlone.utils.isLinked function. Switch to using\n plone.app.linkintegrity's variant\n [vangheem]", "- Fix error to allow site navigation if TinyMCE content_css setting is None\n [Gagaro]", "5.0b4 (2015-08-23)\n------------------", "- fix #350: \"plone.app.content circular dependency on Products.CMFPlone\" - this\n fixes the imports only, not on zcml/genericsetup level.\n [jensens]", "- move Plone specific ``getDefaultPage`` (magic) code from plone.app.layout\n over to Products.CMFPlone. This avoids a circular dependency. Also its\n not really layout only related code.\n [jensens]", "- Fix add-ons to be installed using CMFQuickInstaller (restore support\n for Extensions/Install.py)\n [datakurre]", "- Rename showEditableBorder to showToolbar and deprecate using\n disable_border and enable_border for enable_toolbar and disable_toolbar\n [vangheem]", "- Not using less variables in toolbar everywhere\n [vangheem]", "- Fix link to documentation", "- Rework timezone selection in @@plone-addsite.\n [jaroel]", "- Rework language selection in @@plone-addsite.\n [jaroel]", "- Turn @@tinymce-controlpanel ``content_css`` field into a list, so we can add\n several CSS URLs (useful when add-ons need to provide extra TinyMCE styles),\n and fix TinyMCE config getter so it considers the ``content_css`` value.\n [ebrehault]", "\n5.0b3 (2015-07-20)\n------------------", "- show toolbar buttons on sitemap, accessibility and search pages\n [vangheem]", "- log info after catalog rebuilt\n [vangheem]", "- Renamed 'Zope Management Interface' to 'Management Interface'.\n [jaroel]", "- Fix adding a new Plone site with country specific language. Refs #411.\n [jaroel]", "- fix plone-logged-in bundle not using global jquery for requirejs dependency and in\n weird cases causing select2 load errors in patterns(especially resource registry)\n [vangheem]", "- Use new plone.app.theming policy API and delegate theme cache to plone.app.theming\n [gyst]", "- Fix issue where site root syndication was giving 404s\n [vangheem]", "- update time widget interval selection to be the same as Plone 4 time selection intervals\n [vangheem]", "- use ajax_load in @@search when loading results dynamically, and add missing\n closing tag\n [ebrehault]", "- better formatting of config.js\n [vangheem]", "- Upload pattern uses the baseUrl to compute the upload URL, so this should\n always be the site root and not the current context\n [frapell]", "- rewrite css files when saving customized files in the resource registry\n [vangheem]", "- Update links to point to '@@overview-controlpanel'.\n Fixes https://github.com/plone/Products.CMFPlone/issues/573\n [gforcada]", "- Fix email validation of long domain names.\n [gotcha]", "- fix syndication feed use of lead image as it was using wrong url\n [vangheem]", "- add utility to get site logo\n [vangheem]", "- fix issue where product upgrade did show an error status message\n [datakurre]", "- fix casing on \"First weekday\" field on Date and Time control panel\n [vangheem]", "- fix imaging control panel example format on description\n [vangheem]", "- Add page title to resource registry\n [vangheem]", "- Remove ramcache-controlpanel csrf test. Ramcache control panel has been\n moved to p.a.caching since ages. We will get rid of it.\n [timo]", "- Add undeclared zope.cachedescriptors dependency.\n [timo]", "- Do not require \"Enable LiveSearch\". This fixes https://github.com/plone/Products.CMFPlone/issues/558\n [timo]", "- Fix control panel titles. This fixes https://github.com/plone/Products.CMFPlone/issues/550 https://github.com/plone/Products.CMFPlone/issues/553 https://github.com/plone/Products.CMFPlone/issues/557\n [timo]", "- remove plone.app.jquerytools dependency\n [vangheem]", "- fix bug where bundles would not get built properly with\n compile-plone-resources script when multiple resources\n were defined for a bundle\n [vangheem]", "- do not require css to be defined for non-compilable bundles\n [vangheem]", "- fix weird issue with selecting multiple links and images on a page\n while you are editing with tinymce\n [vangheem]", "- updates to contact forms to make them more user friendly on submission\n [vangheem]", "- include code plugin by default for TinyMCE\n [vangheem]", "- Fix build reading browser cached files by appending random query\n param onto url. See https://github.com/plone/Products.CMFPlone/commit/2d3865805efc6b72dce236eb68e502d8c57717b6\n and https://github.com/plone/Products.CMFPlone/commit/bd1f9ba99d1ad40bb7fe1c00eaa32b8884aae5e2\n [vangheem]", "- fix manage content type and group portlets link to have authenticator\n [vangheem]", "- Convert manage-portlets.js into a pattern and make improvements on\n using the manage portlets infrastructure\n [vangheem]", "- Remove dependency on plone.app.form and other formlib packages\n [tomgross]", "- Remove plone.skip_links from the default set of viewlets in order to follow\n modern a11y methods and drop support for outdated ways [sneridagh]", "- Change the name and link of 'Types' control panel to 'Content Settings' and\n '@@content-controlpanel' since there was confusion with the 'Dexterity\n Content Types' one [sneridagh]", "\n5.0b2 (2015-05-13)\n------------------", "- Add social media settings control panel", "- add ability to provide a css file for tinymce style formats\n [vangheem]", "- fix plone-generate-gruntfile to compile each less resource\n separately\n [vangheem]", "- provide image alignment styles for tinymce images\n [vangheem]", "- Respect TinyMCE control panel settings\n [vangheem]", "- enable/disable versioning behavior with settings in Types control panel\n [vangheem]", "- Make typesToList read metaTypesNotToList from new p.a.registry settings.\n This fixes https://github.com/plone/Products.CMFPlone/issues/454.\n [timo]", "- style tweaks to toolbar\n [pbauer]", "- fix search form usability\n [vangheem]", "- detect when changes are made to the legacy bundle through the interface\n so resources are re-built when they need to be\n [vangheem]", "- fix some legacy import wonkiness. Inserting multiple times, insert-before\n and remove fixed\n [vangheem]", "- make live search and search form give consistent results\n [vangheem]", "- only show edit bar if user logged in\n [vangheem]", "- fix error sending test email in Mail control panel\n [tkimnguyen]", "- pat-modal pattern has been renamed to pat-plone-modal\n [jcbrand]", "- Remove Products.CMFFormController dependency.\n [timo]", "- Fix submission of tinymce control panel.\n [davisagli]", "- Monkey patch SMTPMailer init method to pick up the mail settings from the\n registry instead of from the MailHost itself.\n [timo]", "- Add `resource_blacklist` attribute to resource registry importer, to\n allow filtering of known bad legacy resource imports. Filter js from\n plone.app.jquery.\n [alecm]", "- Fix broken \"Installing a third party add-on\" link\n [cedricmessiant]", "- Fix folder contents button disappeared act\n [vangheem]", "- Fix resource registry javascript build\n [vangheem]", "- Move `plone.htmlhead.links` viewlet manager after `plone.scripts`,\n because the former is sometimes used to include scripts that depend on\n the latter.\n [davisagli]", "- Change the order of the plonebar user menu and move the plone.personal_bar\n viewlet to the last position due to accessibility issues on having it being\n the first element.\n [sneridagh]", "- We only support `utf-8` site-encoding at the moment\n [tomgross]", "\n5.0b1.post1 (2015-03-27)\n------------------------", "- Packaging fix, no code changes.\n [esteele]", "\n5.0b1 (2015-03-26)\n------------------", "- Add tests for configuring encoding of user registration or\n forgotten password emails.\n [davidjb]", "- Pass email encoding to forgotten password email template.\n [davidjb]", "- Pass mail ``Content-Type`` to mailhost when sending forgotten password\n emails.\n [davidjb]", "- Move security control panel to CMFPlone. Fixes #216.\n [jcerjak, timo]", "- Remove ``create_userfolder`` from addPloneSite factory, it is not used\n anymore.\n [jcerjak]", "- Read security settings from the registry instead of portal properties.\n [jcerjak,timo]", "- Fix tests for plone.app.contenttypes unified view names, which uses\n ``listing_view`` for Folder and Collection types.\n [thet]", "- Remove ``selectable_views`` from ``properties.xml``, which isn't used\n anywhere anymore.\n [thet]", "- Remove the remaining ``Topic`` entry in ``default_page_types`` from\n ``propertiestool.xml``. This setting is now done in\n ``plone.app.contenttypes`` respectively ``Products.ATContentTypes``.\n [thet]", "- Add __version__ attribute to __init__.py. This allows us to retrieve the\n current Plone version with 'Products.CMFPlone.__version__'. Even though this\n is no offical standard, many packages in the Python standard library provide\n this.\n [timo]", "- Replaced the legacy mark_special_links javascript with a\n corresponding mockup pattern.\n [fulv]", "- remove plone_javascript_variables.js as necessary values\n are provided on body tag and pattern options\n [vangheem]", "- fix bootstrap css bleeding into global namespaces\n [vangheem]", "- add recurrence pattern\n [vangheem]", "- add history support for folder contents\n [vangheem]", "- Merge plone.app.search here\n [vangheem]", "- Extended ulocalized_time for target_language\n [agitator]", "- Caching for ``@@site-logo``.\n [thet]", "- Support for portal site logos stored in the portal registry by uploading via\n the site control panel. Add a ``@@site-logo`` view for downloading the logo.\n [thet]", "- Fix the resource registry to save the automatically generated filepath to the\n compiled resource on the bundle object after compilation. The filepath is\n always in the '++plone++static/' namespace. This fix makes custom bundles\n actually includable.\n [thet]", "- Get icon from layout_view instead of plone_view.\n [pbauer]", "- Fix contentViews (tabs) markup for Plone 5.\n [davisagli]", "- Rename syndication-settings to syndication-controlpanel. Keep the old view registration for backwards compatibility.\n [timo]", "- Added a link for the advanced 'Create a Plone site' screen to the Plone overview.\n [jaroel]", "- Fixed the label for 'Example content' in the advanced 'Create a Plone site' screen.\n [jaroel]", "- Move markup control panel to CMFPlone. Fixes #220.\n [djay, thet]", "- Use jstz to set default portal_timezone in @@plone-addsite.\n [instification]", "- Make inline validation of AT multiple selection widget work.\n [gbastien]", "- Make sure compiling resources does not commit transaction prematurely.\n [davisagli]", "- Adding the option to configure a bundle from the diazo manifest file.\n [bloodbare]", "- Move the controlpanel overview from plone.app.controlpanel into this package\n https://github.com/plone/Products.CMFPlone/issues/290\n [khink]", "- PLIP 10359: Migrate usergroups controlpanel to ``z3c.form`` and move it from\n plone.app.controlpanel to Products.CMFPlone. Fix and extend tests and add\n robot tests.\n [ferewuz]", "\n5.0a3 (2014-11-01)\n------------------", "- folder_position script: make position and id optional. Default\n position to 'ordered' and id to None, which means: do nothing.\n plone.folder 1.0.5 allows this, making it possible to simply reverse\n the current sort order by using reverse=False.\n [maurits]", "- Fix JS resource viewlet HTML syntax error.\n [rpatterson]", "- Fix resource bundle expressions. They weren't being checked at all and\n reversed the condition if they had been. Also move caching of the cooked\n expressions out of the DB and into a RAM cache.\n [rpatterson]", "- Fix endless resource dependency loop when dependeing on a bundle that also has\n a dependency.\n [rpatterson]", "- reduce deprecation warnings to use plone_layout and not plone_view for\n certain method calls in order to make debugging of robottests easier:\n w/o it shows 1000ds of extra lines in html report.\n [jensens]", "- type controlpanel: Resolved problem with workflow selection form as it\n was breaking if state title had non-ascii characters. see also\n https://github.com/plone/plone.app.controlpanel/pull/26\n [lewicki, jensens]", "- Minor overhaul of CatalogTool.py - no feature changes!\n Optimizations and better readable code for indexer\n ``allowedRolesAndUsers``: now using a set.\n Change if/elif/else to oneliner boolean expression in ``is_folderish``\n indexer.\n Usage of AccessControl 3 style decorators for security declarations.\n Minor reformattings to make code-analysis happy.\n [jensens]", "- Removed some javascripts: fullscreenmode.js, dragdropreorder.js,\n styleswitcher.js, select_all.js, collapsibleformfields.js", "- PLIP 13260: Migration cut, copy and paste into browser views.\n [saily]", "- Abstract the search form and livesearch action URLs making it easier to\n extend the search portlet with custom views or other actions.\n [rpatterson]", "- Fix JavaScript to work with recent jQuery (>= 1.9) versions.\n [thet]", "- Small scoping fix in locking js code\n [do3cc]", "- PLIP 13260: Migrate author page to browser views/z3c.form (issue #78)\n [bosim]", "- Integration of the new markup update and CSS for both Plone and Barceloneta\n theme. This is the work done in the GSOC Barceloneta theme project.\n [albertcasado, sneridagh]", "- Created new viewlet manager for holding main navigation for a more semantic\n use of it. Move the global sections viewlet into it.\n [albertcasado]", "- New toolbar markup based in ul li tags.\n [albertcasado, bloodbare, sneridagh]", "- Update <div id=\"content\"> in all templates with <article id=\"content\">\n [albertcasado]", "- PLIP 14261: New resource registries.\n [bloodbare, vangheem, robgietema, et al]", "\n5.0a2 (2014-04-20)\n------------------", "- Advertise the migration of content to dexterity after a successful\n upgrade to Plone 5.\n [pbauer]", "- Strip leading & trailing spaces from id and title in rename-form.\n See https://dev.plone.org/ticket/12998, https://dev.plone.org/ticket/12989,\n https://dev.plone.org/ticket/9370, https://dev.plone.org/ticket/8338\n [pbauer]", "- Fix incorrect use of dict get method in CatalogTool.search, introduced\n by PloneHotfix20131210 (issue 195)\n [fulv]", "- Added timezone selection to add site page\n [pysailor, yenzenz]", "- Added date date and time controlpanel (moved over from plone.app.event).\n [yenzenz. thet]", "- Remove DL/DT/DD's from portal messages, portlet templates and others.\n https://github.com/plone/Products.CMFPlone/issues/153\n https://github.com/plone/Products.CMFPlone/issues/163\n [khink]", "- PLIP 13260 remove templates and form scripts for\n ``select_default_page`` and ``select_default_view`` because they got\n migrated to browser views. Fix tests for that and remove legacy tests.\n See: https://github.com/plone/Products.CMFPlone/issues/90\n [saily]", "- PLIP 13260: Migration contact-info to ``z3c.form`` and make it highly\n customizeable.\n [timitos, saily]", "\n5.0a1 (2014-03-02)\n------------------", "- remove quickinstall control panel form since a new one was moved to\n plone.app.controlpanel\n [vangheem]", "- Add 'warning' and 'error' status message types to the test_rendering\n view.\n [esteele]", "- Update the front-page links.\n [esteele]", "- In plone-overview view, we can now see Plone sites which are contained into\n Zope folder.\n [bsuttor]", "- Make Plone tool read the exposeDCMetaTags from p.a.registry instead of\n of the site properties.\n [timo]", "- Hide plone.app.registry install profile in the add-ons control panel.\n [esteele]", "- Removed spamProtect.py script, since it doesn't offer real protection.\n [davisagli]", "- Moved the member search form to plone.app.users\n [pabo3000]", "- PLIP #13705: Remove <base> tag.\n [frapell]", "- merge hotfixes from 20131210\n [vangheem]", "- handle plone.app.textfield RichTextValue objects in syndication. Should\n fix syndication with plone.app.contenttypes.\n [vangheem]", "- FolderFeed adapter now takes into account the limit property when displaying\n the RSS feed just like the other adapters do\n [ichim-david]", "- Remove the portal_calendar tool and the dependency on CMFCalendar.\n [davisagli]", "- Remove the plone_deprecated skin layer.\n [gforcada, davisagli]", "- Moved portal_factory and portal_metadata from Products.CMFPlone to\n Products.ATContentTypes (PLIP #13770)\n [ale-rt]", "- Remove the portal_interface tool.\n [ale-rt]", "- Remove the portal_actionicons tool.\n [davisagli]", "- Remove ownership_form and change_ownership script, which were not used.\n [davisagli]", "- Convert author_feedback_template and accessibility_info to browser views.\n [bloodbare]", "- Move calendar_macros and jscalendar to Products.Archetypes.\n [bloodbare]", "- Remove plonetheme.classic from the package dependencies and the default\n extension profile, since it will not ship with Plone 5.\n [timo]", "- Move docs/CHANGES.txt to CHANGES.rst.\n [timo]", "- Replace deprecated test assert statements.\n [timo]", "- Add a dependency on plone.app.theming. Install by default.\n [esteele]", "- Drop dependency on plonetheme.classic.\n [esteele]", "- Remove old logo.jpg. Use logo.png from Sunburst.\n [esteele]", "- Inline validation JavaScript for z3c.form only sends request when\n field name can be obtained from DOM for a widget (#13741).\n [seanupton]", "- Add use_uuid_as_userid site property.\n Part of PLIP 13419.\n [maurits]", "- Let set_own_login_name use the update(Own)LoginName method from PAS.\n Part of PLIP 13419.\n [maurits]", "- recently_modified and recently_published respects allow anonymous to view\n about setting\n [vangheem]", "- Return a 404 instead of \"AttributeError: (dynamic view)\" if a user attempts to\n view a still-temporary PortalFactory item.\n [esteele]", "- Ensure that initial_login is set to True when a user first logs in.\n [taito]", "- Merged PLIP #12198: Depend on Chameleon (five.pt) as a faster page template\n engine.\n [davisagli]", "- make extensionprofiles selection part of 'advanced' in plone-addsite\n [jaroel]", "- enable syndication on plone.app.contenttypes collection\n [vangheem]", "- fix syndication settings to not write on read\n [vangheem]", "- fix wrong download url for podcast syndication\n [Rudd-O]", "- Merged PLIP #12344: Use Dexterity-based core content types.", " * Avoid including ATContentTypes and Archetypes as a dependency.\n * Install the plone.app.contenttypes profile for new sites.", " [davisagli et al]", "- Merged PLIP #13270: Move presentation mode out of core.\n If the feature is still desired, use the plone.app.s5slideshow add-on.\n [davisagli]", "- Add \"plone-5\" ZCML feature. Add-ons can register\n ZCML for Plone 5 only using zcml:condition=\"have plone-5\"\n [davisagli]", "- Plone's javascript is now developed as part of the Plone mockup\n (http://github.com/plone/mockup) and is included as a compiled\n bundle.\n [davisagli]", "- Removed portal_interface tool (PLIP #13770)\n [ale-rt]", "- Removed kss_field_decorator_view support\n [maurits, jaroel]" ]
[ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [9, 32, 98], "buggy_code_start_loc": [9, 32, 98], "filenames": ["CHANGES.rst", "Products/CMFPlone/URLTool.py", "Products/CMFPlone/tests/testURLTool.py"], "fixing_code_end_loc": [13, 36, 112], "fixing_code_start_loc": [10, 33, 99], "message": "Cross-site scripting (XSS) vulnerability in Plone 3.3.0 through 3.3.6, 4.0.0 through 4.0.10, 4.1.0 through 4.1.6, 4.2.0 through 4.2.7, 4.3.x before 4.3.7, and 5.0rc1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:plone:plone:3.3:*:*:*:*:*:*:*", "matchCriteriaId": "FDC93803-6506-4382-A013-18010EE7E06B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.1:*:*:*:*:*:*:*", "matchCriteriaId": "E65977FD-A880-4D16-B56B-94A72774F42D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.2:*:*:*:*:*:*:*", "matchCriteriaId": "4EA5B4F8-2155-403D-97D8-1272285D508B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.3:*:*:*:*:*:*:*", "matchCriteriaId": "A3CA2943-77E5-4384-A019-415BBCE62F94", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.4:*:*:*:*:*:*:*", "matchCriteriaId": "B7FF63F6-F1DC-4A97-A2E6-11CF613A31E8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.5:*:*:*:*:*:*:*", "matchCriteriaId": "538A3519-5B04-4FE5-A3C0-FD26EFA32705", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.6:*:*:*:*:*:*:*", "matchCriteriaId": "858CBC5A-C241-475C-8125-C5EA351B12A7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0:*:*:*:*:*:*:*", "matchCriteriaId": "F3306D84-0F5B-46BA-9BCC-DCD0A1CDD604", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "E08F4534-A588-463F-A745-39E559AB1CB8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "B64341BA-5722-415E-9771-9837168AB7C0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "E2929227-AE19-428D-9AC3-D312A559039B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "3B6DC866-0FEE-475B-855C-A69E004810CD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "50BF3E8E-152C-4E89-BAA2-A952D10F4611", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.7:*:*:*:*:*:*:*", "matchCriteriaId": "F1F88BF6-9058-4CB8-A2D6-5653860CF489", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.8:*:*:*:*:*:*:*", "matchCriteriaId": "B2AA3FA2-15C3-444A-8810-5EF3E0E84D58", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.9:*:*:*:*:*:*:*", "matchCriteriaId": "72F3B15A-CD0F-4CC5-A76F-E62637B30E2E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.10:*:*:*:*:*:*:*", "matchCriteriaId": "D913FCA7-4DAE-4E9A-9146-9AFA8472B04B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1:*:*:*:*:*:*:*", "matchCriteriaId": "7C44B53B-953B-4522-A5B4-11573850D2CD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.1:*:*:*:*:*:*:*", "matchCriteriaId": "D8883023-113A-420A-97B6-A4A9B29CF7DB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.2:*:*:*:*:*:*:*", "matchCriteriaId": "4DF4D113-8D9D-4DA3-A177-64783352F608", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.3:*:*:*:*:*:*:*", "matchCriteriaId": "28F9B699-D1A4-425C-84ED-6A8FD29BE7F8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.4:*:*:*:*:*:*:*", "matchCriteriaId": "47321B60-67DA-4543-B173-D629A9569B45", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.5:*:*:*:*:*:*:*", "matchCriteriaId": "58B36EB2-723F-4E25-8018-EEB2BE806D9D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.6:*:*:*:*:*:*:*", "matchCriteriaId": "7962EF74-6AC1-424C-A202-163AFDADA971", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2:*:*:*:*:*:*:*", "matchCriteriaId": "1F1818BB-E23A-4136-898D-1D0C80C08728", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "5CB06627-133A-40D1-8816-E31E0A9BAD22", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "AE7E448A-2C0C-4DE0-89EA-904718CB6C6D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.3:*:*:*:*:*:*:*", "matchCriteriaId": "6E727C5C-9E54-49F7-B92C-2492069AAE08", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.4:*:*:*:*:*:*:*", "matchCriteriaId": "BFD68465-4CDC-4788-8932-41335B5C4AC8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.5:*:*:*:*:*:*:*", "matchCriteriaId": "A7B739E0-FB73-401C-AB1A-E3C1434AA2A3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.6:*:*:*:*:*:*:*", "matchCriteriaId": "DCC8B987-5173-4C61-8DE6-B70C18EE6FD3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.7:*:*:*:*:*:*:*", "matchCriteriaId": "38BA31E8-77EC-478B-BC6E-E2F145A8B9BD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3:*:*:*:*:*:*:*", "matchCriteriaId": "CE168A35-1A46-4A6F-8A08-25CDD886066D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.1:*:*:*:*:*:*:*", "matchCriteriaId": "CFE0FC06-369B-46CF-9B1E-BAF7AF87E950", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.2:*:*:*:*:*:*:*", "matchCriteriaId": "56571585-E9A2-4B78-B2B1-5D8EADED522A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.3:*:*:*:*:*:*:*", "matchCriteriaId": "2CDF8A15-401C-453E-8D09-8D4CDD4766DB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.4:*:*:*:*:*:*:*", "matchCriteriaId": "39B0B1CE-C0D9-495C-B4E7-E52A50BD6D97", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.5:*:*:*:*:*:*:*", "matchCriteriaId": "043B3CBE-DEA2-474D-AA57-1830A470B621", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.6:*:*:*:*:*:*:*", "matchCriteriaId": "08A6842B-B479-4D91-928A-1CCE1DCB936E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:5.0:rc1:*:*:*:*:*:*", "matchCriteriaId": "8AF9FB6C-134F-4653-8771-1BF46AB39344", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site scripting (XSS) vulnerability in Plone 3.3.0 through 3.3.6, 4.0.0 through 4.0.10, 4.1.0 through 4.1.6, 4.2.0 through 4.2.7, 4.3.x before 4.3.7, and 5.0rc1."}, {"lang": "es", "value": "Existe una vulnerabilidad de tipo Cross-Site Scripting (XSS) en Plone desde la versi\u00f3n 3.3.0 hasta la versi\u00f3n 3.3.6, desde la 4.0.0 hasta la 4.0.10, desde la 4.1.0 hasta la 4.1.6, desde la 4.2.0 hasta la 4.2.7, en las versiones 4.3.x anteriores a la 4.3.7 y 5.0rc1."}], "evaluatorComment": null, "id": "CVE-2015-7316", "lastModified": "2017-10-03T14:47:29.810", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-09-25T17:29:00.587", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2015/09/22/14"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1264788"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/plone/Products.CMFPlone/commit/3da710a2cd68587f0bf34f2e7ea1167d6eeee087"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://plone.org/security/hotfix/20150910/non-persistent-xss-in-plone"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/plone/Products.CMFPlone/commit/3da710a2cd68587f0bf34f2e7ea1167d6eeee087"}, "type": "CWE-79"}
203
Determine whether the {function_name} code is vulnerable or not.
[ ".. This file should contain the changes for the last release only, which\n will be included on the package's page on pypi. All older entries are\n kept in HISTORY.txt", "Changelog\n=========", "5.0rc2 (unreleased)\n-------------------", "\n- Apply isURLInPortal fix from https://pypi.python.org/pypi/Products.PloneHotfix20150910\n [vangheem]", "\n- Do not bother additional CRSF protection for addMember since all public\n users get same CSRF token and the method should be unpublished.\n See https://pypi.python.org/pypi/Products.PloneHotfix20150910\n [vangheem]", "- Remove site properties that have been migrated to the registry.\n [esteele]", "- fix #862: Profile listing on site creation has alignment issues\n [ichim-david]", "\n5.0rc1 (2015-09-08)\n-------------------", "- Remove deprecated global_defines.pt\n [esteele]", "- Remove no-longer-used properties from portal_properties\n [esteele]", "- Move footer and colophon out of skins\n [vangheem]", "- pre-cook resources so we do not write on read for resources generation\n [vangheem]", "- Turn robots.txt into a browser-view, fix link to sitemap.xml.gz, allow\n editing in site-controlpanel.\n Fixes https://github.com/plone/Products.CMFPlone/issues/604\n [pbauer]", "- Remove history_form, history_comparison templates.\n Remove now-empty plone_forms skins folder.\n [esteele]", "- Remove no-longer-used images from portal_images.\n [esteele]", "- Typo in delete modal configuration caused submission redirection errors\n [vangheem]", "- Upgrade known core packages at the end of the Plone migration.\n [maurits]", "- remove Products.CMFPlone.utils.isLinked function. Switch to using\n plone.app.linkintegrity's variant\n [vangheem]", "- Fix error to allow site navigation if TinyMCE content_css setting is None\n [Gagaro]", "5.0b4 (2015-08-23)\n------------------", "- fix #350: \"plone.app.content circular dependency on Products.CMFPlone\" - this\n fixes the imports only, not on zcml/genericsetup level.\n [jensens]", "- move Plone specific ``getDefaultPage`` (magic) code from plone.app.layout\n over to Products.CMFPlone. This avoids a circular dependency. Also its\n not really layout only related code.\n [jensens]", "- Fix add-ons to be installed using CMFQuickInstaller (restore support\n for Extensions/Install.py)\n [datakurre]", "- Rename showEditableBorder to showToolbar and deprecate using\n disable_border and enable_border for enable_toolbar and disable_toolbar\n [vangheem]", "- Not using less variables in toolbar everywhere\n [vangheem]", "- Fix link to documentation", "- Rework timezone selection in @@plone-addsite.\n [jaroel]", "- Rework language selection in @@plone-addsite.\n [jaroel]", "- Turn @@tinymce-controlpanel ``content_css`` field into a list, so we can add\n several CSS URLs (useful when add-ons need to provide extra TinyMCE styles),\n and fix TinyMCE config getter so it considers the ``content_css`` value.\n [ebrehault]", "\n5.0b3 (2015-07-20)\n------------------", "- show toolbar buttons on sitemap, accessibility and search pages\n [vangheem]", "- log info after catalog rebuilt\n [vangheem]", "- Renamed 'Zope Management Interface' to 'Management Interface'.\n [jaroel]", "- Fix adding a new Plone site with country specific language. Refs #411.\n [jaroel]", "- fix plone-logged-in bundle not using global jquery for requirejs dependency and in\n weird cases causing select2 load errors in patterns(especially resource registry)\n [vangheem]", "- Use new plone.app.theming policy API and delegate theme cache to plone.app.theming\n [gyst]", "- Fix issue where site root syndication was giving 404s\n [vangheem]", "- update time widget interval selection to be the same as Plone 4 time selection intervals\n [vangheem]", "- use ajax_load in @@search when loading results dynamically, and add missing\n closing tag\n [ebrehault]", "- better formatting of config.js\n [vangheem]", "- Upload pattern uses the baseUrl to compute the upload URL, so this should\n always be the site root and not the current context\n [frapell]", "- rewrite css files when saving customized files in the resource registry\n [vangheem]", "- Update links to point to '@@overview-controlpanel'.\n Fixes https://github.com/plone/Products.CMFPlone/issues/573\n [gforcada]", "- Fix email validation of long domain names.\n [gotcha]", "- fix syndication feed use of lead image as it was using wrong url\n [vangheem]", "- add utility to get site logo\n [vangheem]", "- fix issue where product upgrade did show an error status message\n [datakurre]", "- fix casing on \"First weekday\" field on Date and Time control panel\n [vangheem]", "- fix imaging control panel example format on description\n [vangheem]", "- Add page title to resource registry\n [vangheem]", "- Remove ramcache-controlpanel csrf test. Ramcache control panel has been\n moved to p.a.caching since ages. We will get rid of it.\n [timo]", "- Add undeclared zope.cachedescriptors dependency.\n [timo]", "- Do not require \"Enable LiveSearch\". This fixes https://github.com/plone/Products.CMFPlone/issues/558\n [timo]", "- Fix control panel titles. This fixes https://github.com/plone/Products.CMFPlone/issues/550 https://github.com/plone/Products.CMFPlone/issues/553 https://github.com/plone/Products.CMFPlone/issues/557\n [timo]", "- remove plone.app.jquerytools dependency\n [vangheem]", "- fix bug where bundles would not get built properly with\n compile-plone-resources script when multiple resources\n were defined for a bundle\n [vangheem]", "- do not require css to be defined for non-compilable bundles\n [vangheem]", "- fix weird issue with selecting multiple links and images on a page\n while you are editing with tinymce\n [vangheem]", "- updates to contact forms to make them more user friendly on submission\n [vangheem]", "- include code plugin by default for TinyMCE\n [vangheem]", "- Fix build reading browser cached files by appending random query\n param onto url. See https://github.com/plone/Products.CMFPlone/commit/2d3865805efc6b72dce236eb68e502d8c57717b6\n and https://github.com/plone/Products.CMFPlone/commit/bd1f9ba99d1ad40bb7fe1c00eaa32b8884aae5e2\n [vangheem]", "- fix manage content type and group portlets link to have authenticator\n [vangheem]", "- Convert manage-portlets.js into a pattern and make improvements on\n using the manage portlets infrastructure\n [vangheem]", "- Remove dependency on plone.app.form and other formlib packages\n [tomgross]", "- Remove plone.skip_links from the default set of viewlets in order to follow\n modern a11y methods and drop support for outdated ways [sneridagh]", "- Change the name and link of 'Types' control panel to 'Content Settings' and\n '@@content-controlpanel' since there was confusion with the 'Dexterity\n Content Types' one [sneridagh]", "\n5.0b2 (2015-05-13)\n------------------", "- Add social media settings control panel", "- add ability to provide a css file for tinymce style formats\n [vangheem]", "- fix plone-generate-gruntfile to compile each less resource\n separately\n [vangheem]", "- provide image alignment styles for tinymce images\n [vangheem]", "- Respect TinyMCE control panel settings\n [vangheem]", "- enable/disable versioning behavior with settings in Types control panel\n [vangheem]", "- Make typesToList read metaTypesNotToList from new p.a.registry settings.\n This fixes https://github.com/plone/Products.CMFPlone/issues/454.\n [timo]", "- style tweaks to toolbar\n [pbauer]", "- fix search form usability\n [vangheem]", "- detect when changes are made to the legacy bundle through the interface\n so resources are re-built when they need to be\n [vangheem]", "- fix some legacy import wonkiness. Inserting multiple times, insert-before\n and remove fixed\n [vangheem]", "- make live search and search form give consistent results\n [vangheem]", "- only show edit bar if user logged in\n [vangheem]", "- fix error sending test email in Mail control panel\n [tkimnguyen]", "- pat-modal pattern has been renamed to pat-plone-modal\n [jcbrand]", "- Remove Products.CMFFormController dependency.\n [timo]", "- Fix submission of tinymce control panel.\n [davisagli]", "- Monkey patch SMTPMailer init method to pick up the mail settings from the\n registry instead of from the MailHost itself.\n [timo]", "- Add `resource_blacklist` attribute to resource registry importer, to\n allow filtering of known bad legacy resource imports. Filter js from\n plone.app.jquery.\n [alecm]", "- Fix broken \"Installing a third party add-on\" link\n [cedricmessiant]", "- Fix folder contents button disappeared act\n [vangheem]", "- Fix resource registry javascript build\n [vangheem]", "- Move `plone.htmlhead.links` viewlet manager after `plone.scripts`,\n because the former is sometimes used to include scripts that depend on\n the latter.\n [davisagli]", "- Change the order of the plonebar user menu and move the plone.personal_bar\n viewlet to the last position due to accessibility issues on having it being\n the first element.\n [sneridagh]", "- We only support `utf-8` site-encoding at the moment\n [tomgross]", "\n5.0b1.post1 (2015-03-27)\n------------------------", "- Packaging fix, no code changes.\n [esteele]", "\n5.0b1 (2015-03-26)\n------------------", "- Add tests for configuring encoding of user registration or\n forgotten password emails.\n [davidjb]", "- Pass email encoding to forgotten password email template.\n [davidjb]", "- Pass mail ``Content-Type`` to mailhost when sending forgotten password\n emails.\n [davidjb]", "- Move security control panel to CMFPlone. Fixes #216.\n [jcerjak, timo]", "- Remove ``create_userfolder`` from addPloneSite factory, it is not used\n anymore.\n [jcerjak]", "- Read security settings from the registry instead of portal properties.\n [jcerjak,timo]", "- Fix tests for plone.app.contenttypes unified view names, which uses\n ``listing_view`` for Folder and Collection types.\n [thet]", "- Remove ``selectable_views`` from ``properties.xml``, which isn't used\n anywhere anymore.\n [thet]", "- Remove the remaining ``Topic`` entry in ``default_page_types`` from\n ``propertiestool.xml``. This setting is now done in\n ``plone.app.contenttypes`` respectively ``Products.ATContentTypes``.\n [thet]", "- Add __version__ attribute to __init__.py. This allows us to retrieve the\n current Plone version with 'Products.CMFPlone.__version__'. Even though this\n is no offical standard, many packages in the Python standard library provide\n this.\n [timo]", "- Replaced the legacy mark_special_links javascript with a\n corresponding mockup pattern.\n [fulv]", "- remove plone_javascript_variables.js as necessary values\n are provided on body tag and pattern options\n [vangheem]", "- fix bootstrap css bleeding into global namespaces\n [vangheem]", "- add recurrence pattern\n [vangheem]", "- add history support for folder contents\n [vangheem]", "- Merge plone.app.search here\n [vangheem]", "- Extended ulocalized_time for target_language\n [agitator]", "- Caching for ``@@site-logo``.\n [thet]", "- Support for portal site logos stored in the portal registry by uploading via\n the site control panel. Add a ``@@site-logo`` view for downloading the logo.\n [thet]", "- Fix the resource registry to save the automatically generated filepath to the\n compiled resource on the bundle object after compilation. The filepath is\n always in the '++plone++static/' namespace. This fix makes custom bundles\n actually includable.\n [thet]", "- Get icon from layout_view instead of plone_view.\n [pbauer]", "- Fix contentViews (tabs) markup for Plone 5.\n [davisagli]", "- Rename syndication-settings to syndication-controlpanel. Keep the old view registration for backwards compatibility.\n [timo]", "- Added a link for the advanced 'Create a Plone site' screen to the Plone overview.\n [jaroel]", "- Fixed the label for 'Example content' in the advanced 'Create a Plone site' screen.\n [jaroel]", "- Move markup control panel to CMFPlone. Fixes #220.\n [djay, thet]", "- Use jstz to set default portal_timezone in @@plone-addsite.\n [instification]", "- Make inline validation of AT multiple selection widget work.\n [gbastien]", "- Make sure compiling resources does not commit transaction prematurely.\n [davisagli]", "- Adding the option to configure a bundle from the diazo manifest file.\n [bloodbare]", "- Move the controlpanel overview from plone.app.controlpanel into this package\n https://github.com/plone/Products.CMFPlone/issues/290\n [khink]", "- PLIP 10359: Migrate usergroups controlpanel to ``z3c.form`` and move it from\n plone.app.controlpanel to Products.CMFPlone. Fix and extend tests and add\n robot tests.\n [ferewuz]", "\n5.0a3 (2014-11-01)\n------------------", "- folder_position script: make position and id optional. Default\n position to 'ordered' and id to None, which means: do nothing.\n plone.folder 1.0.5 allows this, making it possible to simply reverse\n the current sort order by using reverse=False.\n [maurits]", "- Fix JS resource viewlet HTML syntax error.\n [rpatterson]", "- Fix resource bundle expressions. They weren't being checked at all and\n reversed the condition if they had been. Also move caching of the cooked\n expressions out of the DB and into a RAM cache.\n [rpatterson]", "- Fix endless resource dependency loop when dependeing on a bundle that also has\n a dependency.\n [rpatterson]", "- reduce deprecation warnings to use plone_layout and not plone_view for\n certain method calls in order to make debugging of robottests easier:\n w/o it shows 1000ds of extra lines in html report.\n [jensens]", "- type controlpanel: Resolved problem with workflow selection form as it\n was breaking if state title had non-ascii characters. see also\n https://github.com/plone/plone.app.controlpanel/pull/26\n [lewicki, jensens]", "- Minor overhaul of CatalogTool.py - no feature changes!\n Optimizations and better readable code for indexer\n ``allowedRolesAndUsers``: now using a set.\n Change if/elif/else to oneliner boolean expression in ``is_folderish``\n indexer.\n Usage of AccessControl 3 style decorators for security declarations.\n Minor reformattings to make code-analysis happy.\n [jensens]", "- Removed some javascripts: fullscreenmode.js, dragdropreorder.js,\n styleswitcher.js, select_all.js, collapsibleformfields.js", "- PLIP 13260: Migration cut, copy and paste into browser views.\n [saily]", "- Abstract the search form and livesearch action URLs making it easier to\n extend the search portlet with custom views or other actions.\n [rpatterson]", "- Fix JavaScript to work with recent jQuery (>= 1.9) versions.\n [thet]", "- Small scoping fix in locking js code\n [do3cc]", "- PLIP 13260: Migrate author page to browser views/z3c.form (issue #78)\n [bosim]", "- Integration of the new markup update and CSS for both Plone and Barceloneta\n theme. This is the work done in the GSOC Barceloneta theme project.\n [albertcasado, sneridagh]", "- Created new viewlet manager for holding main navigation for a more semantic\n use of it. Move the global sections viewlet into it.\n [albertcasado]", "- New toolbar markup based in ul li tags.\n [albertcasado, bloodbare, sneridagh]", "- Update <div id=\"content\"> in all templates with <article id=\"content\">\n [albertcasado]", "- PLIP 14261: New resource registries.\n [bloodbare, vangheem, robgietema, et al]", "\n5.0a2 (2014-04-20)\n------------------", "- Advertise the migration of content to dexterity after a successful\n upgrade to Plone 5.\n [pbauer]", "- Strip leading & trailing spaces from id and title in rename-form.\n See https://dev.plone.org/ticket/12998, https://dev.plone.org/ticket/12989,\n https://dev.plone.org/ticket/9370, https://dev.plone.org/ticket/8338\n [pbauer]", "- Fix incorrect use of dict get method in CatalogTool.search, introduced\n by PloneHotfix20131210 (issue 195)\n [fulv]", "- Added timezone selection to add site page\n [pysailor, yenzenz]", "- Added date date and time controlpanel (moved over from plone.app.event).\n [yenzenz. thet]", "- Remove DL/DT/DD's from portal messages, portlet templates and others.\n https://github.com/plone/Products.CMFPlone/issues/153\n https://github.com/plone/Products.CMFPlone/issues/163\n [khink]", "- PLIP 13260 remove templates and form scripts for\n ``select_default_page`` and ``select_default_view`` because they got\n migrated to browser views. Fix tests for that and remove legacy tests.\n See: https://github.com/plone/Products.CMFPlone/issues/90\n [saily]", "- PLIP 13260: Migration contact-info to ``z3c.form`` and make it highly\n customizeable.\n [timitos, saily]", "\n5.0a1 (2014-03-02)\n------------------", "- remove quickinstall control panel form since a new one was moved to\n plone.app.controlpanel\n [vangheem]", "- Add 'warning' and 'error' status message types to the test_rendering\n view.\n [esteele]", "- Update the front-page links.\n [esteele]", "- In plone-overview view, we can now see Plone sites which are contained into\n Zope folder.\n [bsuttor]", "- Make Plone tool read the exposeDCMetaTags from p.a.registry instead of\n of the site properties.\n [timo]", "- Hide plone.app.registry install profile in the add-ons control panel.\n [esteele]", "- Removed spamProtect.py script, since it doesn't offer real protection.\n [davisagli]", "- Moved the member search form to plone.app.users\n [pabo3000]", "- PLIP #13705: Remove <base> tag.\n [frapell]", "- merge hotfixes from 20131210\n [vangheem]", "- handle plone.app.textfield RichTextValue objects in syndication. Should\n fix syndication with plone.app.contenttypes.\n [vangheem]", "- FolderFeed adapter now takes into account the limit property when displaying\n the RSS feed just like the other adapters do\n [ichim-david]", "- Remove the portal_calendar tool and the dependency on CMFCalendar.\n [davisagli]", "- Remove the plone_deprecated skin layer.\n [gforcada, davisagli]", "- Moved portal_factory and portal_metadata from Products.CMFPlone to\n Products.ATContentTypes (PLIP #13770)\n [ale-rt]", "- Remove the portal_interface tool.\n [ale-rt]", "- Remove the portal_actionicons tool.\n [davisagli]", "- Remove ownership_form and change_ownership script, which were not used.\n [davisagli]", "- Convert author_feedback_template and accessibility_info to browser views.\n [bloodbare]", "- Move calendar_macros and jscalendar to Products.Archetypes.\n [bloodbare]", "- Remove plonetheme.classic from the package dependencies and the default\n extension profile, since it will not ship with Plone 5.\n [timo]", "- Move docs/CHANGES.txt to CHANGES.rst.\n [timo]", "- Replace deprecated test assert statements.\n [timo]", "- Add a dependency on plone.app.theming. Install by default.\n [esteele]", "- Drop dependency on plonetheme.classic.\n [esteele]", "- Remove old logo.jpg. Use logo.png from Sunburst.\n [esteele]", "- Inline validation JavaScript for z3c.form only sends request when\n field name can be obtained from DOM for a widget (#13741).\n [seanupton]", "- Add use_uuid_as_userid site property.\n Part of PLIP 13419.\n [maurits]", "- Let set_own_login_name use the update(Own)LoginName method from PAS.\n Part of PLIP 13419.\n [maurits]", "- recently_modified and recently_published respects allow anonymous to view\n about setting\n [vangheem]", "- Return a 404 instead of \"AttributeError: (dynamic view)\" if a user attempts to\n view a still-temporary PortalFactory item.\n [esteele]", "- Ensure that initial_login is set to True when a user first logs in.\n [taito]", "- Merged PLIP #12198: Depend on Chameleon (five.pt) as a faster page template\n engine.\n [davisagli]", "- make extensionprofiles selection part of 'advanced' in plone-addsite\n [jaroel]", "- enable syndication on plone.app.contenttypes collection\n [vangheem]", "- fix syndication settings to not write on read\n [vangheem]", "- fix wrong download url for podcast syndication\n [Rudd-O]", "- Merged PLIP #12344: Use Dexterity-based core content types.", " * Avoid including ATContentTypes and Archetypes as a dependency.\n * Install the plone.app.contenttypes profile for new sites.", " [davisagli et al]", "- Merged PLIP #13270: Move presentation mode out of core.\n If the feature is still desired, use the plone.app.s5slideshow add-on.\n [davisagli]", "- Add \"plone-5\" ZCML feature. Add-ons can register\n ZCML for Plone 5 only using zcml:condition=\"have plone-5\"\n [davisagli]", "- Plone's javascript is now developed as part of the Plone mockup\n (http://github.com/plone/mockup) and is included as a compiled\n bundle.\n [davisagli]", "- Removed portal_interface tool (PLIP #13770)\n [ale-rt]", "- Removed kss_field_decorator_view support\n [maurits, jaroel]" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [9, 32, 98], "buggy_code_start_loc": [9, 32, 98], "filenames": ["CHANGES.rst", "Products/CMFPlone/URLTool.py", "Products/CMFPlone/tests/testURLTool.py"], "fixing_code_end_loc": [13, 36, 112], "fixing_code_start_loc": [10, 33, 99], "message": "Cross-site scripting (XSS) vulnerability in Plone 3.3.0 through 3.3.6, 4.0.0 through 4.0.10, 4.1.0 through 4.1.6, 4.2.0 through 4.2.7, 4.3.x before 4.3.7, and 5.0rc1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:plone:plone:3.3:*:*:*:*:*:*:*", "matchCriteriaId": "FDC93803-6506-4382-A013-18010EE7E06B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.1:*:*:*:*:*:*:*", "matchCriteriaId": "E65977FD-A880-4D16-B56B-94A72774F42D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.2:*:*:*:*:*:*:*", "matchCriteriaId": "4EA5B4F8-2155-403D-97D8-1272285D508B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.3:*:*:*:*:*:*:*", "matchCriteriaId": "A3CA2943-77E5-4384-A019-415BBCE62F94", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.4:*:*:*:*:*:*:*", "matchCriteriaId": "B7FF63F6-F1DC-4A97-A2E6-11CF613A31E8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.5:*:*:*:*:*:*:*", "matchCriteriaId": "538A3519-5B04-4FE5-A3C0-FD26EFA32705", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.6:*:*:*:*:*:*:*", "matchCriteriaId": "858CBC5A-C241-475C-8125-C5EA351B12A7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0:*:*:*:*:*:*:*", "matchCriteriaId": "F3306D84-0F5B-46BA-9BCC-DCD0A1CDD604", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "E08F4534-A588-463F-A745-39E559AB1CB8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "B64341BA-5722-415E-9771-9837168AB7C0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "E2929227-AE19-428D-9AC3-D312A559039B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "3B6DC866-0FEE-475B-855C-A69E004810CD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "50BF3E8E-152C-4E89-BAA2-A952D10F4611", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.7:*:*:*:*:*:*:*", "matchCriteriaId": "F1F88BF6-9058-4CB8-A2D6-5653860CF489", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.8:*:*:*:*:*:*:*", "matchCriteriaId": "B2AA3FA2-15C3-444A-8810-5EF3E0E84D58", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.9:*:*:*:*:*:*:*", "matchCriteriaId": "72F3B15A-CD0F-4CC5-A76F-E62637B30E2E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.10:*:*:*:*:*:*:*", "matchCriteriaId": "D913FCA7-4DAE-4E9A-9146-9AFA8472B04B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1:*:*:*:*:*:*:*", "matchCriteriaId": "7C44B53B-953B-4522-A5B4-11573850D2CD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.1:*:*:*:*:*:*:*", "matchCriteriaId": "D8883023-113A-420A-97B6-A4A9B29CF7DB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.2:*:*:*:*:*:*:*", "matchCriteriaId": "4DF4D113-8D9D-4DA3-A177-64783352F608", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.3:*:*:*:*:*:*:*", "matchCriteriaId": "28F9B699-D1A4-425C-84ED-6A8FD29BE7F8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.4:*:*:*:*:*:*:*", "matchCriteriaId": "47321B60-67DA-4543-B173-D629A9569B45", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.5:*:*:*:*:*:*:*", "matchCriteriaId": "58B36EB2-723F-4E25-8018-EEB2BE806D9D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.6:*:*:*:*:*:*:*", "matchCriteriaId": "7962EF74-6AC1-424C-A202-163AFDADA971", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2:*:*:*:*:*:*:*", "matchCriteriaId": "1F1818BB-E23A-4136-898D-1D0C80C08728", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "5CB06627-133A-40D1-8816-E31E0A9BAD22", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "AE7E448A-2C0C-4DE0-89EA-904718CB6C6D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.3:*:*:*:*:*:*:*", "matchCriteriaId": "6E727C5C-9E54-49F7-B92C-2492069AAE08", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.4:*:*:*:*:*:*:*", "matchCriteriaId": "BFD68465-4CDC-4788-8932-41335B5C4AC8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.5:*:*:*:*:*:*:*", "matchCriteriaId": "A7B739E0-FB73-401C-AB1A-E3C1434AA2A3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.6:*:*:*:*:*:*:*", "matchCriteriaId": "DCC8B987-5173-4C61-8DE6-B70C18EE6FD3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.7:*:*:*:*:*:*:*", "matchCriteriaId": "38BA31E8-77EC-478B-BC6E-E2F145A8B9BD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3:*:*:*:*:*:*:*", "matchCriteriaId": "CE168A35-1A46-4A6F-8A08-25CDD886066D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.1:*:*:*:*:*:*:*", "matchCriteriaId": "CFE0FC06-369B-46CF-9B1E-BAF7AF87E950", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.2:*:*:*:*:*:*:*", "matchCriteriaId": "56571585-E9A2-4B78-B2B1-5D8EADED522A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.3:*:*:*:*:*:*:*", "matchCriteriaId": "2CDF8A15-401C-453E-8D09-8D4CDD4766DB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.4:*:*:*:*:*:*:*", "matchCriteriaId": "39B0B1CE-C0D9-495C-B4E7-E52A50BD6D97", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.5:*:*:*:*:*:*:*", "matchCriteriaId": "043B3CBE-DEA2-474D-AA57-1830A470B621", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.6:*:*:*:*:*:*:*", "matchCriteriaId": "08A6842B-B479-4D91-928A-1CCE1DCB936E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:5.0:rc1:*:*:*:*:*:*", "matchCriteriaId": "8AF9FB6C-134F-4653-8771-1BF46AB39344", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site scripting (XSS) vulnerability in Plone 3.3.0 through 3.3.6, 4.0.0 through 4.0.10, 4.1.0 through 4.1.6, 4.2.0 through 4.2.7, 4.3.x before 4.3.7, and 5.0rc1."}, {"lang": "es", "value": "Existe una vulnerabilidad de tipo Cross-Site Scripting (XSS) en Plone desde la versi\u00f3n 3.3.0 hasta la versi\u00f3n 3.3.6, desde la 4.0.0 hasta la 4.0.10, desde la 4.1.0 hasta la 4.1.6, desde la 4.2.0 hasta la 4.2.7, en las versiones 4.3.x anteriores a la 4.3.7 y 5.0rc1."}], "evaluatorComment": null, "id": "CVE-2015-7316", "lastModified": "2017-10-03T14:47:29.810", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-09-25T17:29:00.587", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2015/09/22/14"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1264788"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/plone/Products.CMFPlone/commit/3da710a2cd68587f0bf34f2e7ea1167d6eeee087"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://plone.org/security/hotfix/20150910/non-persistent-xss-in-plone"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/plone/Products.CMFPlone/commit/3da710a2cd68587f0bf34f2e7ea1167d6eeee087"}, "type": "CWE-79"}
203
Determine whether the {function_name} code is vulnerable or not.
[ "from Products.CMFCore.URLTool import URLTool as BaseTool\nfrom Products.CMFCore.utils import getToolByName\nfrom AccessControl import ClassSecurityInfo\nfrom App.class_init import InitializeClass\nfrom Products.CMFPlone.PloneBaseTool import PloneBaseTool", "from posixpath import normpath\nfrom urlparse import urlparse, urljoin\nimport re", "\nclass URLTool(PloneBaseTool, BaseTool):", " meta_type = 'Plone URL Tool'\n security = ClassSecurityInfo()\n toolicon = 'skins/plone_images/link_icon.png'", " security.declarePublic('isURLInPortal')\n def isURLInPortal(self, url, context=None):\n \"\"\" Check if a given url is on the same host and contains the portal\n path. Used to ensure that login forms can determine relevant\n referrers (i.e. in portal). Also return true for some relative\n urls if context is passed in to allow for url parsing. When context\n is not provided, assume that relative urls are in the portal. It is\n assumed that http://portal is the same portal as https://portal.", " External sites listed in 'allow_external_login_sites' of\n site_properties are also considered within the portal to allow for\n single sign on.\n \"\"\"\n # sanitize url\n url = re.sub('^[\\x00-\\x20]+', '', url).strip()", "", "\n p_url = self()", " _, u_host, u_path, _, _, _ = urlparse(url)\n if not u_host and not u_path.startswith('/'):\n if context is None:\n return True # old behavior\n if not context.isPrincipiaFolderish:\n useurl = context.aq_parent.absolute_url()\n else:\n useurl = context.absolute_url()\n else:\n useurl = p_url # when u_path.startswith('/')\n if not useurl.endswith('/'):\n useurl += '/'", " # urljoin to current url to get an absolute path\n _, u_host, u_path, _, _, _ = urlparse(urljoin(useurl, url))", " # normalise to end with a '/' so /foobar is not considered within /foo\n if not u_path:\n u_path = '/'\n else:\n u_path = normpath(u_path)\n if not u_path.endswith('/'):\n u_path += '/'\n _, host, path, _, _, _ = urlparse(p_url)\n if not path.endswith('/'):\n path += '/'\n if host == u_host and u_path.startswith(path):\n return True", " props = getToolByName(self, 'portal_properties').site_properties\n for external_site in props.getProperty('allow_external_login_sites', []):\n _, host, path, _, _, _ = urlparse(external_site)\n if not path.endswith('/'):\n path += '/'\n if host == u_host and u_path.startswith(path):\n return True\n return False", "\nURLTool.__doc__ = BaseTool.__doc__", "InitializeClass(URLTool)" ]
[ 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [9, 32, 98], "buggy_code_start_loc": [9, 32, 98], "filenames": ["CHANGES.rst", "Products/CMFPlone/URLTool.py", "Products/CMFPlone/tests/testURLTool.py"], "fixing_code_end_loc": [13, 36, 112], "fixing_code_start_loc": [10, 33, 99], "message": "Cross-site scripting (XSS) vulnerability in Plone 3.3.0 through 3.3.6, 4.0.0 through 4.0.10, 4.1.0 through 4.1.6, 4.2.0 through 4.2.7, 4.3.x before 4.3.7, and 5.0rc1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:plone:plone:3.3:*:*:*:*:*:*:*", "matchCriteriaId": "FDC93803-6506-4382-A013-18010EE7E06B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.1:*:*:*:*:*:*:*", "matchCriteriaId": "E65977FD-A880-4D16-B56B-94A72774F42D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.2:*:*:*:*:*:*:*", "matchCriteriaId": "4EA5B4F8-2155-403D-97D8-1272285D508B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.3:*:*:*:*:*:*:*", "matchCriteriaId": "A3CA2943-77E5-4384-A019-415BBCE62F94", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.4:*:*:*:*:*:*:*", "matchCriteriaId": "B7FF63F6-F1DC-4A97-A2E6-11CF613A31E8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.5:*:*:*:*:*:*:*", "matchCriteriaId": "538A3519-5B04-4FE5-A3C0-FD26EFA32705", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.6:*:*:*:*:*:*:*", "matchCriteriaId": "858CBC5A-C241-475C-8125-C5EA351B12A7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0:*:*:*:*:*:*:*", "matchCriteriaId": "F3306D84-0F5B-46BA-9BCC-DCD0A1CDD604", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "E08F4534-A588-463F-A745-39E559AB1CB8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "B64341BA-5722-415E-9771-9837168AB7C0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "E2929227-AE19-428D-9AC3-D312A559039B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "3B6DC866-0FEE-475B-855C-A69E004810CD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "50BF3E8E-152C-4E89-BAA2-A952D10F4611", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.7:*:*:*:*:*:*:*", "matchCriteriaId": "F1F88BF6-9058-4CB8-A2D6-5653860CF489", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.8:*:*:*:*:*:*:*", "matchCriteriaId": "B2AA3FA2-15C3-444A-8810-5EF3E0E84D58", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.9:*:*:*:*:*:*:*", "matchCriteriaId": "72F3B15A-CD0F-4CC5-A76F-E62637B30E2E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.10:*:*:*:*:*:*:*", "matchCriteriaId": "D913FCA7-4DAE-4E9A-9146-9AFA8472B04B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1:*:*:*:*:*:*:*", "matchCriteriaId": "7C44B53B-953B-4522-A5B4-11573850D2CD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.1:*:*:*:*:*:*:*", "matchCriteriaId": "D8883023-113A-420A-97B6-A4A9B29CF7DB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.2:*:*:*:*:*:*:*", "matchCriteriaId": "4DF4D113-8D9D-4DA3-A177-64783352F608", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.3:*:*:*:*:*:*:*", "matchCriteriaId": "28F9B699-D1A4-425C-84ED-6A8FD29BE7F8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.4:*:*:*:*:*:*:*", "matchCriteriaId": "47321B60-67DA-4543-B173-D629A9569B45", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.5:*:*:*:*:*:*:*", "matchCriteriaId": "58B36EB2-723F-4E25-8018-EEB2BE806D9D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.6:*:*:*:*:*:*:*", "matchCriteriaId": "7962EF74-6AC1-424C-A202-163AFDADA971", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2:*:*:*:*:*:*:*", "matchCriteriaId": "1F1818BB-E23A-4136-898D-1D0C80C08728", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "5CB06627-133A-40D1-8816-E31E0A9BAD22", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "AE7E448A-2C0C-4DE0-89EA-904718CB6C6D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.3:*:*:*:*:*:*:*", "matchCriteriaId": "6E727C5C-9E54-49F7-B92C-2492069AAE08", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.4:*:*:*:*:*:*:*", "matchCriteriaId": "BFD68465-4CDC-4788-8932-41335B5C4AC8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.5:*:*:*:*:*:*:*", "matchCriteriaId": "A7B739E0-FB73-401C-AB1A-E3C1434AA2A3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.6:*:*:*:*:*:*:*", "matchCriteriaId": "DCC8B987-5173-4C61-8DE6-B70C18EE6FD3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.7:*:*:*:*:*:*:*", "matchCriteriaId": "38BA31E8-77EC-478B-BC6E-E2F145A8B9BD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3:*:*:*:*:*:*:*", "matchCriteriaId": "CE168A35-1A46-4A6F-8A08-25CDD886066D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.1:*:*:*:*:*:*:*", "matchCriteriaId": "CFE0FC06-369B-46CF-9B1E-BAF7AF87E950", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.2:*:*:*:*:*:*:*", "matchCriteriaId": "56571585-E9A2-4B78-B2B1-5D8EADED522A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.3:*:*:*:*:*:*:*", "matchCriteriaId": "2CDF8A15-401C-453E-8D09-8D4CDD4766DB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.4:*:*:*:*:*:*:*", "matchCriteriaId": "39B0B1CE-C0D9-495C-B4E7-E52A50BD6D97", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.5:*:*:*:*:*:*:*", "matchCriteriaId": "043B3CBE-DEA2-474D-AA57-1830A470B621", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.6:*:*:*:*:*:*:*", "matchCriteriaId": "08A6842B-B479-4D91-928A-1CCE1DCB936E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:5.0:rc1:*:*:*:*:*:*", "matchCriteriaId": "8AF9FB6C-134F-4653-8771-1BF46AB39344", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site scripting (XSS) vulnerability in Plone 3.3.0 through 3.3.6, 4.0.0 through 4.0.10, 4.1.0 through 4.1.6, 4.2.0 through 4.2.7, 4.3.x before 4.3.7, and 5.0rc1."}, {"lang": "es", "value": "Existe una vulnerabilidad de tipo Cross-Site Scripting (XSS) en Plone desde la versi\u00f3n 3.3.0 hasta la versi\u00f3n 3.3.6, desde la 4.0.0 hasta la 4.0.10, desde la 4.1.0 hasta la 4.1.6, desde la 4.2.0 hasta la 4.2.7, en las versiones 4.3.x anteriores a la 4.3.7 y 5.0rc1."}], "evaluatorComment": null, "id": "CVE-2015-7316", "lastModified": "2017-10-03T14:47:29.810", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-09-25T17:29:00.587", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2015/09/22/14"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1264788"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/plone/Products.CMFPlone/commit/3da710a2cd68587f0bf34f2e7ea1167d6eeee087"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://plone.org/security/hotfix/20150910/non-persistent-xss-in-plone"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/plone/Products.CMFPlone/commit/3da710a2cd68587f0bf34f2e7ea1167d6eeee087"}, "type": "CWE-79"}
203
Determine whether the {function_name} code is vulnerable or not.
[ "from Products.CMFCore.URLTool import URLTool as BaseTool\nfrom Products.CMFCore.utils import getToolByName\nfrom AccessControl import ClassSecurityInfo\nfrom App.class_init import InitializeClass\nfrom Products.CMFPlone.PloneBaseTool import PloneBaseTool", "from posixpath import normpath\nfrom urlparse import urlparse, urljoin\nimport re", "\nclass URLTool(PloneBaseTool, BaseTool):", " meta_type = 'Plone URL Tool'\n security = ClassSecurityInfo()\n toolicon = 'skins/plone_images/link_icon.png'", " security.declarePublic('isURLInPortal')\n def isURLInPortal(self, url, context=None):\n \"\"\" Check if a given url is on the same host and contains the portal\n path. Used to ensure that login forms can determine relevant\n referrers (i.e. in portal). Also return true for some relative\n urls if context is passed in to allow for url parsing. When context\n is not provided, assume that relative urls are in the portal. It is\n assumed that http://portal is the same portal as https://portal.", " External sites listed in 'allow_external_login_sites' of\n site_properties are also considered within the portal to allow for\n single sign on.\n \"\"\"\n # sanitize url\n url = re.sub('^[\\x00-\\x20]+', '', url).strip()", " if ('<script' in url or '%3Cscript' in url or 'javascript:' in url or\n 'javascript%3A' in url):\n return False", "\n p_url = self()", " _, u_host, u_path, _, _, _ = urlparse(url)\n if not u_host and not u_path.startswith('/'):\n if context is None:\n return True # old behavior\n if not context.isPrincipiaFolderish:\n useurl = context.aq_parent.absolute_url()\n else:\n useurl = context.absolute_url()\n else:\n useurl = p_url # when u_path.startswith('/')\n if not useurl.endswith('/'):\n useurl += '/'", " # urljoin to current url to get an absolute path\n _, u_host, u_path, _, _, _ = urlparse(urljoin(useurl, url))", " # normalise to end with a '/' so /foobar is not considered within /foo\n if not u_path:\n u_path = '/'\n else:\n u_path = normpath(u_path)\n if not u_path.endswith('/'):\n u_path += '/'\n _, host, path, _, _, _ = urlparse(p_url)\n if not path.endswith('/'):\n path += '/'\n if host == u_host and u_path.startswith(path):\n return True", " props = getToolByName(self, 'portal_properties').site_properties\n for external_site in props.getProperty('allow_external_login_sites', []):\n _, host, path, _, _, _ = urlparse(external_site)\n if not path.endswith('/'):\n path += '/'\n if host == u_host and u_path.startswith(path):\n return True\n return False", "\nURLTool.__doc__ = BaseTool.__doc__", "InitializeClass(URLTool)" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [9, 32, 98], "buggy_code_start_loc": [9, 32, 98], "filenames": ["CHANGES.rst", "Products/CMFPlone/URLTool.py", "Products/CMFPlone/tests/testURLTool.py"], "fixing_code_end_loc": [13, 36, 112], "fixing_code_start_loc": [10, 33, 99], "message": "Cross-site scripting (XSS) vulnerability in Plone 3.3.0 through 3.3.6, 4.0.0 through 4.0.10, 4.1.0 through 4.1.6, 4.2.0 through 4.2.7, 4.3.x before 4.3.7, and 5.0rc1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:plone:plone:3.3:*:*:*:*:*:*:*", "matchCriteriaId": "FDC93803-6506-4382-A013-18010EE7E06B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.1:*:*:*:*:*:*:*", "matchCriteriaId": "E65977FD-A880-4D16-B56B-94A72774F42D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.2:*:*:*:*:*:*:*", "matchCriteriaId": "4EA5B4F8-2155-403D-97D8-1272285D508B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.3:*:*:*:*:*:*:*", "matchCriteriaId": "A3CA2943-77E5-4384-A019-415BBCE62F94", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.4:*:*:*:*:*:*:*", "matchCriteriaId": "B7FF63F6-F1DC-4A97-A2E6-11CF613A31E8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.5:*:*:*:*:*:*:*", "matchCriteriaId": "538A3519-5B04-4FE5-A3C0-FD26EFA32705", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.6:*:*:*:*:*:*:*", "matchCriteriaId": "858CBC5A-C241-475C-8125-C5EA351B12A7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0:*:*:*:*:*:*:*", "matchCriteriaId": "F3306D84-0F5B-46BA-9BCC-DCD0A1CDD604", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "E08F4534-A588-463F-A745-39E559AB1CB8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "B64341BA-5722-415E-9771-9837168AB7C0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "E2929227-AE19-428D-9AC3-D312A559039B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "3B6DC866-0FEE-475B-855C-A69E004810CD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "50BF3E8E-152C-4E89-BAA2-A952D10F4611", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.7:*:*:*:*:*:*:*", "matchCriteriaId": "F1F88BF6-9058-4CB8-A2D6-5653860CF489", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.8:*:*:*:*:*:*:*", "matchCriteriaId": "B2AA3FA2-15C3-444A-8810-5EF3E0E84D58", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.9:*:*:*:*:*:*:*", "matchCriteriaId": "72F3B15A-CD0F-4CC5-A76F-E62637B30E2E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.10:*:*:*:*:*:*:*", "matchCriteriaId": "D913FCA7-4DAE-4E9A-9146-9AFA8472B04B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1:*:*:*:*:*:*:*", "matchCriteriaId": "7C44B53B-953B-4522-A5B4-11573850D2CD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.1:*:*:*:*:*:*:*", "matchCriteriaId": "D8883023-113A-420A-97B6-A4A9B29CF7DB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.2:*:*:*:*:*:*:*", "matchCriteriaId": "4DF4D113-8D9D-4DA3-A177-64783352F608", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.3:*:*:*:*:*:*:*", "matchCriteriaId": "28F9B699-D1A4-425C-84ED-6A8FD29BE7F8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.4:*:*:*:*:*:*:*", "matchCriteriaId": "47321B60-67DA-4543-B173-D629A9569B45", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.5:*:*:*:*:*:*:*", "matchCriteriaId": "58B36EB2-723F-4E25-8018-EEB2BE806D9D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.6:*:*:*:*:*:*:*", "matchCriteriaId": "7962EF74-6AC1-424C-A202-163AFDADA971", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2:*:*:*:*:*:*:*", "matchCriteriaId": "1F1818BB-E23A-4136-898D-1D0C80C08728", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "5CB06627-133A-40D1-8816-E31E0A9BAD22", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "AE7E448A-2C0C-4DE0-89EA-904718CB6C6D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.3:*:*:*:*:*:*:*", "matchCriteriaId": "6E727C5C-9E54-49F7-B92C-2492069AAE08", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.4:*:*:*:*:*:*:*", "matchCriteriaId": "BFD68465-4CDC-4788-8932-41335B5C4AC8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.5:*:*:*:*:*:*:*", "matchCriteriaId": "A7B739E0-FB73-401C-AB1A-E3C1434AA2A3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.6:*:*:*:*:*:*:*", "matchCriteriaId": "DCC8B987-5173-4C61-8DE6-B70C18EE6FD3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.7:*:*:*:*:*:*:*", "matchCriteriaId": "38BA31E8-77EC-478B-BC6E-E2F145A8B9BD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3:*:*:*:*:*:*:*", "matchCriteriaId": "CE168A35-1A46-4A6F-8A08-25CDD886066D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.1:*:*:*:*:*:*:*", "matchCriteriaId": "CFE0FC06-369B-46CF-9B1E-BAF7AF87E950", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.2:*:*:*:*:*:*:*", "matchCriteriaId": "56571585-E9A2-4B78-B2B1-5D8EADED522A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.3:*:*:*:*:*:*:*", "matchCriteriaId": "2CDF8A15-401C-453E-8D09-8D4CDD4766DB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.4:*:*:*:*:*:*:*", "matchCriteriaId": "39B0B1CE-C0D9-495C-B4E7-E52A50BD6D97", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.5:*:*:*:*:*:*:*", "matchCriteriaId": "043B3CBE-DEA2-474D-AA57-1830A470B621", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.6:*:*:*:*:*:*:*", "matchCriteriaId": "08A6842B-B479-4D91-928A-1CCE1DCB936E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:5.0:rc1:*:*:*:*:*:*", "matchCriteriaId": "8AF9FB6C-134F-4653-8771-1BF46AB39344", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site scripting (XSS) vulnerability in Plone 3.3.0 through 3.3.6, 4.0.0 through 4.0.10, 4.1.0 through 4.1.6, 4.2.0 through 4.2.7, 4.3.x before 4.3.7, and 5.0rc1."}, {"lang": "es", "value": "Existe una vulnerabilidad de tipo Cross-Site Scripting (XSS) en Plone desde la versi\u00f3n 3.3.0 hasta la versi\u00f3n 3.3.6, desde la 4.0.0 hasta la 4.0.10, desde la 4.1.0 hasta la 4.1.6, desde la 4.2.0 hasta la 4.2.7, en las versiones 4.3.x anteriores a la 4.3.7 y 5.0rc1."}], "evaluatorComment": null, "id": "CVE-2015-7316", "lastModified": "2017-10-03T14:47:29.810", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-09-25T17:29:00.587", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2015/09/22/14"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1264788"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/plone/Products.CMFPlone/commit/3da710a2cd68587f0bf34f2e7ea1167d6eeee087"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://plone.org/security/hotfix/20150910/non-persistent-xss-in-plone"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/plone/Products.CMFPlone/commit/3da710a2cd68587f0bf34f2e7ea1167d6eeee087"}, "type": "CWE-79"}
203
Determine whether the {function_name} code is vulnerable or not.
[ "import unittest", "from Products.CMFCore.tests.base.dummy import DummySite\nfrom Products.CMFCore.tests.base.dummy import DummyFolder\nfrom Products.CMFCore.tests.base.dummy import DummyContent", "from Acquisition import aq_parent", "\nclass DummyFolder(DummyFolder):\n def absolute_url(self):\n return '/'.join([aq_parent(self).absolute_url(), self.getId()])", "\nclass DummyProperties(DummyContent):", " _allow_external_login_sites = [\n 'http://external1',\n 'http://external2/',\n 'http://external3/site',\n 'http://external4/site/'\n ]", " def getProperty(self, name, default=None):\n if name == 'allow_external_login_sites':\n return self._allow_external_login_sites\n return default", "\nclass TestURLTool(unittest.TestCase):", " def setUp(self):\n self.site = DummySite(id='foo')\n self.site._setObject('foo', DummyFolder(id='foo'))\n self.site.foo._setObject('doc1', DummyContent(id='doc1'))\n self.site.portal_properties = DummyProperties(id='portal_properties')\n self.site.portal_properties.site_properties = \\\n DummyProperties(id='site_properties')", " def _makeOne(self, *args, **kw):\n from Products.CMFPlone.URLTool import URLTool\n url_tool = URLTool(*args, **kw)\n return url_tool.__of__(self.site)", " def test_isURLInPortal(self):\n url_tool = self._makeOne()\n iURLiP = url_tool.isURLInPortal\n self.assertTrue(iURLiP('http://www.foobar.com/bar/foo/folder'))\n self.assertTrue(iURLiP('http://www.foobar.com/bar/foo'))\n self.assertFalse(iURLiP('http://www.foobar.com/bar2/foo'))\n self.assertTrue(iURLiP('https://www.foobar.com/bar/foo/folder'))\n self.assertFalse(iURLiP('http://www.foobar.com:8080/bar/foo/folder'))\n self.assertFalse(iURLiP('http://www.foobar.com/bar'))\n self.assertFalse(iURLiP('/images'))\n self.assertTrue(iURLiP('/bar/foo/foo'))", " def test_isURLInPortalRelative(self):\n url_tool = self._makeOne()\n iURLiP = url_tool.isURLInPortal", " #non-root relative urls will need a current context to be passed in\n self.assertTrue(iURLiP('images/img1.jpg'))\n self.assertTrue(iURLiP('./images/img1.jpg'))", " # /bar/foo/something\n self.assertTrue(iURLiP('../something', self.site.foo.doc1))\n # /bar/afolder\n self.assertFalse(iURLiP('../../afolder', self.site.foo.doc1))\n # /afolder\n self.assertFalse(iURLiP('../../../afolder', self.site.foo.doc1))", " # /../afolder? How do we have more ../'s than there are parts in\n # the URL?\n self.assertFalse(iURLiP('../../../../afolder', self.site.foo.doc1))", " # /bar/foo/afolder\n self.assertTrue(iURLiP('../../foo/afolder', self.site.foo.doc1))", " def test_isURLInPortalExternal(self):\n url_tool = self._makeOne()\n iURLiP = url_tool.isURLInPortal\n self.assertTrue(iURLiP('http://external1'))\n self.assertTrue(iURLiP('http://external1/'))\n self.assertTrue(iURLiP('http://external1/something'))\n self.assertTrue(iURLiP('http://external2'))\n self.assertTrue(iURLiP('http://external2/'))\n self.assertTrue(iURLiP('http://external2/something'))\n self.assertTrue(iURLiP('http://external3/site'))\n self.assertTrue(iURLiP('http://external3/site/'))\n self.assertTrue(iURLiP('http://external3/site/something'))\n self.assertTrue(iURLiP('http://external4/site'))\n self.assertTrue(iURLiP('http://external4/site/'))\n self.assertTrue(iURLiP('http://external4/site/something'))", " self.assertFalse(iURLiP('http://external3/other'))\n self.assertFalse(iURLiP('http://external4/other'))\n self.assertFalse(iURLiP('http://external5'))\n self.assertFalse(iURLiP('http://external11'))", "" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
PreciseBugs
{"buggy_code_end_loc": [9, 32, 98], "buggy_code_start_loc": [9, 32, 98], "filenames": ["CHANGES.rst", "Products/CMFPlone/URLTool.py", "Products/CMFPlone/tests/testURLTool.py"], "fixing_code_end_loc": [13, 36, 112], "fixing_code_start_loc": [10, 33, 99], "message": "Cross-site scripting (XSS) vulnerability in Plone 3.3.0 through 3.3.6, 4.0.0 through 4.0.10, 4.1.0 through 4.1.6, 4.2.0 through 4.2.7, 4.3.x before 4.3.7, and 5.0rc1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:plone:plone:3.3:*:*:*:*:*:*:*", "matchCriteriaId": "FDC93803-6506-4382-A013-18010EE7E06B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.1:*:*:*:*:*:*:*", "matchCriteriaId": "E65977FD-A880-4D16-B56B-94A72774F42D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.2:*:*:*:*:*:*:*", "matchCriteriaId": "4EA5B4F8-2155-403D-97D8-1272285D508B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.3:*:*:*:*:*:*:*", "matchCriteriaId": "A3CA2943-77E5-4384-A019-415BBCE62F94", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.4:*:*:*:*:*:*:*", "matchCriteriaId": "B7FF63F6-F1DC-4A97-A2E6-11CF613A31E8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.5:*:*:*:*:*:*:*", "matchCriteriaId": "538A3519-5B04-4FE5-A3C0-FD26EFA32705", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.6:*:*:*:*:*:*:*", "matchCriteriaId": "858CBC5A-C241-475C-8125-C5EA351B12A7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0:*:*:*:*:*:*:*", "matchCriteriaId": "F3306D84-0F5B-46BA-9BCC-DCD0A1CDD604", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "E08F4534-A588-463F-A745-39E559AB1CB8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "B64341BA-5722-415E-9771-9837168AB7C0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "E2929227-AE19-428D-9AC3-D312A559039B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "3B6DC866-0FEE-475B-855C-A69E004810CD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "50BF3E8E-152C-4E89-BAA2-A952D10F4611", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.7:*:*:*:*:*:*:*", "matchCriteriaId": "F1F88BF6-9058-4CB8-A2D6-5653860CF489", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.8:*:*:*:*:*:*:*", "matchCriteriaId": "B2AA3FA2-15C3-444A-8810-5EF3E0E84D58", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.9:*:*:*:*:*:*:*", "matchCriteriaId": "72F3B15A-CD0F-4CC5-A76F-E62637B30E2E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.10:*:*:*:*:*:*:*", "matchCriteriaId": "D913FCA7-4DAE-4E9A-9146-9AFA8472B04B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1:*:*:*:*:*:*:*", "matchCriteriaId": "7C44B53B-953B-4522-A5B4-11573850D2CD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.1:*:*:*:*:*:*:*", "matchCriteriaId": "D8883023-113A-420A-97B6-A4A9B29CF7DB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.2:*:*:*:*:*:*:*", "matchCriteriaId": "4DF4D113-8D9D-4DA3-A177-64783352F608", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.3:*:*:*:*:*:*:*", "matchCriteriaId": "28F9B699-D1A4-425C-84ED-6A8FD29BE7F8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.4:*:*:*:*:*:*:*", "matchCriteriaId": "47321B60-67DA-4543-B173-D629A9569B45", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.5:*:*:*:*:*:*:*", "matchCriteriaId": "58B36EB2-723F-4E25-8018-EEB2BE806D9D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.6:*:*:*:*:*:*:*", "matchCriteriaId": "7962EF74-6AC1-424C-A202-163AFDADA971", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2:*:*:*:*:*:*:*", "matchCriteriaId": "1F1818BB-E23A-4136-898D-1D0C80C08728", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "5CB06627-133A-40D1-8816-E31E0A9BAD22", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "AE7E448A-2C0C-4DE0-89EA-904718CB6C6D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.3:*:*:*:*:*:*:*", "matchCriteriaId": "6E727C5C-9E54-49F7-B92C-2492069AAE08", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.4:*:*:*:*:*:*:*", "matchCriteriaId": "BFD68465-4CDC-4788-8932-41335B5C4AC8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.5:*:*:*:*:*:*:*", "matchCriteriaId": "A7B739E0-FB73-401C-AB1A-E3C1434AA2A3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.6:*:*:*:*:*:*:*", "matchCriteriaId": "DCC8B987-5173-4C61-8DE6-B70C18EE6FD3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.7:*:*:*:*:*:*:*", "matchCriteriaId": "38BA31E8-77EC-478B-BC6E-E2F145A8B9BD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3:*:*:*:*:*:*:*", "matchCriteriaId": "CE168A35-1A46-4A6F-8A08-25CDD886066D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.1:*:*:*:*:*:*:*", "matchCriteriaId": "CFE0FC06-369B-46CF-9B1E-BAF7AF87E950", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.2:*:*:*:*:*:*:*", "matchCriteriaId": "56571585-E9A2-4B78-B2B1-5D8EADED522A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.3:*:*:*:*:*:*:*", "matchCriteriaId": "2CDF8A15-401C-453E-8D09-8D4CDD4766DB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.4:*:*:*:*:*:*:*", "matchCriteriaId": "39B0B1CE-C0D9-495C-B4E7-E52A50BD6D97", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.5:*:*:*:*:*:*:*", "matchCriteriaId": "043B3CBE-DEA2-474D-AA57-1830A470B621", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.6:*:*:*:*:*:*:*", "matchCriteriaId": "08A6842B-B479-4D91-928A-1CCE1DCB936E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:5.0:rc1:*:*:*:*:*:*", "matchCriteriaId": "8AF9FB6C-134F-4653-8771-1BF46AB39344", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site scripting (XSS) vulnerability in Plone 3.3.0 through 3.3.6, 4.0.0 through 4.0.10, 4.1.0 through 4.1.6, 4.2.0 through 4.2.7, 4.3.x before 4.3.7, and 5.0rc1."}, {"lang": "es", "value": "Existe una vulnerabilidad de tipo Cross-Site Scripting (XSS) en Plone desde la versi\u00f3n 3.3.0 hasta la versi\u00f3n 3.3.6, desde la 4.0.0 hasta la 4.0.10, desde la 4.1.0 hasta la 4.1.6, desde la 4.2.0 hasta la 4.2.7, en las versiones 4.3.x anteriores a la 4.3.7 y 5.0rc1."}], "evaluatorComment": null, "id": "CVE-2015-7316", "lastModified": "2017-10-03T14:47:29.810", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-09-25T17:29:00.587", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2015/09/22/14"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1264788"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/plone/Products.CMFPlone/commit/3da710a2cd68587f0bf34f2e7ea1167d6eeee087"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://plone.org/security/hotfix/20150910/non-persistent-xss-in-plone"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/plone/Products.CMFPlone/commit/3da710a2cd68587f0bf34f2e7ea1167d6eeee087"}, "type": "CWE-79"}
203
Determine whether the {function_name} code is vulnerable or not.
[ "import unittest", "from Products.CMFCore.tests.base.dummy import DummySite\nfrom Products.CMFCore.tests.base.dummy import DummyFolder\nfrom Products.CMFCore.tests.base.dummy import DummyContent", "from Acquisition import aq_parent", "\nclass DummyFolder(DummyFolder):\n def absolute_url(self):\n return '/'.join([aq_parent(self).absolute_url(), self.getId()])", "\nclass DummyProperties(DummyContent):", " _allow_external_login_sites = [\n 'http://external1',\n 'http://external2/',\n 'http://external3/site',\n 'http://external4/site/'\n ]", " def getProperty(self, name, default=None):\n if name == 'allow_external_login_sites':\n return self._allow_external_login_sites\n return default", "\nclass TestURLTool(unittest.TestCase):", " def setUp(self):\n self.site = DummySite(id='foo')\n self.site._setObject('foo', DummyFolder(id='foo'))\n self.site.foo._setObject('doc1', DummyContent(id='doc1'))\n self.site.portal_properties = DummyProperties(id='portal_properties')\n self.site.portal_properties.site_properties = \\\n DummyProperties(id='site_properties')", " def _makeOne(self, *args, **kw):\n from Products.CMFPlone.URLTool import URLTool\n url_tool = URLTool(*args, **kw)\n return url_tool.__of__(self.site)", " def test_isURLInPortal(self):\n url_tool = self._makeOne()\n iURLiP = url_tool.isURLInPortal\n self.assertTrue(iURLiP('http://www.foobar.com/bar/foo/folder'))\n self.assertTrue(iURLiP('http://www.foobar.com/bar/foo'))\n self.assertFalse(iURLiP('http://www.foobar.com/bar2/foo'))\n self.assertTrue(iURLiP('https://www.foobar.com/bar/foo/folder'))\n self.assertFalse(iURLiP('http://www.foobar.com:8080/bar/foo/folder'))\n self.assertFalse(iURLiP('http://www.foobar.com/bar'))\n self.assertFalse(iURLiP('/images'))\n self.assertTrue(iURLiP('/bar/foo/foo'))", " def test_isURLInPortalRelative(self):\n url_tool = self._makeOne()\n iURLiP = url_tool.isURLInPortal", " #non-root relative urls will need a current context to be passed in\n self.assertTrue(iURLiP('images/img1.jpg'))\n self.assertTrue(iURLiP('./images/img1.jpg'))", " # /bar/foo/something\n self.assertTrue(iURLiP('../something', self.site.foo.doc1))\n # /bar/afolder\n self.assertFalse(iURLiP('../../afolder', self.site.foo.doc1))\n # /afolder\n self.assertFalse(iURLiP('../../../afolder', self.site.foo.doc1))", " # /../afolder? How do we have more ../'s than there are parts in\n # the URL?\n self.assertFalse(iURLiP('../../../../afolder', self.site.foo.doc1))", " # /bar/foo/afolder\n self.assertTrue(iURLiP('../../foo/afolder', self.site.foo.doc1))", " def test_isURLInPortalExternal(self):\n url_tool = self._makeOne()\n iURLiP = url_tool.isURLInPortal\n self.assertTrue(iURLiP('http://external1'))\n self.assertTrue(iURLiP('http://external1/'))\n self.assertTrue(iURLiP('http://external1/something'))\n self.assertTrue(iURLiP('http://external2'))\n self.assertTrue(iURLiP('http://external2/'))\n self.assertTrue(iURLiP('http://external2/something'))\n self.assertTrue(iURLiP('http://external3/site'))\n self.assertTrue(iURLiP('http://external3/site/'))\n self.assertTrue(iURLiP('http://external3/site/something'))\n self.assertTrue(iURLiP('http://external4/site'))\n self.assertTrue(iURLiP('http://external4/site/'))\n self.assertTrue(iURLiP('http://external4/site/something'))", " self.assertFalse(iURLiP('http://external3/other'))\n self.assertFalse(iURLiP('http://external4/other'))\n self.assertFalse(iURLiP('http://external5'))\n self.assertFalse(iURLiP('http://external11'))", "\n def test_script_tag_url_not_in_portal(self):\n url_tool = self._makeOne()\n iURLiP = url_tool.isURLInPortal\n self.assertFalse(iURLiP('<script>alert(\"hi\");</script>'))\n self.assertFalse(\n iURLiP('%3Cscript%3Ealert(%22hi%22)%3B%3C%2Fscript%3E'))", " def test_inline_url_not_in_portal(self):\n url_tool = self._makeOne()\n iURLiP = url_tool.isURLInPortal\n self.assertFalse(iURLiP('javascript%3Aalert(3)'))\n self.assertFalse(iURLiP('javascript:alert(3)'))" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [9, 32, 98], "buggy_code_start_loc": [9, 32, 98], "filenames": ["CHANGES.rst", "Products/CMFPlone/URLTool.py", "Products/CMFPlone/tests/testURLTool.py"], "fixing_code_end_loc": [13, 36, 112], "fixing_code_start_loc": [10, 33, 99], "message": "Cross-site scripting (XSS) vulnerability in Plone 3.3.0 through 3.3.6, 4.0.0 through 4.0.10, 4.1.0 through 4.1.6, 4.2.0 through 4.2.7, 4.3.x before 4.3.7, and 5.0rc1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:plone:plone:3.3:*:*:*:*:*:*:*", "matchCriteriaId": "FDC93803-6506-4382-A013-18010EE7E06B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.1:*:*:*:*:*:*:*", "matchCriteriaId": "E65977FD-A880-4D16-B56B-94A72774F42D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.2:*:*:*:*:*:*:*", "matchCriteriaId": "4EA5B4F8-2155-403D-97D8-1272285D508B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.3:*:*:*:*:*:*:*", "matchCriteriaId": "A3CA2943-77E5-4384-A019-415BBCE62F94", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.4:*:*:*:*:*:*:*", "matchCriteriaId": "B7FF63F6-F1DC-4A97-A2E6-11CF613A31E8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.5:*:*:*:*:*:*:*", "matchCriteriaId": "538A3519-5B04-4FE5-A3C0-FD26EFA32705", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:3.3.6:*:*:*:*:*:*:*", "matchCriteriaId": "858CBC5A-C241-475C-8125-C5EA351B12A7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0:*:*:*:*:*:*:*", "matchCriteriaId": "F3306D84-0F5B-46BA-9BCC-DCD0A1CDD604", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "E08F4534-A588-463F-A745-39E559AB1CB8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "B64341BA-5722-415E-9771-9837168AB7C0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "E2929227-AE19-428D-9AC3-D312A559039B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "3B6DC866-0FEE-475B-855C-A69E004810CD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "50BF3E8E-152C-4E89-BAA2-A952D10F4611", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.7:*:*:*:*:*:*:*", "matchCriteriaId": "F1F88BF6-9058-4CB8-A2D6-5653860CF489", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.8:*:*:*:*:*:*:*", "matchCriteriaId": "B2AA3FA2-15C3-444A-8810-5EF3E0E84D58", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.9:*:*:*:*:*:*:*", "matchCriteriaId": "72F3B15A-CD0F-4CC5-A76F-E62637B30E2E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.0.10:*:*:*:*:*:*:*", "matchCriteriaId": "D913FCA7-4DAE-4E9A-9146-9AFA8472B04B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1:*:*:*:*:*:*:*", "matchCriteriaId": "7C44B53B-953B-4522-A5B4-11573850D2CD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.1:*:*:*:*:*:*:*", "matchCriteriaId": "D8883023-113A-420A-97B6-A4A9B29CF7DB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.2:*:*:*:*:*:*:*", "matchCriteriaId": "4DF4D113-8D9D-4DA3-A177-64783352F608", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.3:*:*:*:*:*:*:*", "matchCriteriaId": "28F9B699-D1A4-425C-84ED-6A8FD29BE7F8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.4:*:*:*:*:*:*:*", "matchCriteriaId": "47321B60-67DA-4543-B173-D629A9569B45", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.5:*:*:*:*:*:*:*", "matchCriteriaId": "58B36EB2-723F-4E25-8018-EEB2BE806D9D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.1.6:*:*:*:*:*:*:*", "matchCriteriaId": "7962EF74-6AC1-424C-A202-163AFDADA971", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2:*:*:*:*:*:*:*", "matchCriteriaId": "1F1818BB-E23A-4136-898D-1D0C80C08728", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "5CB06627-133A-40D1-8816-E31E0A9BAD22", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "AE7E448A-2C0C-4DE0-89EA-904718CB6C6D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.3:*:*:*:*:*:*:*", "matchCriteriaId": "6E727C5C-9E54-49F7-B92C-2492069AAE08", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.4:*:*:*:*:*:*:*", "matchCriteriaId": "BFD68465-4CDC-4788-8932-41335B5C4AC8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.5:*:*:*:*:*:*:*", "matchCriteriaId": "A7B739E0-FB73-401C-AB1A-E3C1434AA2A3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.6:*:*:*:*:*:*:*", "matchCriteriaId": "DCC8B987-5173-4C61-8DE6-B70C18EE6FD3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.2.7:*:*:*:*:*:*:*", "matchCriteriaId": "38BA31E8-77EC-478B-BC6E-E2F145A8B9BD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3:*:*:*:*:*:*:*", "matchCriteriaId": "CE168A35-1A46-4A6F-8A08-25CDD886066D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.1:*:*:*:*:*:*:*", "matchCriteriaId": "CFE0FC06-369B-46CF-9B1E-BAF7AF87E950", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.2:*:*:*:*:*:*:*", "matchCriteriaId": "56571585-E9A2-4B78-B2B1-5D8EADED522A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.3:*:*:*:*:*:*:*", "matchCriteriaId": "2CDF8A15-401C-453E-8D09-8D4CDD4766DB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.4:*:*:*:*:*:*:*", "matchCriteriaId": "39B0B1CE-C0D9-495C-B4E7-E52A50BD6D97", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.5:*:*:*:*:*:*:*", "matchCriteriaId": "043B3CBE-DEA2-474D-AA57-1830A470B621", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:4.3.6:*:*:*:*:*:*:*", "matchCriteriaId": "08A6842B-B479-4D91-928A-1CCE1DCB936E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:plone:plone:5.0:rc1:*:*:*:*:*:*", "matchCriteriaId": "8AF9FB6C-134F-4653-8771-1BF46AB39344", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site scripting (XSS) vulnerability in Plone 3.3.0 through 3.3.6, 4.0.0 through 4.0.10, 4.1.0 through 4.1.6, 4.2.0 through 4.2.7, 4.3.x before 4.3.7, and 5.0rc1."}, {"lang": "es", "value": "Existe una vulnerabilidad de tipo Cross-Site Scripting (XSS) en Plone desde la versi\u00f3n 3.3.0 hasta la versi\u00f3n 3.3.6, desde la 4.0.0 hasta la 4.0.10, desde la 4.1.0 hasta la 4.1.6, desde la 4.2.0 hasta la 4.2.7, en las versiones 4.3.x anteriores a la 4.3.7 y 5.0rc1."}], "evaluatorComment": null, "id": "CVE-2015-7316", "lastModified": "2017-10-03T14:47:29.810", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-09-25T17:29:00.587", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2015/09/22/14"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1264788"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/plone/Products.CMFPlone/commit/3da710a2cd68587f0bf34f2e7ea1167d6eeee087"}, {"source": "cve@mitre.org", "tags": ["Vendor Advisory"], "url": "https://plone.org/security/hotfix/20150910/non-persistent-xss-in-plone"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/plone/Products.CMFPlone/commit/3da710a2cd68587f0bf34f2e7ea1167d6eeee087"}, "type": "CWE-79"}
203
Determine whether the {function_name} code is vulnerable or not.
[ "/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.", "Licensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at", " http://www.apache.org/licenses/LICENSE-2.0", "Unless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/", "#include \"tensorflow/core/framework/op_requires.h\"\n#define EIGEN_USE_THREADS", "#if (defined(GOOGLE_CUDA) && GOOGLE_CUDA) || \\\n (defined(TENSORFLOW_USE_ROCM) && TENSORFLOW_USE_ROCM)\n#define EIGEN_USE_GPU\n#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "#include \"tensorflow/core/kernels/quantize_and_dequantize_op.h\"", "#include \"tensorflow/core/framework/op.h\"\n#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/register_types.h\"\n#include \"tensorflow/core/framework/type_traits.h\"\n#include \"tensorflow/core/framework/types.h\"\n#include \"tensorflow/core/lib/core/errors.h\"", "namespace tensorflow {", "typedef Eigen::ThreadPoolDevice CPUDevice;\ntypedef Eigen::GpuDevice GPUDevice;", "// Simulate quantization precision loss in a float tensor by:\n// 1. Quantize the tensor to fixed point numbers, which should match the target\n// quantization method when it is used in inference.\n// 2. Dequantize it back to floating point numbers for the following ops, most\n// likely matmul.\ntemplate <typename Device, typename T>\nclass QuantizeAndDequantizeV2Op : public OpKernel {\n public:\n explicit QuantizeAndDequantizeV2Op(OpKernelConstruction* ctx)\n : OpKernel(ctx) {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"signed_input\", &signed_input_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"axis\", &axis_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"num_bits\", &num_bits_));\n OP_REQUIRES(ctx, num_bits_ > 0 && num_bits_ < (signed_input_ ? 62 : 63),\n errors::InvalidArgument(\"num_bits is out of range: \", num_bits_,\n \" with signed_input_ \", signed_input_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"range_given\", &range_given_));", " string round_mode_string;\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"round_mode\", &round_mode_string));\n OP_REQUIRES(\n ctx,\n (round_mode_string == \"HALF_UP\" || round_mode_string == \"HALF_TO_EVEN\"),\n errors::InvalidArgument(\"Round mode string must be \"\n \"'HALF_UP' or \"\n \"'HALF_TO_EVEN', is '\" +\n round_mode_string + \"'\"));\n if (round_mode_string == \"HALF_UP\") {\n round_mode_ = ROUND_HALF_UP;\n } else if (round_mode_string == \"HALF_TO_EVEN\") {\n round_mode_ = ROUND_HALF_TO_EVEN;\n }\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"narrow_range\", &narrow_range_));\n }", " void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);\n OP_REQUIRES(\n ctx, axis_ >= -1,\n errors::InvalidArgument(\"Axis must be at least -1. Found \", axis_));\n OP_REQUIRES(\n ctx, (axis_ == -1 || axis_ < input.shape().dims()),\n errors::InvalidArgument(\"Shape must be at least rank \", axis_ + 1,\n \" but is rank \", input.shape().dims()));\n const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_);\n Tensor input_min_tensor;\n Tensor input_max_tensor;\n Tensor* output = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));\n if (range_given_) {\n input_min_tensor = ctx->input(1);\n input_max_tensor = ctx->input(2);\n if (axis_ == -1) {\n auto min_val = input_min_tensor.scalar<T>()();\n auto max_val = input_max_tensor.scalar<T>()();\n OP_REQUIRES(ctx, min_val <= max_val,\n errors::InvalidArgument(\"Invalid range: input_min \",\n min_val, \" > input_max \", max_val));\n } else {\n OP_REQUIRES(ctx, input_min_tensor.dim_size(0) == depth,\n errors::InvalidArgument(\n \"input_min_tensor has incorrect size, was \",\n input_min_tensor.dim_size(0), \" expected \", depth,\n \" to match dim \", axis_, \" of the input \",\n input_min_tensor.shape()));\n OP_REQUIRES(ctx, input_max_tensor.dim_size(0) == depth,\n errors::InvalidArgument(\n \"input_max_tensor has incorrect size, was \",\n input_max_tensor.dim_size(0), \" expected \", depth,\n \" to match dim \", axis_, \" of the input \",\n input_max_tensor.shape()));\n }\n } else {\n auto range_shape = (axis_ == -1) ? TensorShape({}) : TensorShape({depth});\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,\n range_shape, &input_min_tensor));\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,\n range_shape, &input_max_tensor));\n }", " if (axis_ == -1) {\n functor::QuantizeAndDequantizeOneScaleFunctor<Device, T> f;\n f(ctx->eigen_device<Device>(), input.flat<T>(), signed_input_, num_bits_,\n range_given_, &input_min_tensor, &input_max_tensor, round_mode_,\n narrow_range_, output->flat<T>());\n } else {\n functor::QuantizeAndDequantizePerChannelFunctor<Device, T> f;\n f(ctx->eigen_device<Device>(),\n input.template flat_inner_outer_dims<T, 3>(axis_ - 1), signed_input_,\n num_bits_, range_given_, &input_min_tensor, &input_max_tensor,\n round_mode_, narrow_range_,\n output->template flat_inner_outer_dims<T, 3>(axis_ - 1));\n }\n }", " private:\n int num_bits_;\n int axis_;\n QuantizerRoundMode round_mode_;\n bool signed_input_;\n bool range_given_;\n bool narrow_range_;\n};", "// Implementation of QuantizeAndDequantizeV4GradientOp.\n// When back-propagating the error through a quantized layer, the following\n// paper gives evidence that clipped-ReLU is better than non-clipped:\n// \"Deep Learning with Low Precision by Half-wave Gaussian Quantization\"\n// http://zpascal.net/cvpr2017/Cai_Deep_Learning_With_CVPR_2017_paper.pdf\ntemplate <typename Device, typename T>\nclass QuantizeAndDequantizeV4GradientOp : public OpKernel {\n public:\n explicit QuantizeAndDequantizeV4GradientOp(OpKernelConstruction* ctx)\n : OpKernel::OpKernel(ctx) {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"axis\", &axis_));\n }", " void Compute(OpKernelContext* ctx) override {\n const Tensor& gradient = ctx->input(0);\n const Tensor& input = ctx->input(1);\n Tensor* input_backprop = nullptr;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(0, input.shape(), &input_backprop));", "", "\n OP_REQUIRES(\n ctx, input.IsSameSize(gradient),\n errors::InvalidArgument(\"gradient and input must be the same size\"));\n const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_);\n const Tensor& input_min_tensor = ctx->input(2);\n OP_REQUIRES(ctx,\n input_min_tensor.dims() == 0 || input_min_tensor.dims() == 1,\n errors::InvalidArgument(\n \"Input min tensor must have dimension 1. Recieved \",\n input_min_tensor.dims(), \".\"));\n const Tensor& input_max_tensor = ctx->input(3);\n OP_REQUIRES(ctx,\n input_max_tensor.dims() == 0 || input_max_tensor.dims() == 1,\n errors::InvalidArgument(\n \"Input max tensor must have dimension 1. Recieved \",\n input_max_tensor.dims(), \".\"));\n if (axis_ != -1) {\n OP_REQUIRES(\n ctx, input_min_tensor.dim_size(0) == depth,\n errors::InvalidArgument(\"min has incorrect size, expected \", depth,\n \" was \", input_min_tensor.dim_size(0)));\n OP_REQUIRES(\n ctx, input_max_tensor.dim_size(0) == depth,\n errors::InvalidArgument(\"max has incorrect size, expected \", depth,\n \" was \", input_max_tensor.dim_size(0)));\n }", " TensorShape min_max_shape(input_min_tensor.shape());\n Tensor* input_min_backprop;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(1, min_max_shape, &input_min_backprop));", " Tensor* input_max_backprop;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(2, min_max_shape, &input_max_backprop));", " if (axis_ == -1) {\n functor::QuantizeAndDequantizeOneScaleGradientFunctor<Device, T> f;\n f(ctx->eigen_device<Device>(), gradient.template flat<T>(),\n input.template flat<T>(), input_min_tensor.scalar<T>(),\n input_max_tensor.scalar<T>(), input_backprop->template flat<T>(),\n input_min_backprop->template scalar<T>(),\n input_max_backprop->template scalar<T>());\n } else {\n functor::QuantizeAndDequantizePerChannelGradientFunctor<Device, T> f;\n f(ctx->eigen_device<Device>(),\n gradient.template flat_inner_outer_dims<T, 3>(axis_ - 1),\n input.template flat_inner_outer_dims<T, 3>(axis_ - 1),\n &input_min_tensor, &input_max_tensor,\n input_backprop->template flat_inner_outer_dims<T, 3>(axis_ - 1),\n input_min_backprop->template flat<T>(),\n input_max_backprop->template flat<T>());\n }\n }", " private:\n int axis_;\n};", "// Simulate quantization precision loss in a float tensor by:\n// 1. Quantize the tensor to fixed point numbers, which should match the target\n// quantization method when it is used in inference.\n// 2. Dequantize it back to floating point numbers for the following ops, most\n// likely matmul.\n// Almost identical to QuantizeAndDequantizeV2Op, except that num_bits is a\n// tensor.\ntemplate <typename Device, typename T>\nclass QuantizeAndDequantizeV3Op : public OpKernel {\n public:\n explicit QuantizeAndDequantizeV3Op(OpKernelConstruction* ctx)\n : OpKernel(ctx) {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"signed_input\", &signed_input_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"range_given\", &range_given_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"narrow_range\", &narrow_range_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"axis\", &axis_));\n }", " void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);\n OP_REQUIRES(ctx, axis_ < input.dims(),\n errors::InvalidArgument(\n \"Axis requested is larger than input dimensions. Axis: \",\n axis_, \" Input Dimensions: \", input.dims()));\n const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_);\n Tensor* output = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));", " Tensor num_bits_tensor;\n num_bits_tensor = ctx->input(3);\n int num_bits_val = num_bits_tensor.scalar<int32>()();", " OP_REQUIRES(\n ctx, num_bits_val > 0 && num_bits_val < (signed_input_ ? 62 : 63),\n errors::InvalidArgument(\"num_bits is out of range: \", num_bits_val,\n \" with signed_input_ \", signed_input_));", " Tensor input_min_tensor;\n Tensor input_max_tensor;\n if (range_given_) {\n input_min_tensor = ctx->input(1);\n input_max_tensor = ctx->input(2);\n if (axis_ == -1) {\n auto min_val = input_min_tensor.scalar<T>()();\n auto max_val = input_max_tensor.scalar<T>()();\n OP_REQUIRES(ctx, min_val <= max_val,\n errors::InvalidArgument(\"Invalid range: input_min \",\n min_val, \" > input_max \", max_val));\n } else {\n OP_REQUIRES(ctx, input_min_tensor.dim_size(0) == depth,\n errors::InvalidArgument(\n \"input_min_tensor has incorrect size, was \",\n input_min_tensor.dim_size(0), \" expected \", depth,\n \" to match dim \", axis_, \" of the input \",\n input_min_tensor.shape()));\n OP_REQUIRES(ctx, input_max_tensor.dim_size(0) == depth,\n errors::InvalidArgument(\n \"input_max_tensor has incorrect size, was \",\n input_max_tensor.dim_size(0), \" expected \", depth,\n \" to match dim \", axis_, \" of the input \",\n input_max_tensor.shape()));\n }\n } else {\n auto range_shape = (axis_ == -1) ? TensorShape({}) : TensorShape({depth});\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,\n range_shape, &input_min_tensor));\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,\n range_shape, &input_max_tensor));\n }", " if (axis_ == -1) {\n functor::QuantizeAndDequantizeOneScaleFunctor<Device, T> f;\n f(ctx->eigen_device<Device>(), input.flat<T>(), signed_input_,\n num_bits_val, range_given_, &input_min_tensor, &input_max_tensor,\n ROUND_HALF_TO_EVEN, narrow_range_, output->flat<T>());\n } else {\n functor::QuantizeAndDequantizePerChannelFunctor<Device, T> f;\n f(ctx->eigen_device<Device>(),\n input.template flat_inner_outer_dims<T, 3>(axis_ - 1), signed_input_,\n num_bits_val, range_given_, &input_min_tensor, &input_max_tensor,\n ROUND_HALF_TO_EVEN, narrow_range_,\n output->template flat_inner_outer_dims<T, 3>(axis_ - 1));\n }\n }", " private:\n int axis_;\n bool signed_input_;\n bool range_given_;\n bool narrow_range_;\n};", "// DEPRECATED: Use QuantizeAndDequantizeV2Op.\ntemplate <typename Device, typename T>\nclass QuantizeAndDequantizeOp : public OpKernel {\n public:\n explicit QuantizeAndDequantizeOp(OpKernelConstruction* ctx) : OpKernel(ctx) {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"signed_input\", &signed_input_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"num_bits\", &num_bits_));\n OP_REQUIRES(ctx, num_bits_ > 0 && num_bits_ < (signed_input_ ? 62 : 63),\n errors::InvalidArgument(\"num_bits is out of range: \", num_bits_,\n \" with signed_input_ \", signed_input_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"range_given\", &range_given_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"input_min\", &input_min_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"input_max\", &input_max_));\n if (range_given_) {\n OP_REQUIRES(\n ctx, input_min_ <= input_max_,\n errors::InvalidArgument(\"Invalid range: input_min \", input_min_,\n \" > input_max \", input_max_));\n }\n }", " void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);", " Tensor* output = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));", " // One global scale.\n Tensor input_min_tensor(DataTypeToEnum<T>::value, TensorShape());\n Tensor input_max_tensor(DataTypeToEnum<T>::value, TensorShape());\n // Initialize the tensors with the values in the Attrs.\n input_min_tensor.template scalar<T>()() = static_cast<T>(input_min_);\n input_max_tensor.template scalar<T>()() = static_cast<T>(input_max_);", " functor::QuantizeAndDequantizeOneScaleFunctor<Device, T> functor;\n functor(ctx->eigen_device<Device>(), input.flat<T>(), signed_input_,\n num_bits_, range_given_, &input_min_tensor, &input_max_tensor,\n ROUND_HALF_TO_EVEN, /*narrow_range=*/false, output->flat<T>());\n }", " private:\n bool signed_input_;\n int num_bits_;\n bool range_given_;\n float input_min_;\n float input_max_;\n};", "// Specializations for CPUDevice.", "namespace functor {\ntemplate <typename T>\nstruct QuantizeAndDequantizeOneScaleFunctor<CPUDevice, T> {\n void operator()(const CPUDevice& d, typename TTypes<T>::ConstVec input,\n const bool signed_input, const int num_bits,\n const bool range_given, Tensor* input_min_tensor,\n Tensor* input_max_tensor, QuantizerRoundMode round_mode,\n bool narrow_range, typename TTypes<T>::Vec out) {\n QuantizeAndDequantizeOneScaleImpl<CPUDevice, T>::Compute(\n d, input, signed_input, num_bits, range_given, input_min_tensor,\n input_max_tensor, round_mode, narrow_range, out);\n }\n};", "template <typename T>\nstruct QuantizeAndDequantizePerChannelFunctor<CPUDevice, T> {\n void operator()(const CPUDevice& d, typename TTypes<T, 3>::ConstTensor input,\n bool signed_input, int num_bits, bool range_given,\n Tensor* input_min_tensor, Tensor* input_max_tensor,\n QuantizerRoundMode round_mode, bool narrow_range,\n typename TTypes<T, 3>::Tensor out) {\n QuantizeAndDequantizePerChannelImpl<CPUDevice, T>::Compute(\n d, input, signed_input, num_bits, range_given, input_min_tensor,\n input_max_tensor, round_mode, narrow_range, out);\n }\n};", "template <typename T>\nstruct QuantizeAndDequantizeOneScaleGradientFunctor<CPUDevice, T> {\n void operator()(const CPUDevice& d, typename TTypes<T>::ConstFlat gradient,\n typename TTypes<T>::ConstFlat input,\n typename TTypes<T>::ConstScalar input_min_tensor,\n typename TTypes<T>::ConstScalar input_max_tensor,\n typename TTypes<T>::Flat input_backprop,\n typename TTypes<T>::Scalar input_min_backprop,\n typename TTypes<T>::Scalar input_max_backprop) {\n QuantizeAndDequantizeOneScaleGradientImpl<CPUDevice, T>::Compute(\n d, gradient, input, input_min_tensor, input_max_tensor, input_backprop,\n input_min_backprop, input_max_backprop);\n }\n};", "template <typename T>\nstruct QuantizeAndDequantizePerChannelGradientFunctor<CPUDevice, T> {\n void operator()(const CPUDevice& d,\n typename TTypes<T, 3>::ConstTensor gradient,\n typename TTypes<T, 3>::ConstTensor input,\n const Tensor* input_min_tensor,\n const Tensor* input_max_tensor,\n typename TTypes<T, 3>::Tensor input_backprop,\n typename TTypes<T>::Flat input_min_backprop,\n typename TTypes<T>::Flat input_max_backprop) {\n QuantizeAndDequantizePerChannelGradientImpl<CPUDevice, T>::Compute(\n d, gradient, input, input_min_tensor, input_max_tensor, input_backprop,\n input_min_backprop, input_max_backprop);\n }\n};", "template struct functor::QuantizeAndDequantizeOneScaleGradientFunctor<CPUDevice,\n float>;\ntemplate struct functor::QuantizeAndDequantizePerChannelGradientFunctor<\n CPUDevice, double>;", "} // namespace functor", "#define REGISTER_CPU_KERNEL(T) \\\n REGISTER_KERNEL_BUILDER(Name(\"QuantizeAndDequantizeV2\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<T>(\"T\"), \\\n QuantizeAndDequantizeV2Op<CPUDevice, T>); \\\n REGISTER_KERNEL_BUILDER(Name(\"QuantizeAndDequantizeV3\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<T>(\"T\"), \\\n QuantizeAndDequantizeV3Op<CPUDevice, T>); \\\n REGISTER_KERNEL_BUILDER(Name(\"QuantizeAndDequantizeV4\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<T>(\"T\"), \\\n QuantizeAndDequantizeV2Op<CPUDevice, T>); \\\n REGISTER_KERNEL_BUILDER(Name(\"QuantizeAndDequantizeV4Grad\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<T>(\"T\"), \\\n QuantizeAndDequantizeV4GradientOp<CPUDevice, T>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"QuantizeAndDequantize\").Device(DEVICE_CPU).TypeConstraint<T>(\"T\"), \\\n QuantizeAndDequantizeOp<CPUDevice, T>);\nTF_CALL_float(REGISTER_CPU_KERNEL);\nTF_CALL_double(REGISTER_CPU_KERNEL);\n#undef REGISTER_CPU_KERNEL", "#if (defined(GOOGLE_CUDA) && GOOGLE_CUDA) || \\\n (defined(TENSORFLOW_USE_ROCM) && TENSORFLOW_USE_ROCM)\n#define REGISTER_GPU_KERNEL(T) \\\n REGISTER_KERNEL_BUILDER(Name(\"QuantizeAndDequantizeV2\") \\\n .Device(DEVICE_GPU) \\\n .HostMemory(\"input_min\") \\\n .HostMemory(\"input_max\") \\\n .TypeConstraint<T>(\"T\"), \\\n QuantizeAndDequantizeV2Op<GPUDevice, T>); \\\n REGISTER_KERNEL_BUILDER(Name(\"QuantizeAndDequantizeV3\") \\\n .Device(DEVICE_GPU) \\\n .HostMemory(\"input_min\") \\\n .HostMemory(\"input_max\") \\\n .HostMemory(\"num_bits\") \\\n .TypeConstraint<T>(\"T\"), \\\n QuantizeAndDequantizeV3Op<GPUDevice, T>); \\\n REGISTER_KERNEL_BUILDER(Name(\"QuantizeAndDequantizeV4\") \\\n .Device(DEVICE_GPU) \\\n .HostMemory(\"input_min\") \\\n .HostMemory(\"input_max\") \\\n .TypeConstraint<T>(\"T\"), \\\n QuantizeAndDequantizeV2Op<GPUDevice, T>); \\\n REGISTER_KERNEL_BUILDER(Name(\"QuantizeAndDequantizeV4Grad\") \\\n .Device(DEVICE_GPU) \\\n .HostMemory(\"input_min\") \\\n .HostMemory(\"input_max\") \\\n .TypeConstraint<T>(\"T\"), \\\n QuantizeAndDequantizeV4GradientOp<GPUDevice, T>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"QuantizeAndDequantize\").Device(DEVICE_GPU).TypeConstraint<T>(\"T\"), \\\n QuantizeAndDequantizeOp<GPUDevice, T>);\nTF_CALL_float(REGISTER_GPU_KERNEL);\nTF_CALL_double(REGISTER_GPU_KERNEL);\n#undef REGISTER_GPU_KERNEL\n#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM\n} // namespace tensorflow" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [160], "buggy_code_start_loc": [160], "filenames": ["tensorflow/core/kernels/quantize_and_dequantize_op.cc"], "fixing_code_end_loc": [168], "fixing_code_start_loc": [161], "message": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions the implementation of `tf.raw_ops.QuantizeAndDequantizeV4Grad` is vulnerable to an integer overflow issue caused by converting a signed integer value to an unsigned one and then allocating memory based on this value. The [implementation](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/quantize_and_dequantize_op.cc#L126) uses the `axis` value as the size argument to `absl::InlinedVector` constructor. But, the constructor uses an unsigned type for the argument, so the implicit conversion transforms the negative value to a large integer. We have patched the issue in GitHub commit 96f364a1ca3009f98980021c4b32be5fdcca33a1. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, and TensorFlow 2.4.3, as these are also affected and still in supported range.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "0F83C081-51CC-415F-A8C0-0A44C75E2CD6", "versionEndExcluding": "2.3.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.3.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "BD3F2BF8-EBA9-42BF-8F9B-D918B880B15A", "versionEndExcluding": "2.4.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "D03E99A7-4E3D-427D-A156-C0713E9FB02A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.6.0:rc0:*:*:*:*:*:*", "matchCriteriaId": "70FA6E48-6C57-40CA-809F-4E3D07CBF348", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.6.0:rc1:*:*:*:*:*:*", "matchCriteriaId": "42187561-E491-434D-828C-F36701446634", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.6.0:rc2:*:*:*:*:*:*", "matchCriteriaId": "C66B61C8-450A-4C5E-9174-F970D6DEE778", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions the implementation of `tf.raw_ops.QuantizeAndDequantizeV4Grad` is vulnerable to an integer overflow issue caused by converting a signed integer value to an unsigned one and then allocating memory based on this value. The [implementation](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/quantize_and_dequantize_op.cc#L126) uses the `axis` value as the size argument to `absl::InlinedVector` constructor. But, the constructor uses an unsigned type for the argument, so the implicit conversion transforms the negative value to a large integer. We have patched the issue in GitHub commit 96f364a1ca3009f98980021c4b32be5fdcca33a1. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, and TensorFlow 2.4.3, as these are also affected and still in supported range."}, {"lang": "es", "value": "TensorFlow es una plataforma de c\u00f3digo abierto de extremo a extremo para el aprendizaje autom\u00e1tico. En las versiones afectadas, la implementaci\u00f3n \"tf.raw_ops.QuantizeAndDequantizeV4Grad\" es vulnerable a un problema de desbordamiento de enteros causado al convertir un valor entero con signo a uno sin signo y la posterior asignaci\u00f3n de memoria basada en este valor. La [implementaci\u00f3n](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/quantize_and_dequantize_op.cc#L126) usa el valor de \"axis\" como argumento del tama\u00f1o del constructor de \"absl::InlinedVector\". Pero, el constructor usa un tipo sin signo para el argumento, por lo que la conversi\u00f3n impl\u00edcita transforma el valor negativo en un entero grande. Hemos parcheado el problema en el commit 96f364a1ca3009f98980021c4b32be5fdcca33a1 de GitHub. La correcci\u00f3n ser\u00e1 incluida en TensorFlow versi\u00f3n 2.6.0. Tambi\u00e9n seleccionaremos este commit en TensorFlow 2.5.1, y TensorFlow 2.4.3, ya que estos tambi\u00e9n est\u00e1n afectados y todav\u00eda en el rango de soporte."}], "evaluatorComment": null, "id": "CVE-2021-37645", "lastModified": "2021-08-18T15:38:52.563", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 2.1, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-08-12T21:15:07.887", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/commit/96f364a1ca3009f98980021c4b32be5fdcca33a1"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/security/advisories/GHSA-9w2p-5mgw-p94c"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-681"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/tensorflow/tensorflow/commit/96f364a1ca3009f98980021c4b32be5fdcca33a1"}, "type": "CWE-681"}
204
Determine whether the {function_name} code is vulnerable or not.
[ "/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.", "Licensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at", " http://www.apache.org/licenses/LICENSE-2.0", "Unless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/", "#include \"tensorflow/core/framework/op_requires.h\"\n#define EIGEN_USE_THREADS", "#if (defined(GOOGLE_CUDA) && GOOGLE_CUDA) || \\\n (defined(TENSORFLOW_USE_ROCM) && TENSORFLOW_USE_ROCM)\n#define EIGEN_USE_GPU\n#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM", "#include \"tensorflow/core/kernels/quantize_and_dequantize_op.h\"", "#include \"tensorflow/core/framework/op.h\"\n#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/register_types.h\"\n#include \"tensorflow/core/framework/type_traits.h\"\n#include \"tensorflow/core/framework/types.h\"\n#include \"tensorflow/core/lib/core/errors.h\"", "namespace tensorflow {", "typedef Eigen::ThreadPoolDevice CPUDevice;\ntypedef Eigen::GpuDevice GPUDevice;", "// Simulate quantization precision loss in a float tensor by:\n// 1. Quantize the tensor to fixed point numbers, which should match the target\n// quantization method when it is used in inference.\n// 2. Dequantize it back to floating point numbers for the following ops, most\n// likely matmul.\ntemplate <typename Device, typename T>\nclass QuantizeAndDequantizeV2Op : public OpKernel {\n public:\n explicit QuantizeAndDequantizeV2Op(OpKernelConstruction* ctx)\n : OpKernel(ctx) {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"signed_input\", &signed_input_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"axis\", &axis_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"num_bits\", &num_bits_));\n OP_REQUIRES(ctx, num_bits_ > 0 && num_bits_ < (signed_input_ ? 62 : 63),\n errors::InvalidArgument(\"num_bits is out of range: \", num_bits_,\n \" with signed_input_ \", signed_input_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"range_given\", &range_given_));", " string round_mode_string;\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"round_mode\", &round_mode_string));\n OP_REQUIRES(\n ctx,\n (round_mode_string == \"HALF_UP\" || round_mode_string == \"HALF_TO_EVEN\"),\n errors::InvalidArgument(\"Round mode string must be \"\n \"'HALF_UP' or \"\n \"'HALF_TO_EVEN', is '\" +\n round_mode_string + \"'\"));\n if (round_mode_string == \"HALF_UP\") {\n round_mode_ = ROUND_HALF_UP;\n } else if (round_mode_string == \"HALF_TO_EVEN\") {\n round_mode_ = ROUND_HALF_TO_EVEN;\n }\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"narrow_range\", &narrow_range_));\n }", " void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);\n OP_REQUIRES(\n ctx, axis_ >= -1,\n errors::InvalidArgument(\"Axis must be at least -1. Found \", axis_));\n OP_REQUIRES(\n ctx, (axis_ == -1 || axis_ < input.shape().dims()),\n errors::InvalidArgument(\"Shape must be at least rank \", axis_ + 1,\n \" but is rank \", input.shape().dims()));\n const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_);\n Tensor input_min_tensor;\n Tensor input_max_tensor;\n Tensor* output = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));\n if (range_given_) {\n input_min_tensor = ctx->input(1);\n input_max_tensor = ctx->input(2);\n if (axis_ == -1) {\n auto min_val = input_min_tensor.scalar<T>()();\n auto max_val = input_max_tensor.scalar<T>()();\n OP_REQUIRES(ctx, min_val <= max_val,\n errors::InvalidArgument(\"Invalid range: input_min \",\n min_val, \" > input_max \", max_val));\n } else {\n OP_REQUIRES(ctx, input_min_tensor.dim_size(0) == depth,\n errors::InvalidArgument(\n \"input_min_tensor has incorrect size, was \",\n input_min_tensor.dim_size(0), \" expected \", depth,\n \" to match dim \", axis_, \" of the input \",\n input_min_tensor.shape()));\n OP_REQUIRES(ctx, input_max_tensor.dim_size(0) == depth,\n errors::InvalidArgument(\n \"input_max_tensor has incorrect size, was \",\n input_max_tensor.dim_size(0), \" expected \", depth,\n \" to match dim \", axis_, \" of the input \",\n input_max_tensor.shape()));\n }\n } else {\n auto range_shape = (axis_ == -1) ? TensorShape({}) : TensorShape({depth});\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,\n range_shape, &input_min_tensor));\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,\n range_shape, &input_max_tensor));\n }", " if (axis_ == -1) {\n functor::QuantizeAndDequantizeOneScaleFunctor<Device, T> f;\n f(ctx->eigen_device<Device>(), input.flat<T>(), signed_input_, num_bits_,\n range_given_, &input_min_tensor, &input_max_tensor, round_mode_,\n narrow_range_, output->flat<T>());\n } else {\n functor::QuantizeAndDequantizePerChannelFunctor<Device, T> f;\n f(ctx->eigen_device<Device>(),\n input.template flat_inner_outer_dims<T, 3>(axis_ - 1), signed_input_,\n num_bits_, range_given_, &input_min_tensor, &input_max_tensor,\n round_mode_, narrow_range_,\n output->template flat_inner_outer_dims<T, 3>(axis_ - 1));\n }\n }", " private:\n int num_bits_;\n int axis_;\n QuantizerRoundMode round_mode_;\n bool signed_input_;\n bool range_given_;\n bool narrow_range_;\n};", "// Implementation of QuantizeAndDequantizeV4GradientOp.\n// When back-propagating the error through a quantized layer, the following\n// paper gives evidence that clipped-ReLU is better than non-clipped:\n// \"Deep Learning with Low Precision by Half-wave Gaussian Quantization\"\n// http://zpascal.net/cvpr2017/Cai_Deep_Learning_With_CVPR_2017_paper.pdf\ntemplate <typename Device, typename T>\nclass QuantizeAndDequantizeV4GradientOp : public OpKernel {\n public:\n explicit QuantizeAndDequantizeV4GradientOp(OpKernelConstruction* ctx)\n : OpKernel::OpKernel(ctx) {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"axis\", &axis_));\n }", " void Compute(OpKernelContext* ctx) override {\n const Tensor& gradient = ctx->input(0);\n const Tensor& input = ctx->input(1);\n Tensor* input_backprop = nullptr;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(0, input.shape(), &input_backprop));", " OP_REQUIRES(\n ctx, axis_ >= -1,\n errors::InvalidArgument(\"Axis must be at least -1. Found \", axis_));\n OP_REQUIRES(ctx, (axis_ == -1 || axis_ < input.shape().dims()),\n errors::InvalidArgument(\n \"Axis should be -1 or 0 or a positive value less than \",\n input.shape().dims(), \"but given axis value was \", axis_));", "\n OP_REQUIRES(\n ctx, input.IsSameSize(gradient),\n errors::InvalidArgument(\"gradient and input must be the same size\"));\n const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_);\n const Tensor& input_min_tensor = ctx->input(2);\n OP_REQUIRES(ctx,\n input_min_tensor.dims() == 0 || input_min_tensor.dims() == 1,\n errors::InvalidArgument(\n \"Input min tensor must have dimension 1. Recieved \",\n input_min_tensor.dims(), \".\"));\n const Tensor& input_max_tensor = ctx->input(3);\n OP_REQUIRES(ctx,\n input_max_tensor.dims() == 0 || input_max_tensor.dims() == 1,\n errors::InvalidArgument(\n \"Input max tensor must have dimension 1. Recieved \",\n input_max_tensor.dims(), \".\"));\n if (axis_ != -1) {\n OP_REQUIRES(\n ctx, input_min_tensor.dim_size(0) == depth,\n errors::InvalidArgument(\"min has incorrect size, expected \", depth,\n \" was \", input_min_tensor.dim_size(0)));\n OP_REQUIRES(\n ctx, input_max_tensor.dim_size(0) == depth,\n errors::InvalidArgument(\"max has incorrect size, expected \", depth,\n \" was \", input_max_tensor.dim_size(0)));\n }", " TensorShape min_max_shape(input_min_tensor.shape());\n Tensor* input_min_backprop;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(1, min_max_shape, &input_min_backprop));", " Tensor* input_max_backprop;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(2, min_max_shape, &input_max_backprop));", " if (axis_ == -1) {\n functor::QuantizeAndDequantizeOneScaleGradientFunctor<Device, T> f;\n f(ctx->eigen_device<Device>(), gradient.template flat<T>(),\n input.template flat<T>(), input_min_tensor.scalar<T>(),\n input_max_tensor.scalar<T>(), input_backprop->template flat<T>(),\n input_min_backprop->template scalar<T>(),\n input_max_backprop->template scalar<T>());\n } else {\n functor::QuantizeAndDequantizePerChannelGradientFunctor<Device, T> f;\n f(ctx->eigen_device<Device>(),\n gradient.template flat_inner_outer_dims<T, 3>(axis_ - 1),\n input.template flat_inner_outer_dims<T, 3>(axis_ - 1),\n &input_min_tensor, &input_max_tensor,\n input_backprop->template flat_inner_outer_dims<T, 3>(axis_ - 1),\n input_min_backprop->template flat<T>(),\n input_max_backprop->template flat<T>());\n }\n }", " private:\n int axis_;\n};", "// Simulate quantization precision loss in a float tensor by:\n// 1. Quantize the tensor to fixed point numbers, which should match the target\n// quantization method when it is used in inference.\n// 2. Dequantize it back to floating point numbers for the following ops, most\n// likely matmul.\n// Almost identical to QuantizeAndDequantizeV2Op, except that num_bits is a\n// tensor.\ntemplate <typename Device, typename T>\nclass QuantizeAndDequantizeV3Op : public OpKernel {\n public:\n explicit QuantizeAndDequantizeV3Op(OpKernelConstruction* ctx)\n : OpKernel(ctx) {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"signed_input\", &signed_input_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"range_given\", &range_given_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"narrow_range\", &narrow_range_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"axis\", &axis_));\n }", " void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);\n OP_REQUIRES(ctx, axis_ < input.dims(),\n errors::InvalidArgument(\n \"Axis requested is larger than input dimensions. Axis: \",\n axis_, \" Input Dimensions: \", input.dims()));\n const int depth = (axis_ == -1) ? 1 : input.dim_size(axis_);\n Tensor* output = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));", " Tensor num_bits_tensor;\n num_bits_tensor = ctx->input(3);\n int num_bits_val = num_bits_tensor.scalar<int32>()();", " OP_REQUIRES(\n ctx, num_bits_val > 0 && num_bits_val < (signed_input_ ? 62 : 63),\n errors::InvalidArgument(\"num_bits is out of range: \", num_bits_val,\n \" with signed_input_ \", signed_input_));", " Tensor input_min_tensor;\n Tensor input_max_tensor;\n if (range_given_) {\n input_min_tensor = ctx->input(1);\n input_max_tensor = ctx->input(2);\n if (axis_ == -1) {\n auto min_val = input_min_tensor.scalar<T>()();\n auto max_val = input_max_tensor.scalar<T>()();\n OP_REQUIRES(ctx, min_val <= max_val,\n errors::InvalidArgument(\"Invalid range: input_min \",\n min_val, \" > input_max \", max_val));\n } else {\n OP_REQUIRES(ctx, input_min_tensor.dim_size(0) == depth,\n errors::InvalidArgument(\n \"input_min_tensor has incorrect size, was \",\n input_min_tensor.dim_size(0), \" expected \", depth,\n \" to match dim \", axis_, \" of the input \",\n input_min_tensor.shape()));\n OP_REQUIRES(ctx, input_max_tensor.dim_size(0) == depth,\n errors::InvalidArgument(\n \"input_max_tensor has incorrect size, was \",\n input_max_tensor.dim_size(0), \" expected \", depth,\n \" to match dim \", axis_, \" of the input \",\n input_max_tensor.shape()));\n }\n } else {\n auto range_shape = (axis_ == -1) ? TensorShape({}) : TensorShape({depth});\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,\n range_shape, &input_min_tensor));\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,\n range_shape, &input_max_tensor));\n }", " if (axis_ == -1) {\n functor::QuantizeAndDequantizeOneScaleFunctor<Device, T> f;\n f(ctx->eigen_device<Device>(), input.flat<T>(), signed_input_,\n num_bits_val, range_given_, &input_min_tensor, &input_max_tensor,\n ROUND_HALF_TO_EVEN, narrow_range_, output->flat<T>());\n } else {\n functor::QuantizeAndDequantizePerChannelFunctor<Device, T> f;\n f(ctx->eigen_device<Device>(),\n input.template flat_inner_outer_dims<T, 3>(axis_ - 1), signed_input_,\n num_bits_val, range_given_, &input_min_tensor, &input_max_tensor,\n ROUND_HALF_TO_EVEN, narrow_range_,\n output->template flat_inner_outer_dims<T, 3>(axis_ - 1));\n }\n }", " private:\n int axis_;\n bool signed_input_;\n bool range_given_;\n bool narrow_range_;\n};", "// DEPRECATED: Use QuantizeAndDequantizeV2Op.\ntemplate <typename Device, typename T>\nclass QuantizeAndDequantizeOp : public OpKernel {\n public:\n explicit QuantizeAndDequantizeOp(OpKernelConstruction* ctx) : OpKernel(ctx) {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"signed_input\", &signed_input_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"num_bits\", &num_bits_));\n OP_REQUIRES(ctx, num_bits_ > 0 && num_bits_ < (signed_input_ ? 62 : 63),\n errors::InvalidArgument(\"num_bits is out of range: \", num_bits_,\n \" with signed_input_ \", signed_input_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"range_given\", &range_given_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"input_min\", &input_min_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"input_max\", &input_max_));\n if (range_given_) {\n OP_REQUIRES(\n ctx, input_min_ <= input_max_,\n errors::InvalidArgument(\"Invalid range: input_min \", input_min_,\n \" > input_max \", input_max_));\n }\n }", " void Compute(OpKernelContext* ctx) override {\n const Tensor& input = ctx->input(0);", " Tensor* output = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, input.shape(), &output));", " // One global scale.\n Tensor input_min_tensor(DataTypeToEnum<T>::value, TensorShape());\n Tensor input_max_tensor(DataTypeToEnum<T>::value, TensorShape());\n // Initialize the tensors with the values in the Attrs.\n input_min_tensor.template scalar<T>()() = static_cast<T>(input_min_);\n input_max_tensor.template scalar<T>()() = static_cast<T>(input_max_);", " functor::QuantizeAndDequantizeOneScaleFunctor<Device, T> functor;\n functor(ctx->eigen_device<Device>(), input.flat<T>(), signed_input_,\n num_bits_, range_given_, &input_min_tensor, &input_max_tensor,\n ROUND_HALF_TO_EVEN, /*narrow_range=*/false, output->flat<T>());\n }", " private:\n bool signed_input_;\n int num_bits_;\n bool range_given_;\n float input_min_;\n float input_max_;\n};", "// Specializations for CPUDevice.", "namespace functor {\ntemplate <typename T>\nstruct QuantizeAndDequantizeOneScaleFunctor<CPUDevice, T> {\n void operator()(const CPUDevice& d, typename TTypes<T>::ConstVec input,\n const bool signed_input, const int num_bits,\n const bool range_given, Tensor* input_min_tensor,\n Tensor* input_max_tensor, QuantizerRoundMode round_mode,\n bool narrow_range, typename TTypes<T>::Vec out) {\n QuantizeAndDequantizeOneScaleImpl<CPUDevice, T>::Compute(\n d, input, signed_input, num_bits, range_given, input_min_tensor,\n input_max_tensor, round_mode, narrow_range, out);\n }\n};", "template <typename T>\nstruct QuantizeAndDequantizePerChannelFunctor<CPUDevice, T> {\n void operator()(const CPUDevice& d, typename TTypes<T, 3>::ConstTensor input,\n bool signed_input, int num_bits, bool range_given,\n Tensor* input_min_tensor, Tensor* input_max_tensor,\n QuantizerRoundMode round_mode, bool narrow_range,\n typename TTypes<T, 3>::Tensor out) {\n QuantizeAndDequantizePerChannelImpl<CPUDevice, T>::Compute(\n d, input, signed_input, num_bits, range_given, input_min_tensor,\n input_max_tensor, round_mode, narrow_range, out);\n }\n};", "template <typename T>\nstruct QuantizeAndDequantizeOneScaleGradientFunctor<CPUDevice, T> {\n void operator()(const CPUDevice& d, typename TTypes<T>::ConstFlat gradient,\n typename TTypes<T>::ConstFlat input,\n typename TTypes<T>::ConstScalar input_min_tensor,\n typename TTypes<T>::ConstScalar input_max_tensor,\n typename TTypes<T>::Flat input_backprop,\n typename TTypes<T>::Scalar input_min_backprop,\n typename TTypes<T>::Scalar input_max_backprop) {\n QuantizeAndDequantizeOneScaleGradientImpl<CPUDevice, T>::Compute(\n d, gradient, input, input_min_tensor, input_max_tensor, input_backprop,\n input_min_backprop, input_max_backprop);\n }\n};", "template <typename T>\nstruct QuantizeAndDequantizePerChannelGradientFunctor<CPUDevice, T> {\n void operator()(const CPUDevice& d,\n typename TTypes<T, 3>::ConstTensor gradient,\n typename TTypes<T, 3>::ConstTensor input,\n const Tensor* input_min_tensor,\n const Tensor* input_max_tensor,\n typename TTypes<T, 3>::Tensor input_backprop,\n typename TTypes<T>::Flat input_min_backprop,\n typename TTypes<T>::Flat input_max_backprop) {\n QuantizeAndDequantizePerChannelGradientImpl<CPUDevice, T>::Compute(\n d, gradient, input, input_min_tensor, input_max_tensor, input_backprop,\n input_min_backprop, input_max_backprop);\n }\n};", "template struct functor::QuantizeAndDequantizeOneScaleGradientFunctor<CPUDevice,\n float>;\ntemplate struct functor::QuantizeAndDequantizePerChannelGradientFunctor<\n CPUDevice, double>;", "} // namespace functor", "#define REGISTER_CPU_KERNEL(T) \\\n REGISTER_KERNEL_BUILDER(Name(\"QuantizeAndDequantizeV2\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<T>(\"T\"), \\\n QuantizeAndDequantizeV2Op<CPUDevice, T>); \\\n REGISTER_KERNEL_BUILDER(Name(\"QuantizeAndDequantizeV3\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<T>(\"T\"), \\\n QuantizeAndDequantizeV3Op<CPUDevice, T>); \\\n REGISTER_KERNEL_BUILDER(Name(\"QuantizeAndDequantizeV4\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<T>(\"T\"), \\\n QuantizeAndDequantizeV2Op<CPUDevice, T>); \\\n REGISTER_KERNEL_BUILDER(Name(\"QuantizeAndDequantizeV4Grad\") \\\n .Device(DEVICE_CPU) \\\n .TypeConstraint<T>(\"T\"), \\\n QuantizeAndDequantizeV4GradientOp<CPUDevice, T>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"QuantizeAndDequantize\").Device(DEVICE_CPU).TypeConstraint<T>(\"T\"), \\\n QuantizeAndDequantizeOp<CPUDevice, T>);\nTF_CALL_float(REGISTER_CPU_KERNEL);\nTF_CALL_double(REGISTER_CPU_KERNEL);\n#undef REGISTER_CPU_KERNEL", "#if (defined(GOOGLE_CUDA) && GOOGLE_CUDA) || \\\n (defined(TENSORFLOW_USE_ROCM) && TENSORFLOW_USE_ROCM)\n#define REGISTER_GPU_KERNEL(T) \\\n REGISTER_KERNEL_BUILDER(Name(\"QuantizeAndDequantizeV2\") \\\n .Device(DEVICE_GPU) \\\n .HostMemory(\"input_min\") \\\n .HostMemory(\"input_max\") \\\n .TypeConstraint<T>(\"T\"), \\\n QuantizeAndDequantizeV2Op<GPUDevice, T>); \\\n REGISTER_KERNEL_BUILDER(Name(\"QuantizeAndDequantizeV3\") \\\n .Device(DEVICE_GPU) \\\n .HostMemory(\"input_min\") \\\n .HostMemory(\"input_max\") \\\n .HostMemory(\"num_bits\") \\\n .TypeConstraint<T>(\"T\"), \\\n QuantizeAndDequantizeV3Op<GPUDevice, T>); \\\n REGISTER_KERNEL_BUILDER(Name(\"QuantizeAndDequantizeV4\") \\\n .Device(DEVICE_GPU) \\\n .HostMemory(\"input_min\") \\\n .HostMemory(\"input_max\") \\\n .TypeConstraint<T>(\"T\"), \\\n QuantizeAndDequantizeV2Op<GPUDevice, T>); \\\n REGISTER_KERNEL_BUILDER(Name(\"QuantizeAndDequantizeV4Grad\") \\\n .Device(DEVICE_GPU) \\\n .HostMemory(\"input_min\") \\\n .HostMemory(\"input_max\") \\\n .TypeConstraint<T>(\"T\"), \\\n QuantizeAndDequantizeV4GradientOp<GPUDevice, T>); \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"QuantizeAndDequantize\").Device(DEVICE_GPU).TypeConstraint<T>(\"T\"), \\\n QuantizeAndDequantizeOp<GPUDevice, T>);\nTF_CALL_float(REGISTER_GPU_KERNEL);\nTF_CALL_double(REGISTER_GPU_KERNEL);\n#undef REGISTER_GPU_KERNEL\n#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM\n} // namespace tensorflow" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [160], "buggy_code_start_loc": [160], "filenames": ["tensorflow/core/kernels/quantize_and_dequantize_op.cc"], "fixing_code_end_loc": [168], "fixing_code_start_loc": [161], "message": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions the implementation of `tf.raw_ops.QuantizeAndDequantizeV4Grad` is vulnerable to an integer overflow issue caused by converting a signed integer value to an unsigned one and then allocating memory based on this value. The [implementation](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/quantize_and_dequantize_op.cc#L126) uses the `axis` value as the size argument to `absl::InlinedVector` constructor. But, the constructor uses an unsigned type for the argument, so the implicit conversion transforms the negative value to a large integer. We have patched the issue in GitHub commit 96f364a1ca3009f98980021c4b32be5fdcca33a1. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, and TensorFlow 2.4.3, as these are also affected and still in supported range.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "0F83C081-51CC-415F-A8C0-0A44C75E2CD6", "versionEndExcluding": "2.3.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.3.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:*:*:*:*", "matchCriteriaId": "BD3F2BF8-EBA9-42BF-8F9B-D918B880B15A", "versionEndExcluding": "2.4.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.4.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.5.0:*:*:*:*:*:*:*", "matchCriteriaId": "D03E99A7-4E3D-427D-A156-C0713E9FB02A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.6.0:rc0:*:*:*:*:*:*", "matchCriteriaId": "70FA6E48-6C57-40CA-809F-4E3D07CBF348", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.6.0:rc1:*:*:*:*:*:*", "matchCriteriaId": "42187561-E491-434D-828C-F36701446634", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:2.6.0:rc2:*:*:*:*:*:*", "matchCriteriaId": "C66B61C8-450A-4C5E-9174-F970D6DEE778", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "TensorFlow is an end-to-end open source platform for machine learning. In affected versions the implementation of `tf.raw_ops.QuantizeAndDequantizeV4Grad` is vulnerable to an integer overflow issue caused by converting a signed integer value to an unsigned one and then allocating memory based on this value. The [implementation](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/quantize_and_dequantize_op.cc#L126) uses the `axis` value as the size argument to `absl::InlinedVector` constructor. But, the constructor uses an unsigned type for the argument, so the implicit conversion transforms the negative value to a large integer. We have patched the issue in GitHub commit 96f364a1ca3009f98980021c4b32be5fdcca33a1. The fix will be included in TensorFlow 2.6.0. We will also cherrypick this commit on TensorFlow 2.5.1, and TensorFlow 2.4.3, as these are also affected and still in supported range."}, {"lang": "es", "value": "TensorFlow es una plataforma de c\u00f3digo abierto de extremo a extremo para el aprendizaje autom\u00e1tico. En las versiones afectadas, la implementaci\u00f3n \"tf.raw_ops.QuantizeAndDequantizeV4Grad\" es vulnerable a un problema de desbordamiento de enteros causado al convertir un valor entero con signo a uno sin signo y la posterior asignaci\u00f3n de memoria basada en este valor. La [implementaci\u00f3n](https://github.com/tensorflow/tensorflow/blob/8d72537c6abf5a44103b57b9c2e22c14f5f49698/tensorflow/core/kernels/quantize_and_dequantize_op.cc#L126) usa el valor de \"axis\" como argumento del tama\u00f1o del constructor de \"absl::InlinedVector\". Pero, el constructor usa un tipo sin signo para el argumento, por lo que la conversi\u00f3n impl\u00edcita transforma el valor negativo en un entero grande. Hemos parcheado el problema en el commit 96f364a1ca3009f98980021c4b32be5fdcca33a1 de GitHub. La correcci\u00f3n ser\u00e1 incluida en TensorFlow versi\u00f3n 2.6.0. Tambi\u00e9n seleccionaremos este commit en TensorFlow 2.5.1, y TensorFlow 2.4.3, ya que estos tambi\u00e9n est\u00e1n afectados y todav\u00eda en el rango de soporte."}], "evaluatorComment": null, "id": "CVE-2021-37645", "lastModified": "2021-08-18T15:38:52.563", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 2.1, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-08-12T21:15:07.887", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/commit/96f364a1ca3009f98980021c4b32be5fdcca33a1"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/security/advisories/GHSA-9w2p-5mgw-p94c"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-681"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/tensorflow/tensorflow/commit/96f364a1ca3009f98980021c4b32be5fdcca33a1"}, "type": "CWE-681"}
204
Determine whether the {function_name} code is vulnerable or not.
[ "package server", "import (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net/http\"\n\t\"os\"\n\t\"os/signal\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"runtime/debug\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"", "\t\"github.com/Azure/go-autorest/autorest/adal\"\n\t\"github.com/gorilla/mux\"\n\t\"k8s.io/klog/v2\"", "\t\"github.com/Azure/aad-pod-identity/pkg/auth\"\n\t\"github.com/Azure/aad-pod-identity/pkg/k8s\"\n\t\"github.com/Azure/aad-pod-identity/pkg/metrics\"\n\t\"github.com/Azure/aad-pod-identity/pkg/nmi\"\n\t\"github.com/Azure/aad-pod-identity/pkg/nmi/conntrack\"\n\t\"github.com/Azure/aad-pod-identity/pkg/nmi/iptables\"\n\t\"github.com/Azure/aad-pod-identity/pkg/pod\"\n)", "const (\n\tlocalhost = \"127.0.0.1\"\n\t// \"/metadata\" portion is case-insensitive in IMDS\n\ttokenPathPrefix = \"/{type:(?i:metadata)}/identity/oauth2/token\" // #nosec\n\thostTokenPathPrefix = \"/host/token\"\n\t// \"/metadata\" portion is case-insensitive in IMDS\n\tinstancePathPrefix = \"/{type:(?i:metadata)}/instance\" // #nosec\n\theaderRetryAfter = \"Retry-After\"", "", ")", "// Server encapsulates all of the parameters necessary for starting up\n// the server. These can be set via command line.\ntype Server struct {\n\tKubeClient k8s.Client\n\tNMIHost string\n\tNMIPort string\n\tMetadataIP string\n\tMetadataPort string\n\tNodeName string\n\tIPTableUpdateTimeIntervalInSeconds int\n\tMICNamespace string\n\tInitialized bool\n\tBlockInstanceMetadata bool\n\tMetadataHeaderRequired bool\n\tSetRetryAfterHeader bool\n\tEnableConntrackDeletion bool\n\t// TokenClient is client that fetches identities and tokens\n\tTokenClient nmi.TokenClient\n\tReporter *metrics.Reporter\n}", "// NMIResponse is the response returned to caller\ntype NMIResponse struct {\n\tToken msiResponse `json:\"token\"`\n\tClientID string `json:\"clientid\"`\n}", "// MetadataResponse represents the error returned\n// to caller when metadata header is not specified.\ntype MetadataResponse struct {\n\tError string `json:\"error\"`\n\tErrorDescription string `json:\"error_description\"`\n}", "// NewServer will create a new Server with default values.\nfunc NewServer(micNamespace string, blockInstanceMetadata, metadataHeaderRequired, setRetryAfterHeader bool) *Server {\n\treporter, err := metrics.NewReporter()\n\tif err != nil {\n\t\tklog.Errorf(\"failed to create reporter for metrics, error: %+v\", err)\n\t} else {\n\t\t// keeping this reference to be used in ServeHTTP, as server is not accessible in ServeHTTP\n\t\tappHandlerReporter = reporter\n\t\tauth.InitReporter(reporter)\n\t}\n\treturn &Server{\n\t\tMICNamespace: micNamespace,\n\t\tBlockInstanceMetadata: blockInstanceMetadata,\n\t\tMetadataHeaderRequired: metadataHeaderRequired,\n\t\tReporter: reporter,\n\t\tSetRetryAfterHeader: setRetryAfterHeader,\n\t}\n}", "// Run runs the specified Server.\nfunc (s *Server) Run() error {\n\tgo s.updateIPTableRules()", "\trtr := mux.NewRouter()", "", "\trtr.PathPrefix(tokenPathPrefix).Handler(appHandler(s.msiHandler))", "", "\trtr.PathPrefix(hostTokenPathPrefix).Handler(appHandler(s.hostHandler))\n\tif s.BlockInstanceMetadata {\n\t\trtr.PathPrefix(instancePathPrefix).HandlerFunc(forbiddenHandler)\n\t}\n\trtr.PathPrefix(\"/\").HandlerFunc(s.defaultPathHandler)", "\tklog.Infof(\"listening on %s:%s\", s.NMIHost, s.NMIPort)\n\tif err := http.ListenAndServe(fmt.Sprintf(\"%s:%s\", s.NMIHost, s.NMIPort), rtr); err != nil {\n\t\tklog.Fatalf(\"error creating http server: %+v\", err)\n\t}\n\treturn nil\n}", "func (s *Server) updateIPTableRulesInternal() {\n\ttarget := s.NMIHost\n\tif target == \"0.0.0.0\" {\n\t\t// if we're binding to all interfaces, we still want to add iptables rules for localhost only\n\t\ttarget = localhost\n\t}", "\tklog.V(5).Infof(\"node(%s) ip(%s) metadata address(%s:%s) nmi port(%s)\", s.NodeName, target, s.MetadataIP, s.MetadataPort, s.NMIPort)", "\tif err := iptables.AddCustomChain(s.MetadataIP, s.MetadataPort, target, s.NMIPort); err != nil {\n\t\tklog.Fatalf(\"%s\", err)\n\t}\n\tif err := iptables.LogCustomChain(); err != nil {\n\t\tklog.Fatalf(\"%s\", err)\n\t}\n}", "// try to delete pre-existing conntrack entries for metadata endpoint\nfunc (s *Server) deleteConntrackEntries() {\n\tklog.Infof(\"deleting conntrack entries for %s:%s\", s.MetadataIP, s.MetadataPort)", "\tif err := conntrack.DeleteConntrackEntries(s.MetadataIP, s.MetadataPort); err != nil {\n\t\tklog.Fatalf(\"failed to delete conntrack entries for metadata ip: %s\", err)\n\t}\n}", "// updateIPTableRules ensures the correct iptable rules are set\n// such that metadata requests are received by nmi assigned port\n// NOT originating from HostIP destined to metadata endpoint are\n// routed to NMI endpoint\nfunc (s *Server) updateIPTableRules() {\n\tsignalChan := make(chan os.Signal, 1)\n\tsignal.Notify(signalChan, syscall.SIGTERM, syscall.SIGINT)", "\tticker := time.NewTicker(time.Second * time.Duration(s.IPTableUpdateTimeIntervalInSeconds))\n\tdefer ticker.Stop()\n\t// Run once before the waiting on ticker for the rules to take effect\n\t// immediately.\n\ts.updateIPTableRulesInternal()\n\t// delete conntrack entries for pre-existing connections to metadata endpoint\n\tif s.EnableConntrackDeletion {\n\t\ts.deleteConntrackEntries()\n\t}\n\ts.Initialized = true", "loop:\n\tfor {\n\t\tselect {\n\t\tcase <-signalChan:\n\t\t\thandleTermination()\n\t\t\tbreak loop", "\t\tcase <-ticker.C:\n\t\t\ts.updateIPTableRulesInternal()\n\t\t}\n\t}\n}", "type appHandler func(http.ResponseWriter, *http.Request) string", "type responseWriter struct {\n\thttp.ResponseWriter\n\tstatusCode int\n}", "func (rw *responseWriter) WriteHeader(code int) {\n\trw.statusCode = code\n\trw.ResponseWriter.WriteHeader(code)\n}", "func newResponseWriter(w http.ResponseWriter) *responseWriter {\n\treturn &responseWriter{w, http.StatusOK}\n}", "var appHandlerReporter *metrics.Reporter", "// ServeHTTP implements the net/http server handler interface\n// and recovers from panics.\nfunc (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ttracker := fmt.Sprintf(\"req.method=%s reg.path=%s req.remote=%s\", r.Method, r.URL.Path, parseRemoteAddr(r.RemoteAddr))", "\t// Set the header in advance so that both success as well\n\t// as error paths have it set as application/json content type.\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tstart := time.Now()\n\tdefer func() {\n\t\tvar err error\n\t\tif rec := recover(); rec != nil {\n\t\t\t_, file, line, _ := runtime.Caller(3)\n\t\t\tstack := string(debug.Stack())\n\t\t\tswitch t := rec.(type) {\n\t\t\tcase string:\n\t\t\t\terr = errors.New(t)\n\t\t\tcase error:\n\t\t\t\terr = t\n\t\t\tdefault:\n\t\t\t\terr = errors.New(\"unknown error\")\n\t\t\t}\n\t\t\tklog.Errorf(\"panic processing request: %+v, file: %s, line: %d, stacktrace: '%s' %s res.status=%d\", r, file, line, stack, tracker, http.StatusInternalServerError)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t}()\n\trw := newResponseWriter(w)\n\tns := fn(rw, r)\n\tlatency := time.Since(start)\n\tklog.Infof(\"status (%d) took %d ns for %s\", rw.statusCode, latency.Nanoseconds(), tracker)", "\ttokenRequest := parseTokenRequest(r)", "\tif appHandlerReporter != nil {\n\t\terr := appHandlerReporter.ReportOperationAndStatus(\n\t\t\tr.URL.Path,\n\t\t\tstrconv.Itoa(rw.statusCode),\n\t\t\tns,\n\t\t\ttokenRequest.Resource,\n\t\t\tmetrics.NMIOperationsDurationM.M(metrics.SinceInSeconds(start)))\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"failed to report metrics, error: %+v\", err)\n\t\t}\n\t}\n}", "func (s *Server) hostHandler(w http.ResponseWriter, r *http.Request) (ns string) {\n\thostIP := parseRemoteAddr(r.RemoteAddr)\n\ttokenRequest := parseTokenRequest(r)", "\tpodns, podname := parsePodInfo(r)\n\tif podns == \"\" || podname == \"\" {\n\t\tklog.Error(\"missing podname and podns from request\")\n\t\thttp.Error(w, \"missing 'podname' and 'podns' from request header\", http.StatusBadRequest)\n\t\treturn\n\t}\n\t// set the ns so it can be used for metrics\n\tns = podns\n\tif hostIP != localhost {\n\t\tklog.Errorf(\"request remote address is not from a host\")\n\t\thttp.Error(w, \"request remote address is not from a host\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif !tokenRequest.ValidateResourceParamExists() {\n\t\tklog.Warning(\"parameter resource cannot be empty\")\n\t\thttp.Error(w, \"parameter resource cannot be empty\", http.StatusBadRequest)\n\t\treturn\n\t}", "\tpodID, err := s.TokenClient.GetIdentities(r.Context(), podns, podname, tokenRequest.ClientID, tokenRequest.ResourceID)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to get identities, error: %+v\", err)\n\t\thttp.Error(w, err.Error(), http.StatusNotFound)\n\t\treturn\n\t}\n\ttokens, err := s.TokenClient.GetTokens(r.Context(), tokenRequest.ClientID, tokenRequest.Resource, *podID)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to get service principal token for pod:%s/%s, error: %+v\", podns, podname, err)\n\t\thttpErrorCode := http.StatusForbidden\n\t\tif auth.IsHealthCheckError(err) {\n\t\t\t// the adal library performs a health check prior to making the token request\n\t\t\t// if the health check fails, we want to return a 503 instead of 403\n\t\t\t// for health check failures, the error is not a token refresh error\n\t\t\thttpErrorCode = http.StatusServiceUnavailable\n\t\t}\n\t\thttp.Error(w, err.Error(), httpErrorCode)\n\t\treturn\n\t}\n\tnmiResp := NMIResponse{\n\t\tToken: newMSIResponse(*tokens[0]),\n\t\tClientID: podID.Spec.ClientID,\n\t}\n\tresponse, err := json.Marshal(nmiResp)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to marshal service principal token and clientid for pod:%s/%s, error: %+v\", podns, podname, err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Length\", strconv.Itoa(len(response)))\n\t_, _ = w.Write(response)\n\treturn\n}", "// msiResponse marshals in a format that matches the underlying\n// metadata endpoint more closely. This increases compatibility\n// with callers built on older versions of adal client libraries.\ntype msiResponse struct {\n\tAccessToken string `json:\"access_token\"`\n\tRefreshToken string `json:\"refresh_token\"`", "\tExpiresIn string `json:\"expires_in\"`\n\tExpiresOn string `json:\"expires_on\"`\n\tNotBefore string `json:\"not_before\"`", "\tResource string `json:\"resource\"`\n\tType string `json:\"token_type\"`\n}", "func newMSIResponse(token adal.Token) msiResponse {\n\treturn msiResponse{\n\t\tAccessToken: token.AccessToken,\n\t\tRefreshToken: token.RefreshToken,\n\t\tExpiresIn: token.ExpiresIn.String(),\n\t\tExpiresOn: token.ExpiresOn.String(),\n\t\tNotBefore: token.NotBefore.String(),\n\t\tResource: token.Resource,\n\t\tType: token.Type,\n\t}\n}", "func (s *Server) isMIC(podNS, rsName string) bool {\n\tmicRegEx := regexp.MustCompile(`^mic-*`)\n\tif strings.EqualFold(podNS, s.MICNamespace) && micRegEx.MatchString(rsName) {\n\t\treturn true\n\t}\n\treturn false\n}", "func (s *Server) getTokenForExceptedPod(rqClientID, rqResource string) ([]byte, int, error) {\n\tvar token *adal.Token\n\tvar err error\n\t// ClientID is empty, so we are going to use System assigned MSI\n\tif rqClientID == \"\" {\n\t\tklog.Infof(\"fetching token for system assigned MSI\")\n\t\ttoken, err = auth.GetServicePrincipalTokenFromMSI(rqResource)\n\t} else { // User assigned identity usage.\n\t\tklog.Infof(\"fetching token for user assigned MSI for resource: %s\", rqResource)\n\t\ttoken, err = auth.GetServicePrincipalTokenFromMSIWithUserAssignedID(rqClientID, rqResource)\n\t}\n\tif err != nil {\n\t\t// TODO: return the right status code based on the error we got from adal.\n\t\treturn nil, http.StatusForbidden, fmt.Errorf(\"failed to get service principal token, error: %+v\", err)\n\t}\n\tresponse, err := json.Marshal(newMSIResponse(*token))\n\tif err != nil {\n\t\treturn nil, http.StatusInternalServerError, fmt.Errorf(\"failed to marshal service principal token, error: %+v\", err)\n\t}\n\treturn response, http.StatusOK, nil\n}", "// msiHandler uses the remote address to identify the pod ip and uses it\n// to find a matching client id, and then returns the token sourced through\n// AAD using adal\n// if the requests contains client id it validates it against the admin\n// configured id.\nfunc (s *Server) msiHandler(w http.ResponseWriter, r *http.Request) (ns string) {\n\tif s.MetadataHeaderRequired && parseMetadata(r) != \"true\" {\n\t\tklog.Errorf(\"metadata header is not specified, req.method=%s reg.path=%s req.remote=%s\", r.Method, r.URL.Path, parseRemoteAddr(r.RemoteAddr))\n\t\tmetadataNotSpecifiedError(w)\n\t\treturn\n\t}", "\tpodIP := parseRemoteAddr(r.RemoteAddr)\n\ttokenRequest := parseTokenRequest(r)", "\tif podIP == \"\" {\n\t\tklog.Error(\"request remote address is empty\")\n\t\thttp.Error(w, \"request remote address is empty\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif !tokenRequest.ValidateResourceParamExists() {\n\t\tklog.Warning(\"parameter resource cannot be empty\")\n\t\thttp.Error(w, \"parameter resource cannot be empty\", http.StatusBadRequest)\n\t\treturn\n\t}", "\tpodns, podname, rsName, selectors, err := s.KubeClient.GetPodInfo(podIP)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to get pod info from pod IP: %s, error: %+v\", podIP, err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\t// set ns for using in metrics\n\tns = podns\n\texceptionList, err := s.KubeClient.ListPodIdentityExceptions(podns)\n\tif err != nil {\n\t\tklog.Errorf(\"getting list of AzurePodIdentityException in %s namespace failed with error: %+v\", podns, err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}", "\t// If its mic, then just directly get the token and pass back.\n\tif pod.IsPodExcepted(selectors.MatchLabels, *exceptionList) || s.isMIC(podns, rsName) {\n\t\tklog.Infof(\"exception pod %s/%s token handling\", podns, podname)\n\t\tresponse, errorCode, err := s.getTokenForExceptedPod(tokenRequest.ClientID, tokenRequest.Resource)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"failed to get service principal token for pod:%s/%s with error code %d, error: %+v\", podns, podname, errorCode, err)\n\t\t\thttp.Error(w, err.Error(), errorCode)\n\t\t\treturn\n\t\t}\n\t\tw.Header().Set(\"Content-Length\", strconv.Itoa(len(response)))\n\t\t_, _ = w.Write(response)\n\t\treturn\n\t}", "\tpodID, err := s.TokenClient.GetIdentities(r.Context(), podns, podname, tokenRequest.ClientID, tokenRequest.ResourceID)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to get matching identities for pod: %s/%s, error: %+v\", podns, podname, err)\n\t\thttpErrorCode := http.StatusNotFound\n\t\tif s.SetRetryAfterHeader {\n\t\t\thttpErrorCode = http.StatusServiceUnavailable\n\t\t\t// setting it to 20s to allow MIC to finish processing current cycle and pick up this\n\t\t\t// pod in the next sync cycle\n\t\t\tw.Header().Set(headerRetryAfter, \"20\")\n\t\t}\n\t\thttp.Error(w, err.Error(), httpErrorCode)\n\t\treturn\n\t}", "\ttokens, err := s.TokenClient.GetTokens(r.Context(), tokenRequest.ClientID, tokenRequest.Resource, *podID)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to get service principal token for pod: %s/%s, error: %+v\", podns, podname, err)\n\t\thttpErrorCode := http.StatusForbidden\n\t\tif auth.IsHealthCheckError(err) {\n\t\t\t// the adal library performs a health check prior to making the token request\n\t\t\t// if the health check fails, we want to return a 503 instead of 403\n\t\t\t// for health check failures, the error is not a token refresh error\n\t\t\thttpErrorCode = http.StatusServiceUnavailable\n\t\t}\n\t\thttp.Error(w, err.Error(), httpErrorCode)\n\t\treturn\n\t}", "\tvar v interface{}\n\tif len(tokens) == 1 {\n\t\tv = newMSIResponse(*tokens[0])\n\t} else {\n\t\tvar msiResp []msiResponse\n\t\tfor _, token := range tokens {\n\t\t\tmsiResp = append(msiResp, newMSIResponse(*token))\n\t\t}\n\t\tv = msiResp\n\t}", "\tresponse, err := json.Marshal(v)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to marshal service principal token for pod: %s/%s, error: %+v\", podns, podname, err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Length\", strconv.Itoa(len(response)))\n\t_, _ = w.Write(response)\n\treturn\n}", "// Error replies to the request without the specified metadata header.\n// It does not otherwise end the request; the caller should ensure no further\n// writes are done to w.\nfunc metadataNotSpecifiedError(w http.ResponseWriter) {\n\tmetadataResp := MetadataResponse{\n\t\tError: \"invalid_request\",\n\t\tErrorDescription: \"Required metadata header not specified\",\n\t}\n\tresponse, err := json.Marshal(metadataResp)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to marshal metadata response, %+v\", err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}", "\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.WriteHeader(http.StatusBadRequest)\n\tfmt.Fprintln(w, string(response))\n}", "func parseMetadata(r *http.Request) (metadata string) {\n\treturn r.Header.Get(\"metadata\")\n}", "func parsePodInfo(r *http.Request) (podns string, podname string) {\n\tpodns = r.Header.Get(\"podns\")\n\tpodname = r.Header.Get(\"podname\")", "\treturn podns, podname\n}", "func parseRemoteAddr(addr string) string {\n\tn := strings.IndexByte(addr, ':')\n\tif n <= 1 {\n\t\treturn \"\"\n\t}\n\thostname := addr[0:n]\n\tif net.ParseIP(hostname) == nil {\n\t\treturn \"\"\n\t}\n\treturn hostname\n}", "// TokenRequest contains the client and resource ID token, as well as what resource the client is trying to access.\ntype TokenRequest struct {\n\t// ClientID identifies, by Azure AD client ID, a specific identity to use\n\t// when authenticating to Azure AD. It is mutually exclusive with\n\t// MsiResourceID.\n\t// Example: 77788899-f67e-42e1-9a78-89985f6bff3e\n\tClientID string", "\t// MsiResourceID identifies, by urlencoded ARM resource ID, a specific\n\t// identity to use when authenticating to Azure AD. It is mutually exclusive\n\t// with ClientID.\n\t// Example: /subscriptions/<subid>/resourcegroups/<resourcegroup>/providers/Microsoft.ManagedIdentity/userAssignedIdentities/<name>\n\tResourceID string", "\t// Resource is the urlencoded URI of the resource for the requested AD token.\n\t// Example: https://vault.azure.net.\n\tResource string\n}", "// ValidateResourceParamExists returns true if there exists a resource parameter from the request.\nfunc (r TokenRequest) ValidateResourceParamExists() bool {\n\t// check if resource exists in the request\n\t// if resource doesn't exist in the request, then adal libraries will return the same error\n\t// IMDS also returns an error with 400 response code if resource parameter is empty\n\t// this is done to emulate same behavior observed while requesting token from IMDS\n\treturn len(r.Resource) != 0\n}", "func parseTokenRequest(r *http.Request) (request TokenRequest) {\n\tvals := r.URL.Query()\n\tif vals != nil {\n\t\t// These are mutually exclusive values (client_id, msi_resource_id)\n\t\trequest.ClientID = vals.Get(\"client_id\")\n\t\trequest.ResourceID = vals.Get(\"msi_res_id\")", "\t\trequest.Resource = vals.Get(\"resource\")\n\t}\n\treturn request\n}", "// defaultPathHandler creates a new request and returns the response body and code\nfunc (s *Server) defaultPathHandler(w http.ResponseWriter, r *http.Request) {\n\tif s.MetadataHeaderRequired && parseMetadata(r) != \"true\" {\n\t\tklog.Errorf(\"metadata header is not specified, req.method=%s reg.path=%s req.remote=%s\", r.Method, r.URL.Path, parseRemoteAddr(r.RemoteAddr))\n\t\tmetadataNotSpecifiedError(w)\n\t\treturn\n\t}", "\tclient := &http.Client{}\n\treq, err := http.NewRequest(r.Method, r.URL.String(), r.Body)\n\tif err != nil || req == nil {\n\t\tklog.Errorf(\"failed creating a new request for %s, error: %+v\", r.URL.String(), err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\thost := fmt.Sprintf(\"%s:%s\", s.MetadataIP, s.MetadataPort)\n\treq.Host = host\n\treq.URL.Host = host\n\treq.URL.Scheme = \"http\"\n\tif r.Header != nil {\n\t\tcopyHeader(req.Header, r.Header)\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tklog.Errorf(\"failed executing request for %s, error: %+v\", req.URL.String(), err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()", "\tbody, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to read response body for %s, error: %+v\", req.URL.String(), err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n\tcopyHeader(w.Header(), resp.Header)\n\tw.WriteHeader(resp.StatusCode)\n\t_, _ = w.Write(body)\n}", "// forbiddenHandler responds to any request with HTTP 403 Forbidden\nfunc forbiddenHandler(w http.ResponseWriter, r *http.Request) {\n\thttp.Error(w, \"Request blocked by AAD Pod Identity NMI\", http.StatusForbidden)\n}\n", "", "func copyHeader(dst, src http.Header) {\n\tfor k, vv := range src {\n\t\tfor _, v := range vv {\n\t\t\tdst.Add(k, v)\n\t\t}\n\t}\n}", "func handleTermination() {\n\tklog.Info(\"received SIGTERM, shutting down\")", "\texitCode := 0\n\t// clean up iptables\n\tif err := iptables.DeleteCustomChain(); err != nil {\n\t\tklog.Errorf(\"failed to clean up during shutdown, error: %+v\", err)\n\t\texitCode = 1\n\t}", "\t// wait for pod to delete\n\tklog.Info(\"handled termination, awaiting pod deletion\")\n\ttime.Sleep(10 * time.Second)", "\tklog.Infof(\"exiting with %v\", exitCode)\n\tos.Exit(exitCode)\n}" ]
[ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [583, 265], "buggy_code_start_loc": [40, 219], "filenames": ["pkg/nmi/server/server.go", "pkg/nmi/server/server_test.go"], "fixing_code_end_loc": [608, 301], "fixing_code_start_loc": [41, 220], "message": "aad-pod-identity assigns Azure Active Directory identities to Kubernetes applications and has now been deprecated as of 24 October 2022. The NMI component in AAD Pod Identity intercepts and validates token requests based on regex. In this case, a token request made with backslash in the request (example: `/metadata/identity\\oauth2\\token/`) would bypass the NMI validation and be sent to IMDS allowing a pod in the cluster to access identities that it shouldn't have access to. This issue has been fixed and has been included in AAD Pod Identity release version 1.8.13. If using the AKS pod-managed identities add-on, no action is required. The clusters should now be running the version 1.8.13 release.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:microsoft:azure_ad_pod_identity:*:*:*:*:*:*:*:*", "matchCriteriaId": "3428D360-1FFE-4291-80B0-9EFB6F173AE6", "versionEndExcluding": "1.8.13", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "aad-pod-identity assigns Azure Active Directory identities to Kubernetes applications and has now been deprecated as of 24 October 2022. The NMI component in AAD Pod Identity intercepts and validates token requests based on regex. In this case, a token request made with backslash in the request (example: `/metadata/identity\\oauth2\\token/`) would bypass the NMI validation and be sent to IMDS allowing a pod in the cluster to access identities that it shouldn't have access to. This issue has been fixed and has been included in AAD Pod Identity release version 1.8.13. If using the AKS pod-managed identities add-on, no action is required. The clusters should now be running the version 1.8.13 release."}], "evaluatorComment": null, "id": "CVE-2022-23551", "lastModified": "2023-01-04T19:54:14.517", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "LOW", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:H/UI:R/S:U/C:L/I:H/A:L", "version": "3.1"}, "exploitabilityScore": 0.6, "impactScore": 4.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "LOW", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:H/UI:R/S:U/C:L/I:H/A:L", "version": "3.1"}, "exploitabilityScore": 0.6, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-12-21T20:15:09.490", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Azure/aad-pod-identity/commit/7e01970391bde6c360d077066ca17d059204cb5d"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Azure/aad-pod-identity/releases/tag/v1.8.13"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Azure/aad-pod-identity/security/advisories/GHSA-p82q-rxpm-hjpc"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-1259"}, {"lang": "en", "value": "CWE-863"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Azure/aad-pod-identity/commit/7e01970391bde6c360d077066ca17d059204cb5d"}, "type": "NVD-CWE-noinfo"}
205
Determine whether the {function_name} code is vulnerable or not.
[ "package server", "import (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net/http\"\n\t\"os\"\n\t\"os/signal\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"runtime/debug\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"", "\t\"github.com/Azure/go-autorest/autorest/adal\"\n\t\"github.com/gorilla/mux\"\n\t\"k8s.io/klog/v2\"", "\t\"github.com/Azure/aad-pod-identity/pkg/auth\"\n\t\"github.com/Azure/aad-pod-identity/pkg/k8s\"\n\t\"github.com/Azure/aad-pod-identity/pkg/metrics\"\n\t\"github.com/Azure/aad-pod-identity/pkg/nmi\"\n\t\"github.com/Azure/aad-pod-identity/pkg/nmi/conntrack\"\n\t\"github.com/Azure/aad-pod-identity/pkg/nmi/iptables\"\n\t\"github.com/Azure/aad-pod-identity/pkg/pod\"\n)", "const (\n\tlocalhost = \"127.0.0.1\"\n\t// \"/metadata\" portion is case-insensitive in IMDS\n\ttokenPathPrefix = \"/{type:(?i:metadata)}/identity/oauth2/token\" // #nosec\n\thostTokenPathPrefix = \"/host/token\"\n\t// \"/metadata\" portion is case-insensitive in IMDS\n\tinstancePathPrefix = \"/{type:(?i:metadata)}/instance\" // #nosec\n\theaderRetryAfter = \"Retry-After\"", ")", "var (\n\t// invalidTokenPathMatcher matches the token path that is not supported by IMDS\n\t// this handler is configured right after the token path handler to block requests with\n\t// invalid token path instead of sending it to IMDS.\n\t// we don't have to handle case sensitivity for \"/identity/\" as that's rejected by IMDS\n\tinvalidTokenPathMatcher = mux.MatcherFunc(func(req *http.Request, rm *mux.RouteMatch) bool {\n\t\tr := regexp.MustCompile(\"/(?i:metadata)/identity(.*?)oauth2(.*?)token\") // #nosec\n\t\treturn r.MatchString(req.URL.Path)\n\t})", ")", "// Server encapsulates all of the parameters necessary for starting up\n// the server. These can be set via command line.\ntype Server struct {\n\tKubeClient k8s.Client\n\tNMIHost string\n\tNMIPort string\n\tMetadataIP string\n\tMetadataPort string\n\tNodeName string\n\tIPTableUpdateTimeIntervalInSeconds int\n\tMICNamespace string\n\tInitialized bool\n\tBlockInstanceMetadata bool\n\tMetadataHeaderRequired bool\n\tSetRetryAfterHeader bool\n\tEnableConntrackDeletion bool\n\t// TokenClient is client that fetches identities and tokens\n\tTokenClient nmi.TokenClient\n\tReporter *metrics.Reporter\n}", "// NMIResponse is the response returned to caller\ntype NMIResponse struct {\n\tToken msiResponse `json:\"token\"`\n\tClientID string `json:\"clientid\"`\n}", "// MetadataResponse represents the error returned\n// to caller when metadata header is not specified.\ntype MetadataResponse struct {\n\tError string `json:\"error\"`\n\tErrorDescription string `json:\"error_description\"`\n}", "// NewServer will create a new Server with default values.\nfunc NewServer(micNamespace string, blockInstanceMetadata, metadataHeaderRequired, setRetryAfterHeader bool) *Server {\n\treporter, err := metrics.NewReporter()\n\tif err != nil {\n\t\tklog.Errorf(\"failed to create reporter for metrics, error: %+v\", err)\n\t} else {\n\t\t// keeping this reference to be used in ServeHTTP, as server is not accessible in ServeHTTP\n\t\tappHandlerReporter = reporter\n\t\tauth.InitReporter(reporter)\n\t}\n\treturn &Server{\n\t\tMICNamespace: micNamespace,\n\t\tBlockInstanceMetadata: blockInstanceMetadata,\n\t\tMetadataHeaderRequired: metadataHeaderRequired,\n\t\tReporter: reporter,\n\t\tSetRetryAfterHeader: setRetryAfterHeader,\n\t}\n}", "// Run runs the specified Server.\nfunc (s *Server) Run() error {\n\tgo s.updateIPTableRules()", "\trtr := mux.NewRouter()", "\t// Flow for the request is as follows:\n\t// 1. If the request is for token, then it will be handled by tokenHandler post validation.\n\t// 2. If the request is for token but the path is invalid, then it will be handled by invalidTokenPathHandler.\n\t// 3. If the request is for host token, then it will be handled by hostTokenHandler.\n\t// 4. If the request is for instance metadata\n\t// 4.1 If blockInstanceMetadata is set to true, then it will be handled by blockInstanceMetadataHandler (deny access to instance metadata).\n\t// 5. If the request is for any other path, it will be proxied to IMDS and the response will be returned to the caller.", "\trtr.PathPrefix(tokenPathPrefix).Handler(appHandler(s.msiHandler))", "\trtr.MatcherFunc(invalidTokenPathMatcher).HandlerFunc(invalidTokenPathHandler)", "\trtr.PathPrefix(hostTokenPathPrefix).Handler(appHandler(s.hostHandler))\n\tif s.BlockInstanceMetadata {\n\t\trtr.PathPrefix(instancePathPrefix).HandlerFunc(forbiddenHandler)\n\t}\n\trtr.PathPrefix(\"/\").HandlerFunc(s.defaultPathHandler)", "\tklog.Infof(\"listening on %s:%s\", s.NMIHost, s.NMIPort)\n\tif err := http.ListenAndServe(fmt.Sprintf(\"%s:%s\", s.NMIHost, s.NMIPort), rtr); err != nil {\n\t\tklog.Fatalf(\"error creating http server: %+v\", err)\n\t}\n\treturn nil\n}", "func (s *Server) updateIPTableRulesInternal() {\n\ttarget := s.NMIHost\n\tif target == \"0.0.0.0\" {\n\t\t// if we're binding to all interfaces, we still want to add iptables rules for localhost only\n\t\ttarget = localhost\n\t}", "\tklog.V(5).Infof(\"node(%s) ip(%s) metadata address(%s:%s) nmi port(%s)\", s.NodeName, target, s.MetadataIP, s.MetadataPort, s.NMIPort)", "\tif err := iptables.AddCustomChain(s.MetadataIP, s.MetadataPort, target, s.NMIPort); err != nil {\n\t\tklog.Fatalf(\"%s\", err)\n\t}\n\tif err := iptables.LogCustomChain(); err != nil {\n\t\tklog.Fatalf(\"%s\", err)\n\t}\n}", "// try to delete pre-existing conntrack entries for metadata endpoint\nfunc (s *Server) deleteConntrackEntries() {\n\tklog.Infof(\"deleting conntrack entries for %s:%s\", s.MetadataIP, s.MetadataPort)", "\tif err := conntrack.DeleteConntrackEntries(s.MetadataIP, s.MetadataPort); err != nil {\n\t\tklog.Fatalf(\"failed to delete conntrack entries for metadata ip: %s\", err)\n\t}\n}", "// updateIPTableRules ensures the correct iptable rules are set\n// such that metadata requests are received by nmi assigned port\n// NOT originating from HostIP destined to metadata endpoint are\n// routed to NMI endpoint\nfunc (s *Server) updateIPTableRules() {\n\tsignalChan := make(chan os.Signal, 1)\n\tsignal.Notify(signalChan, syscall.SIGTERM, syscall.SIGINT)", "\tticker := time.NewTicker(time.Second * time.Duration(s.IPTableUpdateTimeIntervalInSeconds))\n\tdefer ticker.Stop()\n\t// Run once before the waiting on ticker for the rules to take effect\n\t// immediately.\n\ts.updateIPTableRulesInternal()\n\t// delete conntrack entries for pre-existing connections to metadata endpoint\n\tif s.EnableConntrackDeletion {\n\t\ts.deleteConntrackEntries()\n\t}\n\ts.Initialized = true", "loop:\n\tfor {\n\t\tselect {\n\t\tcase <-signalChan:\n\t\t\thandleTermination()\n\t\t\tbreak loop", "\t\tcase <-ticker.C:\n\t\t\ts.updateIPTableRulesInternal()\n\t\t}\n\t}\n}", "type appHandler func(http.ResponseWriter, *http.Request) string", "type responseWriter struct {\n\thttp.ResponseWriter\n\tstatusCode int\n}", "func (rw *responseWriter) WriteHeader(code int) {\n\trw.statusCode = code\n\trw.ResponseWriter.WriteHeader(code)\n}", "func newResponseWriter(w http.ResponseWriter) *responseWriter {\n\treturn &responseWriter{w, http.StatusOK}\n}", "var appHandlerReporter *metrics.Reporter", "// ServeHTTP implements the net/http server handler interface\n// and recovers from panics.\nfunc (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ttracker := fmt.Sprintf(\"req.method=%s reg.path=%s req.remote=%s\", r.Method, r.URL.Path, parseRemoteAddr(r.RemoteAddr))", "\t// Set the header in advance so that both success as well\n\t// as error paths have it set as application/json content type.\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tstart := time.Now()\n\tdefer func() {\n\t\tvar err error\n\t\tif rec := recover(); rec != nil {\n\t\t\t_, file, line, _ := runtime.Caller(3)\n\t\t\tstack := string(debug.Stack())\n\t\t\tswitch t := rec.(type) {\n\t\t\tcase string:\n\t\t\t\terr = errors.New(t)\n\t\t\tcase error:\n\t\t\t\terr = t\n\t\t\tdefault:\n\t\t\t\terr = errors.New(\"unknown error\")\n\t\t\t}\n\t\t\tklog.Errorf(\"panic processing request: %+v, file: %s, line: %d, stacktrace: '%s' %s res.status=%d\", r, file, line, stack, tracker, http.StatusInternalServerError)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t}()\n\trw := newResponseWriter(w)\n\tns := fn(rw, r)\n\tlatency := time.Since(start)\n\tklog.Infof(\"status (%d) took %d ns for %s\", rw.statusCode, latency.Nanoseconds(), tracker)", "\ttokenRequest := parseTokenRequest(r)", "\tif appHandlerReporter != nil {\n\t\terr := appHandlerReporter.ReportOperationAndStatus(\n\t\t\tr.URL.Path,\n\t\t\tstrconv.Itoa(rw.statusCode),\n\t\t\tns,\n\t\t\ttokenRequest.Resource,\n\t\t\tmetrics.NMIOperationsDurationM.M(metrics.SinceInSeconds(start)))\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"failed to report metrics, error: %+v\", err)\n\t\t}\n\t}\n}", "func (s *Server) hostHandler(w http.ResponseWriter, r *http.Request) (ns string) {\n\thostIP := parseRemoteAddr(r.RemoteAddr)\n\ttokenRequest := parseTokenRequest(r)", "\tpodns, podname := parsePodInfo(r)\n\tif podns == \"\" || podname == \"\" {\n\t\tklog.Error(\"missing podname and podns from request\")\n\t\thttp.Error(w, \"missing 'podname' and 'podns' from request header\", http.StatusBadRequest)\n\t\treturn\n\t}\n\t// set the ns so it can be used for metrics\n\tns = podns\n\tif hostIP != localhost {\n\t\tklog.Errorf(\"request remote address is not from a host\")\n\t\thttp.Error(w, \"request remote address is not from a host\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif !tokenRequest.ValidateResourceParamExists() {\n\t\tklog.Warning(\"parameter resource cannot be empty\")\n\t\thttp.Error(w, \"parameter resource cannot be empty\", http.StatusBadRequest)\n\t\treturn\n\t}", "\tpodID, err := s.TokenClient.GetIdentities(r.Context(), podns, podname, tokenRequest.ClientID, tokenRequest.ResourceID)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to get identities, error: %+v\", err)\n\t\thttp.Error(w, err.Error(), http.StatusNotFound)\n\t\treturn\n\t}\n\ttokens, err := s.TokenClient.GetTokens(r.Context(), tokenRequest.ClientID, tokenRequest.Resource, *podID)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to get service principal token for pod:%s/%s, error: %+v\", podns, podname, err)\n\t\thttpErrorCode := http.StatusForbidden\n\t\tif auth.IsHealthCheckError(err) {\n\t\t\t// the adal library performs a health check prior to making the token request\n\t\t\t// if the health check fails, we want to return a 503 instead of 403\n\t\t\t// for health check failures, the error is not a token refresh error\n\t\t\thttpErrorCode = http.StatusServiceUnavailable\n\t\t}\n\t\thttp.Error(w, err.Error(), httpErrorCode)\n\t\treturn\n\t}\n\tnmiResp := NMIResponse{\n\t\tToken: newMSIResponse(*tokens[0]),\n\t\tClientID: podID.Spec.ClientID,\n\t}\n\tresponse, err := json.Marshal(nmiResp)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to marshal service principal token and clientid for pod:%s/%s, error: %+v\", podns, podname, err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Length\", strconv.Itoa(len(response)))\n\t_, _ = w.Write(response)\n\treturn\n}", "// msiResponse marshals in a format that matches the underlying\n// metadata endpoint more closely. This increases compatibility\n// with callers built on older versions of adal client libraries.\ntype msiResponse struct {\n\tAccessToken string `json:\"access_token\"`\n\tRefreshToken string `json:\"refresh_token\"`", "\tExpiresIn string `json:\"expires_in\"`\n\tExpiresOn string `json:\"expires_on\"`\n\tNotBefore string `json:\"not_before\"`", "\tResource string `json:\"resource\"`\n\tType string `json:\"token_type\"`\n}", "func newMSIResponse(token adal.Token) msiResponse {\n\treturn msiResponse{\n\t\tAccessToken: token.AccessToken,\n\t\tRefreshToken: token.RefreshToken,\n\t\tExpiresIn: token.ExpiresIn.String(),\n\t\tExpiresOn: token.ExpiresOn.String(),\n\t\tNotBefore: token.NotBefore.String(),\n\t\tResource: token.Resource,\n\t\tType: token.Type,\n\t}\n}", "func (s *Server) isMIC(podNS, rsName string) bool {\n\tmicRegEx := regexp.MustCompile(`^mic-*`)\n\tif strings.EqualFold(podNS, s.MICNamespace) && micRegEx.MatchString(rsName) {\n\t\treturn true\n\t}\n\treturn false\n}", "func (s *Server) getTokenForExceptedPod(rqClientID, rqResource string) ([]byte, int, error) {\n\tvar token *adal.Token\n\tvar err error\n\t// ClientID is empty, so we are going to use System assigned MSI\n\tif rqClientID == \"\" {\n\t\tklog.Infof(\"fetching token for system assigned MSI\")\n\t\ttoken, err = auth.GetServicePrincipalTokenFromMSI(rqResource)\n\t} else { // User assigned identity usage.\n\t\tklog.Infof(\"fetching token for user assigned MSI for resource: %s\", rqResource)\n\t\ttoken, err = auth.GetServicePrincipalTokenFromMSIWithUserAssignedID(rqClientID, rqResource)\n\t}\n\tif err != nil {\n\t\t// TODO: return the right status code based on the error we got from adal.\n\t\treturn nil, http.StatusForbidden, fmt.Errorf(\"failed to get service principal token, error: %+v\", err)\n\t}\n\tresponse, err := json.Marshal(newMSIResponse(*token))\n\tif err != nil {\n\t\treturn nil, http.StatusInternalServerError, fmt.Errorf(\"failed to marshal service principal token, error: %+v\", err)\n\t}\n\treturn response, http.StatusOK, nil\n}", "// msiHandler uses the remote address to identify the pod ip and uses it\n// to find a matching client id, and then returns the token sourced through\n// AAD using adal\n// if the requests contains client id it validates it against the admin\n// configured id.\nfunc (s *Server) msiHandler(w http.ResponseWriter, r *http.Request) (ns string) {\n\tif s.MetadataHeaderRequired && parseMetadata(r) != \"true\" {\n\t\tklog.Errorf(\"metadata header is not specified, req.method=%s reg.path=%s req.remote=%s\", r.Method, r.URL.Path, parseRemoteAddr(r.RemoteAddr))\n\t\tmetadataNotSpecifiedError(w)\n\t\treturn\n\t}", "\tpodIP := parseRemoteAddr(r.RemoteAddr)\n\ttokenRequest := parseTokenRequest(r)", "\tif podIP == \"\" {\n\t\tklog.Error(\"request remote address is empty\")\n\t\thttp.Error(w, \"request remote address is empty\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif !tokenRequest.ValidateResourceParamExists() {\n\t\tklog.Warning(\"parameter resource cannot be empty\")\n\t\thttp.Error(w, \"parameter resource cannot be empty\", http.StatusBadRequest)\n\t\treturn\n\t}", "\tpodns, podname, rsName, selectors, err := s.KubeClient.GetPodInfo(podIP)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to get pod info from pod IP: %s, error: %+v\", podIP, err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\t// set ns for using in metrics\n\tns = podns\n\texceptionList, err := s.KubeClient.ListPodIdentityExceptions(podns)\n\tif err != nil {\n\t\tklog.Errorf(\"getting list of AzurePodIdentityException in %s namespace failed with error: %+v\", podns, err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}", "\t// If its mic, then just directly get the token and pass back.\n\tif pod.IsPodExcepted(selectors.MatchLabels, *exceptionList) || s.isMIC(podns, rsName) {\n\t\tklog.Infof(\"exception pod %s/%s token handling\", podns, podname)\n\t\tresponse, errorCode, err := s.getTokenForExceptedPod(tokenRequest.ClientID, tokenRequest.Resource)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"failed to get service principal token for pod:%s/%s with error code %d, error: %+v\", podns, podname, errorCode, err)\n\t\t\thttp.Error(w, err.Error(), errorCode)\n\t\t\treturn\n\t\t}\n\t\tw.Header().Set(\"Content-Length\", strconv.Itoa(len(response)))\n\t\t_, _ = w.Write(response)\n\t\treturn\n\t}", "\tpodID, err := s.TokenClient.GetIdentities(r.Context(), podns, podname, tokenRequest.ClientID, tokenRequest.ResourceID)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to get matching identities for pod: %s/%s, error: %+v\", podns, podname, err)\n\t\thttpErrorCode := http.StatusNotFound\n\t\tif s.SetRetryAfterHeader {\n\t\t\thttpErrorCode = http.StatusServiceUnavailable\n\t\t\t// setting it to 20s to allow MIC to finish processing current cycle and pick up this\n\t\t\t// pod in the next sync cycle\n\t\t\tw.Header().Set(headerRetryAfter, \"20\")\n\t\t}\n\t\thttp.Error(w, err.Error(), httpErrorCode)\n\t\treturn\n\t}", "\ttokens, err := s.TokenClient.GetTokens(r.Context(), tokenRequest.ClientID, tokenRequest.Resource, *podID)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to get service principal token for pod: %s/%s, error: %+v\", podns, podname, err)\n\t\thttpErrorCode := http.StatusForbidden\n\t\tif auth.IsHealthCheckError(err) {\n\t\t\t// the adal library performs a health check prior to making the token request\n\t\t\t// if the health check fails, we want to return a 503 instead of 403\n\t\t\t// for health check failures, the error is not a token refresh error\n\t\t\thttpErrorCode = http.StatusServiceUnavailable\n\t\t}\n\t\thttp.Error(w, err.Error(), httpErrorCode)\n\t\treturn\n\t}", "\tvar v interface{}\n\tif len(tokens) == 1 {\n\t\tv = newMSIResponse(*tokens[0])\n\t} else {\n\t\tvar msiResp []msiResponse\n\t\tfor _, token := range tokens {\n\t\t\tmsiResp = append(msiResp, newMSIResponse(*token))\n\t\t}\n\t\tv = msiResp\n\t}", "\tresponse, err := json.Marshal(v)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to marshal service principal token for pod: %s/%s, error: %+v\", podns, podname, err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Length\", strconv.Itoa(len(response)))\n\t_, _ = w.Write(response)\n\treturn\n}", "// Error replies to the request without the specified metadata header.\n// It does not otherwise end the request; the caller should ensure no further\n// writes are done to w.\nfunc metadataNotSpecifiedError(w http.ResponseWriter) {\n\tmetadataResp := MetadataResponse{\n\t\tError: \"invalid_request\",\n\t\tErrorDescription: \"Required metadata header not specified\",\n\t}\n\tresponse, err := json.Marshal(metadataResp)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to marshal metadata response, %+v\", err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}", "\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.WriteHeader(http.StatusBadRequest)\n\tfmt.Fprintln(w, string(response))\n}", "func parseMetadata(r *http.Request) (metadata string) {\n\treturn r.Header.Get(\"metadata\")\n}", "func parsePodInfo(r *http.Request) (podns string, podname string) {\n\tpodns = r.Header.Get(\"podns\")\n\tpodname = r.Header.Get(\"podname\")", "\treturn podns, podname\n}", "func parseRemoteAddr(addr string) string {\n\tn := strings.IndexByte(addr, ':')\n\tif n <= 1 {\n\t\treturn \"\"\n\t}\n\thostname := addr[0:n]\n\tif net.ParseIP(hostname) == nil {\n\t\treturn \"\"\n\t}\n\treturn hostname\n}", "// TokenRequest contains the client and resource ID token, as well as what resource the client is trying to access.\ntype TokenRequest struct {\n\t// ClientID identifies, by Azure AD client ID, a specific identity to use\n\t// when authenticating to Azure AD. It is mutually exclusive with\n\t// MsiResourceID.\n\t// Example: 77788899-f67e-42e1-9a78-89985f6bff3e\n\tClientID string", "\t// MsiResourceID identifies, by urlencoded ARM resource ID, a specific\n\t// identity to use when authenticating to Azure AD. It is mutually exclusive\n\t// with ClientID.\n\t// Example: /subscriptions/<subid>/resourcegroups/<resourcegroup>/providers/Microsoft.ManagedIdentity/userAssignedIdentities/<name>\n\tResourceID string", "\t// Resource is the urlencoded URI of the resource for the requested AD token.\n\t// Example: https://vault.azure.net.\n\tResource string\n}", "// ValidateResourceParamExists returns true if there exists a resource parameter from the request.\nfunc (r TokenRequest) ValidateResourceParamExists() bool {\n\t// check if resource exists in the request\n\t// if resource doesn't exist in the request, then adal libraries will return the same error\n\t// IMDS also returns an error with 400 response code if resource parameter is empty\n\t// this is done to emulate same behavior observed while requesting token from IMDS\n\treturn len(r.Resource) != 0\n}", "func parseTokenRequest(r *http.Request) (request TokenRequest) {\n\tvals := r.URL.Query()\n\tif vals != nil {\n\t\t// These are mutually exclusive values (client_id, msi_resource_id)\n\t\trequest.ClientID = vals.Get(\"client_id\")\n\t\trequest.ResourceID = vals.Get(\"msi_res_id\")", "\t\trequest.Resource = vals.Get(\"resource\")\n\t}\n\treturn request\n}", "// defaultPathHandler creates a new request and returns the response body and code\nfunc (s *Server) defaultPathHandler(w http.ResponseWriter, r *http.Request) {\n\tif s.MetadataHeaderRequired && parseMetadata(r) != \"true\" {\n\t\tklog.Errorf(\"metadata header is not specified, req.method=%s reg.path=%s req.remote=%s\", r.Method, r.URL.Path, parseRemoteAddr(r.RemoteAddr))\n\t\tmetadataNotSpecifiedError(w)\n\t\treturn\n\t}", "\tclient := &http.Client{}\n\treq, err := http.NewRequest(r.Method, r.URL.String(), r.Body)\n\tif err != nil || req == nil {\n\t\tklog.Errorf(\"failed creating a new request for %s, error: %+v\", r.URL.String(), err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\thost := fmt.Sprintf(\"%s:%s\", s.MetadataIP, s.MetadataPort)\n\treq.Host = host\n\treq.URL.Host = host\n\treq.URL.Scheme = \"http\"\n\tif r.Header != nil {\n\t\tcopyHeader(req.Header, r.Header)\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tklog.Errorf(\"failed executing request for %s, error: %+v\", req.URL.String(), err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()", "\tbody, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to read response body for %s, error: %+v\", req.URL.String(), err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n\tcopyHeader(w.Header(), resp.Header)\n\tw.WriteHeader(resp.StatusCode)\n\t_, _ = w.Write(body)\n}", "// forbiddenHandler responds to any request with HTTP 403 Forbidden\nfunc forbiddenHandler(w http.ResponseWriter, r *http.Request) {\n\thttp.Error(w, \"Request blocked by AAD Pod Identity NMI\", http.StatusForbidden)\n}\n", "// invalidTokenPathHandler responds to invalid token requests with HTTP 400 Bad Request\nfunc invalidTokenPathHandler(w http.ResponseWriter, r *http.Request) {\n\thttp.Error(w, \"Invalid request\", http.StatusBadRequest)\n}\n", "func copyHeader(dst, src http.Header) {\n\tfor k, vv := range src {\n\t\tfor _, v := range vv {\n\t\t\tdst.Add(k, v)\n\t\t}\n\t}\n}", "func handleTermination() {\n\tklog.Info(\"received SIGTERM, shutting down\")", "\texitCode := 0\n\t// clean up iptables\n\tif err := iptables.DeleteCustomChain(); err != nil {\n\t\tklog.Errorf(\"failed to clean up during shutdown, error: %+v\", err)\n\t\texitCode = 1\n\t}", "\t// wait for pod to delete\n\tklog.Info(\"handled termination, awaiting pod deletion\")\n\ttime.Sleep(10 * time.Second)", "\tklog.Infof(\"exiting with %v\", exitCode)\n\tos.Exit(exitCode)\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [583, 265], "buggy_code_start_loc": [40, 219], "filenames": ["pkg/nmi/server/server.go", "pkg/nmi/server/server_test.go"], "fixing_code_end_loc": [608, 301], "fixing_code_start_loc": [41, 220], "message": "aad-pod-identity assigns Azure Active Directory identities to Kubernetes applications and has now been deprecated as of 24 October 2022. The NMI component in AAD Pod Identity intercepts and validates token requests based on regex. In this case, a token request made with backslash in the request (example: `/metadata/identity\\oauth2\\token/`) would bypass the NMI validation and be sent to IMDS allowing a pod in the cluster to access identities that it shouldn't have access to. This issue has been fixed and has been included in AAD Pod Identity release version 1.8.13. If using the AKS pod-managed identities add-on, no action is required. The clusters should now be running the version 1.8.13 release.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:microsoft:azure_ad_pod_identity:*:*:*:*:*:*:*:*", "matchCriteriaId": "3428D360-1FFE-4291-80B0-9EFB6F173AE6", "versionEndExcluding": "1.8.13", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "aad-pod-identity assigns Azure Active Directory identities to Kubernetes applications and has now been deprecated as of 24 October 2022. The NMI component in AAD Pod Identity intercepts and validates token requests based on regex. In this case, a token request made with backslash in the request (example: `/metadata/identity\\oauth2\\token/`) would bypass the NMI validation and be sent to IMDS allowing a pod in the cluster to access identities that it shouldn't have access to. This issue has been fixed and has been included in AAD Pod Identity release version 1.8.13. If using the AKS pod-managed identities add-on, no action is required. The clusters should now be running the version 1.8.13 release."}], "evaluatorComment": null, "id": "CVE-2022-23551", "lastModified": "2023-01-04T19:54:14.517", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "LOW", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:H/UI:R/S:U/C:L/I:H/A:L", "version": "3.1"}, "exploitabilityScore": 0.6, "impactScore": 4.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "LOW", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:H/UI:R/S:U/C:L/I:H/A:L", "version": "3.1"}, "exploitabilityScore": 0.6, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-12-21T20:15:09.490", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Azure/aad-pod-identity/commit/7e01970391bde6c360d077066ca17d059204cb5d"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Azure/aad-pod-identity/releases/tag/v1.8.13"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Azure/aad-pod-identity/security/advisories/GHSA-p82q-rxpm-hjpc"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-1259"}, {"lang": "en", "value": "CWE-863"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Azure/aad-pod-identity/commit/7e01970391bde6c360d077066ca17d059204cb5d"}, "type": "NVD-CWE-noinfo"}
205
Determine whether the {function_name} code is vulnerable or not.
[ "package server", "import (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"strings\"\n\t\"testing\"", "\t\"github.com/gorilla/mux\"\n)", "var (\n\trtr *mux.Router\n\tserver *httptest.Server\n\ttokenPath = \"/metadata/identity/oauth2/token/\"\n)", "func setup() {\n\trtr = mux.NewRouter()\n\tserver = httptest.NewServer(rtr)\n}", "func teardown() {\n\tserver.Close()\n}", "func TestMsiHandler_NoMetadataHeader(t *testing.T) {\n\tsetup()\n\tdefer teardown()", "\ts := &Server{\n\t\tMetadataHeaderRequired: true,\n\t}\n\trtr.PathPrefix(\"/{type:(?i:metadata)}/identity/oauth2/token/\").Handler(appHandler(s.msiHandler))", "\treq, err := http.NewRequest(http.MethodGet, tokenPath, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}", "\trecorder := httptest.NewRecorder()\n\trtr.ServeHTTP(recorder, req)", "\tif recorder.Code != http.StatusBadRequest {\n\t\tt.Errorf(\"Unexpected status code %d\", recorder.Code)\n\t}", "\tresp := &MetadataResponse{\n\t\tError: \"invalid_request\",\n\t\tErrorDescription: \"Required metadata header not specified\",\n\t}\n\texpected, err := json.Marshal(resp)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}", "\tif string(expected) != strings.TrimSpace(recorder.Body.String()) {\n\t\tt.Errorf(\"Unexpected response body %s\", recorder.Body.String())\n\t}\n}", "func TestMsiHandler_NoRemoteAddress(t *testing.T) {\n\tsetup()\n\tdefer teardown()", "\ts := &Server{\n\t\tMetadataHeaderRequired: false,\n\t}\n\trtr.PathPrefix(\"/{type:(?i:metadata)}/identity/oauth2/token/\").Handler(appHandler(s.msiHandler))", "\treq, err := http.NewRequest(http.MethodGet, tokenPath, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}", "\trecorder := httptest.NewRecorder()\n\trtr.ServeHTTP(recorder, req)", "\tif recorder.Code != http.StatusInternalServerError {\n\t\tt.Errorf(\"Unexpected status code %d\", recorder.Code)\n\t}", "\texpected := \"request remote address is empty\"\n\tif expected != strings.TrimSpace(recorder.Body.String()) {\n\t\tt.Errorf(\"Unexpected response body %s\", recorder.Body.String())\n\t}\n}", "func TestParseTokenRequest(t *testing.T) {\n\tconst endpoint = \"http://127.0.0.1/metadata/identity/oauth2/token\"", "\tt.Run(\"query present\", func(t *testing.T) {\n\t\tconst resource = \"https://vault.azure.net\"\n\t\tconst clientID = \"77788899-f67e-42e1-9a78-89985f6bff3e\"\n\t\tconst resourceID = \"/subscriptions/9f2be85c-f8ae-4569-9353-38e5e8b459ef/resourcegroups/test/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test\"", "\t\tvar r http.Request\n\t\tr.URL, _ = url.Parse(fmt.Sprintf(\"%s?client_id=%s&msi_res_id=%s&resource=%s\", endpoint, clientID, resourceID, resource))", "\t\tresult := parseTokenRequest(&r)", "\t\tif result.ClientID != clientID {\n\t\t\tt.Errorf(\"invalid ClientID - expected: %q, actual: %q\", clientID, result.ClientID)\n\t\t}", "\t\tif result.ResourceID != resourceID {\n\t\t\tt.Errorf(\"invalid ResourceID - expected: %q, actual: %q\", resourceID, result.ResourceID)\n\t\t}", "\t\tif result.Resource != resource {\n\t\t\tt.Errorf(\"invalid Resource - expected: %q, actual: %q\", resource, result.Resource)\n\t\t}\n\t})", "\tt.Run(\"bare endpoint\", func(t *testing.T) {\n\t\tvar r http.Request\n\t\tr.URL, _ = url.Parse(endpoint)", "\t\tresult := parseTokenRequest(&r)", "\t\tif result.ClientID != \"\" {\n\t\t\tt.Errorf(\"invalid ClientID - expected: %q, actual: %q\", \"\", result.ClientID)\n\t\t}", "\t\tif result.ResourceID != \"\" {\n\t\t\tt.Errorf(\"invalid ResourceID - expected: %q, actual: %q\", \"\", result.ResourceID)\n\t\t}", "\t\tif result.Resource != \"\" {\n\t\t\tt.Errorf(\"invalid Resource - expected: %q, actual: %q\", \"\", result.Resource)\n\t\t}\n\t})\n}", "func TestTokenRequest_ValidateResourceParamExists(t *testing.T) {\n\ttr := TokenRequest{\n\t\tResource: \"https://vault.azure.net\",\n\t}", "\tif !tr.ValidateResourceParamExists() {\n\t\tt.Error(\"ValidateResourceParamExists should have returned true when the resource is set\")\n\t}", "\ttr.Resource = \"\"\n\tif tr.ValidateResourceParamExists() {\n\t\tt.Error(\"ValidateResourceParamExists should have returned false when the resource is unset\")\n\t}\n}", "func TestRouterPathPrefix(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\turl string\n\t\texpectedStatusCode int\n\t\texpectedBody string\n\t}{\n\t\t{\n\t\t\tname: \"token request\",\n\t\t\turl: \"/metadata/identity/oauth2/token/\",\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"token_request_handler\",\n\t\t},\n\t\t{\n\t\t\tname: \"token request without / suffix\",\n\t\t\turl: \"/metadata/identity/oauth2/token\",\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"token_request_handler\",\n\t\t},\n\t\t{\n\t\t\tname: \"token request with upper case metadata\",\n\t\t\turl: \"/Metadata/identity/oauth2/token/\",\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"token_request_handler\",\n\t\t},\n\t\t{\n\t\t\tname: \"token request with upper case identity\",\n\t\t\turl: \"/metadata/Identity/oauth2/token/\",\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"default_handler\",\n\t\t},\n\t\t{\n\t\t\tname: \"host token request\",\n\t\t\turl: \"/host/token/\",\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"host_token_request_handler\",\n\t\t},\n\t\t{\n\t\t\tname: \"host token request without / suffix\",\n\t\t\turl: \"/host/token\",\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"host_token_request_handler\",\n\t\t},\n\t\t{\n\t\t\tname: \"instance metadata request\",\n\t\t\turl: \"/metadata/instance\",\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"instance_request_handler\",\n\t\t},\n\t\t{\n\t\t\tname: \"instance metadata request with upper case metadata\",\n\t\t\turl: \"/Metadata/instance\",\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"instance_request_handler\",\n\t\t},\n\t\t{\n\t\t\tname: \"instance metadata request / suffix\",\n\t\t\turl: \"/Metadata/instance/\",\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"instance_request_handler\",\n\t\t},\n\t\t{\n\t\t\tname: \"default metadata request\",\n\t\t\turl: \"/metadata/\",\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"default_handler\",\n\t\t},", "", "\t}", "\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tsetup()\n\t\t\tdefer teardown()", "\t\t\trtr.PathPrefix(tokenPathPrefix).HandlerFunc(testTokenHandler)", "", "\t\t\trtr.PathPrefix(hostTokenPathPrefix).HandlerFunc(testHostTokenHandler)\n\t\t\trtr.PathPrefix(instancePathPrefix).HandlerFunc(testInstanceHandler)\n\t\t\trtr.PathPrefix(\"/\").HandlerFunc(testDefaultHandler)", "\t\t\treq, err := http.NewRequest(http.MethodGet, test.url, nil)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}", "\t\t\trecorder := httptest.NewRecorder()\n\t\t\trtr.ServeHTTP(recorder, req)", "\t\t\tif recorder.Code != test.expectedStatusCode {\n\t\t\t\tt.Errorf(\"unexpected status code %d\", recorder.Code)\n\t\t\t}", "\t\t\tif test.expectedBody != strings.TrimSpace(recorder.Body.String()) {\n\t\t\t\tt.Errorf(\"unexpected response body %s\", recorder.Body.String())\n\t\t\t}\n\t\t})\n\t}\n}", "func testTokenHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"token_request_handler\\n\")\n}", "func testHostTokenHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"host_token_request_handler\\n\")\n}", "func testInstanceHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"instance_request_handler\\n\")\n}", "func testDefaultHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"default_handler\\n\")\n}", "" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
PreciseBugs
{"buggy_code_end_loc": [583, 265], "buggy_code_start_loc": [40, 219], "filenames": ["pkg/nmi/server/server.go", "pkg/nmi/server/server_test.go"], "fixing_code_end_loc": [608, 301], "fixing_code_start_loc": [41, 220], "message": "aad-pod-identity assigns Azure Active Directory identities to Kubernetes applications and has now been deprecated as of 24 October 2022. The NMI component in AAD Pod Identity intercepts and validates token requests based on regex. In this case, a token request made with backslash in the request (example: `/metadata/identity\\oauth2\\token/`) would bypass the NMI validation and be sent to IMDS allowing a pod in the cluster to access identities that it shouldn't have access to. This issue has been fixed and has been included in AAD Pod Identity release version 1.8.13. If using the AKS pod-managed identities add-on, no action is required. The clusters should now be running the version 1.8.13 release.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:microsoft:azure_ad_pod_identity:*:*:*:*:*:*:*:*", "matchCriteriaId": "3428D360-1FFE-4291-80B0-9EFB6F173AE6", "versionEndExcluding": "1.8.13", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "aad-pod-identity assigns Azure Active Directory identities to Kubernetes applications and has now been deprecated as of 24 October 2022. The NMI component in AAD Pod Identity intercepts and validates token requests based on regex. In this case, a token request made with backslash in the request (example: `/metadata/identity\\oauth2\\token/`) would bypass the NMI validation and be sent to IMDS allowing a pod in the cluster to access identities that it shouldn't have access to. This issue has been fixed and has been included in AAD Pod Identity release version 1.8.13. If using the AKS pod-managed identities add-on, no action is required. The clusters should now be running the version 1.8.13 release."}], "evaluatorComment": null, "id": "CVE-2022-23551", "lastModified": "2023-01-04T19:54:14.517", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "LOW", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:H/UI:R/S:U/C:L/I:H/A:L", "version": "3.1"}, "exploitabilityScore": 0.6, "impactScore": 4.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "LOW", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:H/UI:R/S:U/C:L/I:H/A:L", "version": "3.1"}, "exploitabilityScore": 0.6, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-12-21T20:15:09.490", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Azure/aad-pod-identity/commit/7e01970391bde6c360d077066ca17d059204cb5d"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Azure/aad-pod-identity/releases/tag/v1.8.13"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Azure/aad-pod-identity/security/advisories/GHSA-p82q-rxpm-hjpc"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-1259"}, {"lang": "en", "value": "CWE-863"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Azure/aad-pod-identity/commit/7e01970391bde6c360d077066ca17d059204cb5d"}, "type": "NVD-CWE-noinfo"}
205
Determine whether the {function_name} code is vulnerable or not.
[ "package server", "import (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"strings\"\n\t\"testing\"", "\t\"github.com/gorilla/mux\"\n)", "var (\n\trtr *mux.Router\n\tserver *httptest.Server\n\ttokenPath = \"/metadata/identity/oauth2/token/\"\n)", "func setup() {\n\trtr = mux.NewRouter()\n\tserver = httptest.NewServer(rtr)\n}", "func teardown() {\n\tserver.Close()\n}", "func TestMsiHandler_NoMetadataHeader(t *testing.T) {\n\tsetup()\n\tdefer teardown()", "\ts := &Server{\n\t\tMetadataHeaderRequired: true,\n\t}\n\trtr.PathPrefix(\"/{type:(?i:metadata)}/identity/oauth2/token/\").Handler(appHandler(s.msiHandler))", "\treq, err := http.NewRequest(http.MethodGet, tokenPath, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}", "\trecorder := httptest.NewRecorder()\n\trtr.ServeHTTP(recorder, req)", "\tif recorder.Code != http.StatusBadRequest {\n\t\tt.Errorf(\"Unexpected status code %d\", recorder.Code)\n\t}", "\tresp := &MetadataResponse{\n\t\tError: \"invalid_request\",\n\t\tErrorDescription: \"Required metadata header not specified\",\n\t}\n\texpected, err := json.Marshal(resp)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}", "\tif string(expected) != strings.TrimSpace(recorder.Body.String()) {\n\t\tt.Errorf(\"Unexpected response body %s\", recorder.Body.String())\n\t}\n}", "func TestMsiHandler_NoRemoteAddress(t *testing.T) {\n\tsetup()\n\tdefer teardown()", "\ts := &Server{\n\t\tMetadataHeaderRequired: false,\n\t}\n\trtr.PathPrefix(\"/{type:(?i:metadata)}/identity/oauth2/token/\").Handler(appHandler(s.msiHandler))", "\treq, err := http.NewRequest(http.MethodGet, tokenPath, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}", "\trecorder := httptest.NewRecorder()\n\trtr.ServeHTTP(recorder, req)", "\tif recorder.Code != http.StatusInternalServerError {\n\t\tt.Errorf(\"Unexpected status code %d\", recorder.Code)\n\t}", "\texpected := \"request remote address is empty\"\n\tif expected != strings.TrimSpace(recorder.Body.String()) {\n\t\tt.Errorf(\"Unexpected response body %s\", recorder.Body.String())\n\t}\n}", "func TestParseTokenRequest(t *testing.T) {\n\tconst endpoint = \"http://127.0.0.1/metadata/identity/oauth2/token\"", "\tt.Run(\"query present\", func(t *testing.T) {\n\t\tconst resource = \"https://vault.azure.net\"\n\t\tconst clientID = \"77788899-f67e-42e1-9a78-89985f6bff3e\"\n\t\tconst resourceID = \"/subscriptions/9f2be85c-f8ae-4569-9353-38e5e8b459ef/resourcegroups/test/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test\"", "\t\tvar r http.Request\n\t\tr.URL, _ = url.Parse(fmt.Sprintf(\"%s?client_id=%s&msi_res_id=%s&resource=%s\", endpoint, clientID, resourceID, resource))", "\t\tresult := parseTokenRequest(&r)", "\t\tif result.ClientID != clientID {\n\t\t\tt.Errorf(\"invalid ClientID - expected: %q, actual: %q\", clientID, result.ClientID)\n\t\t}", "\t\tif result.ResourceID != resourceID {\n\t\t\tt.Errorf(\"invalid ResourceID - expected: %q, actual: %q\", resourceID, result.ResourceID)\n\t\t}", "\t\tif result.Resource != resource {\n\t\t\tt.Errorf(\"invalid Resource - expected: %q, actual: %q\", resource, result.Resource)\n\t\t}\n\t})", "\tt.Run(\"bare endpoint\", func(t *testing.T) {\n\t\tvar r http.Request\n\t\tr.URL, _ = url.Parse(endpoint)", "\t\tresult := parseTokenRequest(&r)", "\t\tif result.ClientID != \"\" {\n\t\t\tt.Errorf(\"invalid ClientID - expected: %q, actual: %q\", \"\", result.ClientID)\n\t\t}", "\t\tif result.ResourceID != \"\" {\n\t\t\tt.Errorf(\"invalid ResourceID - expected: %q, actual: %q\", \"\", result.ResourceID)\n\t\t}", "\t\tif result.Resource != \"\" {\n\t\t\tt.Errorf(\"invalid Resource - expected: %q, actual: %q\", \"\", result.Resource)\n\t\t}\n\t})\n}", "func TestTokenRequest_ValidateResourceParamExists(t *testing.T) {\n\ttr := TokenRequest{\n\t\tResource: \"https://vault.azure.net\",\n\t}", "\tif !tr.ValidateResourceParamExists() {\n\t\tt.Error(\"ValidateResourceParamExists should have returned true when the resource is set\")\n\t}", "\ttr.Resource = \"\"\n\tif tr.ValidateResourceParamExists() {\n\t\tt.Error(\"ValidateResourceParamExists should have returned false when the resource is unset\")\n\t}\n}", "func TestRouterPathPrefix(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\turl string\n\t\texpectedStatusCode int\n\t\texpectedBody string\n\t}{\n\t\t{\n\t\t\tname: \"token request\",\n\t\t\turl: \"/metadata/identity/oauth2/token/\",\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"token_request_handler\",\n\t\t},\n\t\t{\n\t\t\tname: \"token request without / suffix\",\n\t\t\turl: \"/metadata/identity/oauth2/token\",\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"token_request_handler\",\n\t\t},\n\t\t{\n\t\t\tname: \"token request with upper case metadata\",\n\t\t\turl: \"/Metadata/identity/oauth2/token/\",\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"token_request_handler\",\n\t\t},\n\t\t{\n\t\t\tname: \"token request with upper case identity\",\n\t\t\turl: \"/metadata/Identity/oauth2/token/\",\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"default_handler\",\n\t\t},\n\t\t{\n\t\t\tname: \"host token request\",\n\t\t\turl: \"/host/token/\",\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"host_token_request_handler\",\n\t\t},\n\t\t{\n\t\t\tname: \"host token request without / suffix\",\n\t\t\turl: \"/host/token\",\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"host_token_request_handler\",\n\t\t},\n\t\t{\n\t\t\tname: \"instance metadata request\",\n\t\t\turl: \"/metadata/instance\",\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"instance_request_handler\",\n\t\t},\n\t\t{\n\t\t\tname: \"instance metadata request with upper case metadata\",\n\t\t\turl: \"/Metadata/instance\",\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"instance_request_handler\",\n\t\t},\n\t\t{\n\t\t\tname: \"instance metadata request / suffix\",\n\t\t\turl: \"/Metadata/instance/\",\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"instance_request_handler\",\n\t\t},\n\t\t{\n\t\t\tname: \"default metadata request\",\n\t\t\turl: \"/metadata/\",\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"default_handler\",\n\t\t},", "\t\t{\n\t\t\tname: \"invalid token request with \\\\oauth2\",\n\t\t\turl: `/metadata/identity\\oauth2/token/`,\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"invalid_request_handler\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid token request with \\\\token\",\n\t\t\turl: `/metadata/identity/oauth2\\token/`,\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"invalid_request_handler\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid token request with \\\\oauth2\\\\token\",\n\t\t\turl: `/metadata/identity\\oauth2\\token/`,\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"invalid_request_handler\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid token request with mix of / and \\\\\",\n\t\t\turl: `/metadata/identity/\\oauth2\\token/`,\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"invalid_request_handler\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid token request with multiple \\\\\",\n\t\t\turl: `/metadata/identity\\\\\\oauth2\\\\token/`,\n\t\t\texpectedStatusCode: http.StatusOK,\n\t\t\texpectedBody: \"invalid_request_handler\",\n\t\t},", "\t}", "\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tsetup()\n\t\t\tdefer teardown()", "\t\t\trtr.PathPrefix(tokenPathPrefix).HandlerFunc(testTokenHandler)", "\t\t\trtr.MatcherFunc(invalidTokenPathMatcher).HandlerFunc(testInvalidRequestHandler)", "\t\t\trtr.PathPrefix(hostTokenPathPrefix).HandlerFunc(testHostTokenHandler)\n\t\t\trtr.PathPrefix(instancePathPrefix).HandlerFunc(testInstanceHandler)\n\t\t\trtr.PathPrefix(\"/\").HandlerFunc(testDefaultHandler)", "\t\t\treq, err := http.NewRequest(http.MethodGet, test.url, nil)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}", "\t\t\trecorder := httptest.NewRecorder()\n\t\t\trtr.ServeHTTP(recorder, req)", "\t\t\tif recorder.Code != test.expectedStatusCode {\n\t\t\t\tt.Errorf(\"unexpected status code %d\", recorder.Code)\n\t\t\t}", "\t\t\tif test.expectedBody != strings.TrimSpace(recorder.Body.String()) {\n\t\t\t\tt.Errorf(\"unexpected response body %s\", recorder.Body.String())\n\t\t\t}\n\t\t})\n\t}\n}", "func testTokenHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"token_request_handler\\n\")\n}", "func testHostTokenHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"host_token_request_handler\\n\")\n}", "func testInstanceHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"instance_request_handler\\n\")\n}", "func testDefaultHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"default_handler\\n\")\n}", "\nfunc testInvalidRequestHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"invalid_request_handler\\n\")\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [583, 265], "buggy_code_start_loc": [40, 219], "filenames": ["pkg/nmi/server/server.go", "pkg/nmi/server/server_test.go"], "fixing_code_end_loc": [608, 301], "fixing_code_start_loc": [41, 220], "message": "aad-pod-identity assigns Azure Active Directory identities to Kubernetes applications and has now been deprecated as of 24 October 2022. The NMI component in AAD Pod Identity intercepts and validates token requests based on regex. In this case, a token request made with backslash in the request (example: `/metadata/identity\\oauth2\\token/`) would bypass the NMI validation and be sent to IMDS allowing a pod in the cluster to access identities that it shouldn't have access to. This issue has been fixed and has been included in AAD Pod Identity release version 1.8.13. If using the AKS pod-managed identities add-on, no action is required. The clusters should now be running the version 1.8.13 release.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:microsoft:azure_ad_pod_identity:*:*:*:*:*:*:*:*", "matchCriteriaId": "3428D360-1FFE-4291-80B0-9EFB6F173AE6", "versionEndExcluding": "1.8.13", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "aad-pod-identity assigns Azure Active Directory identities to Kubernetes applications and has now been deprecated as of 24 October 2022. The NMI component in AAD Pod Identity intercepts and validates token requests based on regex. In this case, a token request made with backslash in the request (example: `/metadata/identity\\oauth2\\token/`) would bypass the NMI validation and be sent to IMDS allowing a pod in the cluster to access identities that it shouldn't have access to. This issue has been fixed and has been included in AAD Pod Identity release version 1.8.13. If using the AKS pod-managed identities add-on, no action is required. The clusters should now be running the version 1.8.13 release."}], "evaluatorComment": null, "id": "CVE-2022-23551", "lastModified": "2023-01-04T19:54:14.517", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "LOW", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:H/UI:R/S:U/C:L/I:H/A:L", "version": "3.1"}, "exploitabilityScore": 0.6, "impactScore": 4.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "LOW", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:H/UI:R/S:U/C:L/I:H/A:L", "version": "3.1"}, "exploitabilityScore": 0.6, "impactScore": 4.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-12-21T20:15:09.490", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Azure/aad-pod-identity/commit/7e01970391bde6c360d077066ca17d059204cb5d"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Azure/aad-pod-identity/releases/tag/v1.8.13"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/Azure/aad-pod-identity/security/advisories/GHSA-p82q-rxpm-hjpc"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-1259"}, {"lang": "en", "value": "CWE-863"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Azure/aad-pod-identity/commit/7e01970391bde6c360d077066ca17d059204cb5d"}, "type": "NVD-CWE-noinfo"}
205
Determine whether the {function_name} code is vulnerable or not.
[ "/* radare - LGPL - Copyright 2018 - pancake */", "\n#include <r_types.h>\n#include <r_util.h>\n#include <r_lib.h>\n#include <r_bin.h>\n#include <ht_uu.h>\n#include \"../i/private.h\"\n#include \"mach0/coresymbolication.h\"", "// enable debugging messages\n#define D if (0)\n#define R_UUID_LENGTH 33", "typedef struct symbols_header_t {\n\tut32 magic;\n\tut32 version;\n\tut8 uuid[16];\n\tut32 unk0;\n\tut32 unk1;\n\tut32 slotsize;\n\tut32 addr;\n\tbool valid;\n\tint size;\n} SymbolsHeader;", "typedef struct symbols_metadata_t { // 0x40\n\tut32 cputype;\n\tut32 subtype;\n\tut32 n_segments;\n\tut32 namelen;\n\tut32 name;\n\tbool valid;\n\tut32 size;\n\t//RList *segments;\n\tut32 addr;\n\tint bits;\n\tconst char *arch;\n\tconst char *cpu;\n} SymbolsMetadata;", "// header starts at offset 0 and ends at offset 0x40\nstatic SymbolsHeader parseHeader(RBuffer *buf) {\n\tut8 b[64];\n\tSymbolsHeader sh = { 0 };\n\t(void)r_buf_read_at (buf, 0, b, sizeof (b));\n\tsh.magic = r_read_le32 (b);\n\tsh.version = r_read_le32 (b + 4);\n\tsh.valid = sh.magic == 0xff01ff02;\n\tint i;\n\tfor (i = 0; i < 16; i++) {\n\t\tsh.uuid[i] = b[24 + i];\n\t}\n\tsh.unk0 = r_read_le16 (b + 0x28);\n\tsh.unk1 = r_read_le16 (b + 0x2c); // is slotsize + 1 :?\n\tsh.slotsize = r_read_le16 (b + 0x2e);\n\tsh.size = 0x40;\n\treturn sh;\n}", "static const char *typeString(ut32 n, int *bits) {\n\t*bits = 32;\n\tif (n == 12) { // CPU_SUBTYPE_ARM_V7) {\n\t\treturn \"arm\";\n\t}\n\tif (n == 0x0100000c) { // arm64\n\t\t*bits = 64;\n\t\treturn \"arm\";\n\t}\n\tif (n == 0x0200000c) { // arm64-32\n\t\t// TODO: must change bits\n\t\t*bits = 64;\n\t\treturn \"arm\";\n\t}\n\treturn \"x86\";\n}", "static const char *subtypeString(int n) {\n\tif (n == 9) { // CPU_SUBTYPE_ARM_V7) {\n\t\treturn \"armv7\";\n\t}\n\treturn \"?\";\n}", "// metadata section starts at offset 0x40 and ends around 0xb0 depending on filenamelength\nstatic SymbolsMetadata parseMetadata(RBuffer *buf, int off) {\n\tSymbolsMetadata sm = { 0 };\n\tut8 b[0x100] = { 0 };\n\t(void)r_buf_read_at (buf, off, b, sizeof (b));\n\tsm.addr = off;\n\tsm.cputype = r_read_le32 (b);\n\tsm.arch = typeString (sm.cputype, &sm.bits);\n\t// eprintf (\"0x%08x cputype 0x%x -> %s\\n\", 0x40, sm.cputype, typeString (sm.cputype));\n\t// bits = (strstr (typeString (sm.cputype, &sm.bits), \"64\"))? 64: 32;\n\tsm.subtype = r_read_le32 (b + 4);\n\tsm.cpu = subtypeString (sm.subtype);\n\t// eprintf (\"0x%08x subtype 0x%x -> %s\\n\", 0x44, sm.subtype, subtypeString (sm.subtype));\n\tsm.n_segments = r_read_le32 (b + 8);\n\t// int count = r_read_le32 (b + 0x48);\n\tsm.namelen = r_read_le32 (b + 0xc);\n\t// eprintf (\"0x%08x count %d\\n\", 0x48, count);\n\t// eprintf (\"0x%08x strlen %d\\n\", 0x4c, sm.namelen);\n\t// eprintf (\"0x%08x filename %s\\n\", 0x50, b + 16);\n\tint delta = 16;\n\t//sm.segments = parseSegments (buf, off + sm.namelen + delta, sm.n_segments);\n\tsm.size = (sm.n_segments * 32) + sm.namelen + delta;", "\t// hack to detect format\n\tut32 nm, nm2, nm3;\n\tr_buf_read_at (buf, off + sm.size, (ut8 *)&nm, sizeof (nm));\n\tr_buf_read_at (buf, off + sm.size + 4, (ut8 *)&nm2, sizeof (nm2));\n\tr_buf_read_at (buf, off + sm.size + 8, (ut8 *)&nm3, sizeof (nm3));\n\t// eprintf (\"0x%x next %x %x %x\\n\", off + sm.size, nm, nm2, nm3);\n\tif (r_read_le32 (&nm3) != 0xa1b22b1a) {\n\t\tsm.size -= 8;\n\t\t//\t\tis64 = true;\n\t}\n\treturn sm;\n}", "static RBinSection *bin_section_from_section(RCoreSymCacheElementSection *sect) {\n\tif (!sect->name) {\n\t\treturn NULL;\n\t}\n\tRBinSection *s = R_NEW0 (RBinSection);\n\tif (!s) {\n\t\treturn NULL;\n\t}\n\ts->name = r_str_ndup (sect->name, 256);\n\ts->size = sect->size;\n\ts->vsize = s->size;\n\ts->paddr = sect->paddr;\n\ts->vaddr = sect->vaddr;\n\ts->add = true;\n\ts->perm = strstr (s->name, \"TEXT\") ? 5 : 4;\n\ts->is_segment = false;\n\treturn s;\n}", "static RBinSection *bin_section_from_segment(RCoreSymCacheElementSegment *seg) {\n\tif (!seg->name) {\n\t\treturn NULL;\n\t}\n\tRBinSection *s = R_NEW0 (RBinSection);\n\tif (!s) {\n\t\treturn NULL;\n\t}\n\ts->name = r_str_ndup (seg->name, 16);\n\ts->size = seg->size;\n\ts->vsize = seg->vsize;\n\ts->paddr = seg->paddr;\n\ts->vaddr = seg->vaddr;\n\ts->add = true;\n\ts->perm = strstr (s->name, \"TEXT\") ? 5 : 4;\n\ts->is_segment = true;\n\treturn s;\n}", "static RBinSymbol *bin_symbol_from_symbol(RCoreSymCacheElement *element, RCoreSymCacheElementSymbol *s) {\n\tif (!s->name && !s->mangled_name) {\n\t\treturn NULL;\n\t}\n\tRBinSymbol *sym = R_NEW0 (RBinSymbol);\n\tif (sym) {\n\t\tif (s->name && s->mangled_name) {\n\t\t\tsym->dname = strdup (s->name);\n\t\t\tsym->name = strdup (s->mangled_name);\n\t\t} else if (s->name) {\n\t\t\tsym->name = strdup (s->name);\n\t\t} else if (s->mangled_name) {\n\t\t\tsym->name = s->mangled_name;\n\t\t}\n\t\tsym->paddr = s->paddr;\n\t\tsym->vaddr = r_coresym_cache_element_pa2va (element, s->paddr);\n\t\tsym->size = s->size;\n\t\tsym->type = R_BIN_TYPE_FUNC_STR;\n\t\tsym->bind = \"NONE\";\n\t}\n\treturn sym;\n}", "static RCoreSymCacheElement *parseDragons(RBinFile *bf, RBuffer *buf, int off, int bits, R_OWN char *file_name) {\n\tD eprintf (\"Dragons at 0x%x\\n\", off);\n\tut64 size = r_buf_size (buf);\n\tif (off >= size) {\n\t\treturn NULL;\n\t}\n\tsize -= off;\n\tif (!size) {\n\t\treturn NULL;\n\t}\n\tut8 *b = malloc (size);\n\tif (!b) {\n\t\treturn NULL;\n\t}\n\tint available = r_buf_read_at (buf, off, b, size);\n\tif (available != size) {\n\t\teprintf (\"Warning: r_buf_read_at failed\\n\");\n\t\treturn NULL;\n\t}\n#if 0\n\t// after the list of sections, there's a bunch of unknown\n\t// data, brobably dwords, and then the same section list again\n\t// this function aims to parse it.\n\t0x00000138 |1a2b b2a1 0300 0000 1a2b b2a1 e055 0000| .+.......+...U..\n n_segments ----. .--- how many sections ?\n\t0x00000148 |0100 0000 ca55 0000 0400 0000 1800 0000| .....U..........\n\t .---- how many symbols? 0xc7\n\t0x00000158 |c700 0000 0000 0000 0000 0000 0104 0000| ................\n\t0x00000168 |250b e803 0000 0100 0000 0000 bd55 0000| %............U..\n\t0x00000178 |91bb e903 e35a b42c 93a4 340a 8746 9489| .....Z.,..4..F..\n\t0x00000188 |0cea 4c40 0c00 0000 0900 0000 0000 0000| ..L@............\n\t0x00000198 |0000 0000 0000 0000 0000 0000 0000 0000| ................\n\t0x000001a8 |0080 0000 0000 0000 5f5f 5445 5854 0000| ........__TEXT..\n\t0x000001b8 |0000 0000 0000 0000 0080 0000 0000 0000| ................\n\t0x000001c8 |0040 0000 0000 0000 5f5f 4441 5441 0000| .@......__DATA..\n\t0x000001d8 |0000 0000 0000 0000 00c0 0000 0000 0000| ................\n\t0x000001e8 |0000 0100 0000 0000 5f5f 4c4c 564d 0000| ........__LLVM..\n\t0x000001f8 |0000 0000 0000 0000 00c0 0100 0000 0000| ................\n\t0x00000208 |00c0 0000 0000 0000 5f5f 4c49 4e4b 4544| ........__LINKED\n\t0x00000218 |4954 0000 0000 0000 0000 0000 d069 0000| IT...........i..\n#endif\n\t// eprintf (\"Dragon's magic:\\n\");\n\tint magicCombo = 0;\n\tif (!memcmp (\"\\x1a\\x2b\\xb2\\xa1\", b, 4)) { // 0x130 ?\n\t\tmagicCombo++;\n\t}\n\tif (!memcmp (\"\\x1a\\x2b\\xb2\\xa1\", b + 8, 4)) {\n\t\tmagicCombo++;\n\t}\n\tif (magicCombo != 2) {\n\t\t// hack for C22F7494\n\t\tavailable = r_buf_read_at (buf, off - 8, b, size);\n\t\tif (available != size) {\n\t\t\teprintf (\"Warning: r_buf_read_at failed\\n\");\n\t\t\treturn NULL;\n\t\t}\n\t\tif (!memcmp (\"\\x1a\\x2b\\xb2\\xa1\", b, 4)) { // 0x130 ?\n\t\t\toff -= 8;\n\t\t} else {\n\t\t\teprintf (\"0x%08x parsing error: invalid magic retry\\n\", off);\n\t\t}\n\t}\n\tD eprintf (\"0x%08x magic OK\\n\", off);\n\tD {\n\t\tconst int e0ss = r_read_le32 (b + 12);\n\t\teprintf (\"0x%08x eoss 0x%x\\n\", off + 12, e0ss);\n\t}\n\tfree (b);\n\treturn r_coresym_cache_element_new (bf, buf, off + 16, bits, file_name);\n}", "static bool load_buffer(RBinFile *bf, void **bin_obj, RBuffer *buf, ut64 loadaddr, Sdb *sdb) {\n#if 0\n\tSYMBOLS HEADER", " 0\tMAGIC\t02ff01ff\n 4\tVERSION 1 (little endian)\n 8 ffffffff\n16 002b0000 01000000 { 0x2b00, 0x0000 }\n24\tUUID 16 bytes\n40\t2621 d85b 2100 2000 0000 0000 0000 0000\n56\tffff ffff ffff ff7f 0c00 0000 0900 0000\n72\t0400 0000 6800 0000 2f76 6172 2f66 6f6c .... 4, 104 /// 104 length string\n184\n0x000000b8 5f5f 5445 5854 0000 0000 0000 0000 0000 0000 0000 0000 0000 0080 0000 0000 0000 __TEXT..........................\n0x000000d8 5f5f 4441 5441 0000 0000 0000 0000 0000 0080 0000 0000 0000 0040 0000 0000 0000 __DATA...................@......\n0x000000f8 5f5f 4c4c 564d 0000 0000 0000 0000 0000 00c0 0000 0000 0000 0000 0100 0000 0000 __LLVM..........................\n0x00000118 5f5f 4c49 4e4b 4544 4954 0000 0000 0000 00c0 0100 0000 0000 00c0 0000 0000 0000 __LINKEDIT......................", "#endif\n\t// 0 - magic check, version ...\n\tSymbolsHeader sh = parseHeader (buf);\n\tif (!sh.valid) {\n\t\teprintf (\"Invalid headers\\n\");\n\t\treturn false;\n\t}\n\tSymbolsMetadata sm = parseMetadata (buf, 0x40);\n\tchar * file_name = NULL;\n\tif (sm.namelen) {\n\t\tfile_name = calloc (sm.namelen + 1, 1);\n\t\tif (!file_name) {\n\t\t\treturn false;\n\t\t}\n\t\tif (r_buf_read_at (buf, 0x50, (ut8*)file_name, sm.namelen) != sm.namelen) {\n\t\t\treturn false;\n\t\t}\n\t}\n\tRCoreSymCacheElement *element = parseDragons (bf, buf, sm.addr + sm.size, sm.bits, file_name);\n\tif (element) {\n\t\t*bin_obj = element;\n\t\treturn true;\n\t}\n\tfree (file_name);\n\treturn false;\n}", "static RList *sections(RBinFile *bf) {\n\tRList *res = r_list_newf ((RListFree)r_bin_section_free);\n\tr_return_val_if_fail (res && bf->o && bf->o->bin_obj, res);\n\tRCoreSymCacheElement *element = bf->o->bin_obj;\n\tsize_t i;\n\tif (element->segments) {\n\t\tfor (i = 0; i < element->hdr->n_segments; i++) {\n\t\t\tRCoreSymCacheElementSegment *seg = &element->segments[i];\n\t\t\tRBinSection *s = bin_section_from_segment (seg);\n\t\t\tif (s) {\n\t\t\t\tr_list_append (res, s);\n\t\t\t}\n\t\t}\n\t}\n\tif (element->sections) {\n\t\tfor (i = 0; i < element->hdr->n_sections; i++) {\n\t\t\tRCoreSymCacheElementSection *sect = &element->sections[i];\n\t\t\tRBinSection *s = bin_section_from_section (sect);\n\t\t\tif (s) {\n\t\t\t\tr_list_append (res, s);\n\t\t\t}\n\t\t}\n\t}\n\treturn res;\n}", "static ut64 baddr(RBinFile *bf) {\n\treturn 0LL;\n}", "static RBinInfo *info(RBinFile *bf) {\n\tSymbolsMetadata sm = parseMetadata (bf->buf, 0x40);\n\tRBinInfo *ret = R_NEW0 (RBinInfo);\n\tif (!ret) {\n\t\treturn NULL;\n\t}\n\tret->file = strdup (bf->file);\n\tret->bclass = strdup (\"symbols\");\n\tret->os = strdup (\"unknown\");\n\tret->arch = sm.arch ? strdup (sm.arch) : NULL;\n\tret->bits = sm.bits;\n\tret->type = strdup (\"Symbols file\");\n\tret->subsystem = strdup (\"llvm\");\n\tret->has_va = true;", "\treturn ret;\n}", "static bool check_buffer(RBinFile *bf, RBuffer *b) {\n\tut8 buf[4];\n\tr_buf_read_at (b, 0, buf, sizeof (buf));\n\treturn !memcmp (buf, \"\\x02\\xff\\x01\\xff\", 4);\n}", "static RList *symbols(RBinFile *bf) {\n\tRList *res = r_list_newf ((RListFree)r_bin_symbol_free);\n\tr_return_val_if_fail (res && bf->o && bf->o->bin_obj, res);\n\tRCoreSymCacheElement *element = bf->o->bin_obj;\n\tsize_t i;\n\tHtUU *hash = ht_uu_new0 ();\n\tif (!hash) {\n\t\treturn res;\n\t}\n\tbool found = false;\n\tfor (i = 0; i < element->hdr->n_lined_symbols; i++) {\n\t\tRCoreSymCacheElementSymbol *sym = (RCoreSymCacheElementSymbol *)&element->lined_symbols[i];", "", "\t\tht_uu_find (hash, sym->paddr, &found);\n\t\tif (found) {\n\t\t\tcontinue;\n\t\t}\n\t\tRBinSymbol *s = bin_symbol_from_symbol (element, sym);\n\t\tif (s) {\n\t\t\tr_list_append (res, s);\n\t\t\tht_uu_insert (hash, sym->paddr, 1);\n\t\t}\n\t}\n\tif (element->symbols) {\n\t\tfor (i = 0; i < element->hdr->n_symbols; i++) {\n\t\t\tRCoreSymCacheElementSymbol *sym = &element->symbols[i];\n\t\t\tht_uu_find (hash, sym->paddr, &found);\n\t\t\tif (found) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tRBinSymbol *s = bin_symbol_from_symbol (element, sym);\n\t\t\tif (s) {\n\t\t\t\tr_list_append (res, s);\n\t\t\t}\n\t\t}\n\t}\n\tht_uu_free (hash);\n\treturn res;\n}", "static ut64 size(RBinFile *bf) {\n\treturn UT64_MAX;\n}", "static void destroy(RBinFile *bf) {\n\tr_coresym_cache_element_free (bf->o->bin_obj);\n}", "static void header(RBinFile *bf) {\n\tr_return_if_fail (bf && bf->o);", "\tRCoreSymCacheElement *element = bf->o->bin_obj;\n\tif (!element) {\n\t\treturn;\n\t}", "\tRBin *bin = bf->rbin;\n\tPrintfCallback p = bin->cb_printf;\n\tPJ *pj = pj_new ();\n\tif (!pj) {\n\t\treturn;\n\t}", "\tpj_o (pj);\n\tpj_kn (pj, \"cs_version\", element->hdr->version);\n\tpj_kn (pj, \"size\", element->hdr->size);\n\tif (element->file_name) {\n\t\tpj_ks (pj, \"name\", element->file_name);\n\t}\n\tif (element->binary_version) {\n\t\tpj_ks (pj, \"version\", element->binary_version);\n\t}\n\tchar uuidstr[R_UUID_LENGTH];\n\tr_hex_bin2str (element->hdr->uuid, 16, uuidstr);\n\tpj_ks (pj, \"uuid\", uuidstr);\n\tpj_kn (pj, \"segments\", element->hdr->n_segments);\n\tpj_kn (pj, \"sections\", element->hdr->n_sections);\n\tpj_kn (pj, \"symbols\", element->hdr->n_symbols);\n\tpj_kn (pj, \"lined_symbols\", element->hdr->n_lined_symbols);\n\tpj_kn (pj, \"line_info\", element->hdr->n_line_info);\n\tpj_end (pj);", "\tp (\"%s\\n\", pj_string (pj));\n\tpj_free (pj);\n}", "RBinPlugin r_bin_plugin_symbols = {\n\t.name = \"symbols\",\n\t.desc = \"Apple Symbols file\",\n\t.license = \"MIT\",\n\t.load_buffer = &load_buffer,\n\t.check_buffer = &check_buffer,\n\t.symbols = &symbols,\n\t.sections = &sections,\n\t.size = &size,\n\t.baddr = &baddr,\n\t.info = &info,\n\t.header = &header,\n\t.destroy = &destroy,\n};", "#ifndef R2_PLUGIN_INCORE\nR_API RLibStruct radare_plugin = {\n\t.type = R_LIB_TYPE_BIN,\n\t.data = &r_bin_plugin_symbols,\n\t.version = R2_VERSION\n};\n#endif" ]
[ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [363], "buggy_code_start_loc": [1], "filenames": ["libr/bin/p/bin_symbols.c"], "fixing_code_end_loc": [367], "fixing_code_start_loc": [1], "message": "NULL Pointer Dereference in GitHub repository radareorg/radare2 prior to 5.6.4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:radare:radare2:*:*:*:*:*:*:*:*", "matchCriteriaId": "257C5522-E8C9-42F8-8891-50EDBDD3E873", "versionEndExcluding": "5.6.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:35:*:*:*:*:*:*:*", "matchCriteriaId": "80E516C0-98A4-4ADE-B69F-66A772E2BAAA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:36:*:*:*:*:*:*:*", "matchCriteriaId": "5C675112-476C-4D7C-BCB9-A2FB2D0BC9FD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "NULL Pointer Dereference in GitHub repository radareorg/radare2 prior to 5.6.4."}, {"lang": "es", "value": "Una Desreferencia de puntero NULL en el repositorio de GitHub radareorg/radare2 versiones anteriores a 5.6.4"}], "evaluatorComment": null, "id": "CVE-2022-0712", "lastModified": "2022-04-08T13:53:57.093", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 7.1, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:C", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "LOW", "baseScore": 5.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 3.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-02-22T18:15:12.487", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/radareorg/radare2/commit/515e592b9bea0612bc63d8e93239ff35bcf645c7"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/1e572820-e502-49d1-af0e-81833e2eb466"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/BZTIMAS53YT66FUS4QHQAFRJOBMUFG6D/"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/E6YBRQ3UCFWJVSOYIKPVUDASZ544TFND/"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-476"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/radareorg/radare2/commit/515e592b9bea0612bc63d8e93239ff35bcf645c7"}, "type": "CWE-476"}
206
Determine whether the {function_name} code is vulnerable or not.
[ "/* radare - LGPL - Copyright 2018-2022 - pancake */", "\n#include <r_types.h>\n#include <r_util.h>\n#include <r_lib.h>\n#include <r_bin.h>\n#include <ht_uu.h>\n#include \"../i/private.h\"\n#include \"mach0/coresymbolication.h\"", "// enable debugging messages\n#define D if (0)\n#define R_UUID_LENGTH 33", "typedef struct symbols_header_t {\n\tut32 magic;\n\tut32 version;\n\tut8 uuid[16];\n\tut32 unk0;\n\tut32 unk1;\n\tut32 slotsize;\n\tut32 addr;\n\tbool valid;\n\tint size;\n} SymbolsHeader;", "typedef struct symbols_metadata_t { // 0x40\n\tut32 cputype;\n\tut32 subtype;\n\tut32 n_segments;\n\tut32 namelen;\n\tut32 name;\n\tbool valid;\n\tut32 size;\n\t//RList *segments;\n\tut32 addr;\n\tint bits;\n\tconst char *arch;\n\tconst char *cpu;\n} SymbolsMetadata;", "// header starts at offset 0 and ends at offset 0x40\nstatic SymbolsHeader parseHeader(RBuffer *buf) {\n\tut8 b[64];\n\tSymbolsHeader sh = { 0 };\n\t(void)r_buf_read_at (buf, 0, b, sizeof (b));\n\tsh.magic = r_read_le32 (b);\n\tsh.version = r_read_le32 (b + 4);\n\tsh.valid = sh.magic == 0xff01ff02;\n\tint i;\n\tfor (i = 0; i < 16; i++) {\n\t\tsh.uuid[i] = b[24 + i];\n\t}\n\tsh.unk0 = r_read_le16 (b + 0x28);\n\tsh.unk1 = r_read_le16 (b + 0x2c); // is slotsize + 1 :?\n\tsh.slotsize = r_read_le16 (b + 0x2e);\n\tsh.size = 0x40;\n\treturn sh;\n}", "static const char *typeString(ut32 n, int *bits) {\n\t*bits = 32;\n\tif (n == 12) { // CPU_SUBTYPE_ARM_V7) {\n\t\treturn \"arm\";\n\t}\n\tif (n == 0x0100000c) { // arm64\n\t\t*bits = 64;\n\t\treturn \"arm\";\n\t}\n\tif (n == 0x0200000c) { // arm64-32\n\t\t// TODO: must change bits\n\t\t*bits = 64;\n\t\treturn \"arm\";\n\t}\n\treturn \"x86\";\n}", "static const char *subtypeString(int n) {\n\tif (n == 9) { // CPU_SUBTYPE_ARM_V7) {\n\t\treturn \"armv7\";\n\t}\n\treturn \"?\";\n}", "// metadata section starts at offset 0x40 and ends around 0xb0 depending on filenamelength\nstatic SymbolsMetadata parseMetadata(RBuffer *buf, int off) {\n\tSymbolsMetadata sm = { 0 };\n\tut8 b[0x100] = { 0 };\n\t(void)r_buf_read_at (buf, off, b, sizeof (b));\n\tsm.addr = off;\n\tsm.cputype = r_read_le32 (b);\n\tsm.arch = typeString (sm.cputype, &sm.bits);\n\t// eprintf (\"0x%08x cputype 0x%x -> %s\\n\", 0x40, sm.cputype, typeString (sm.cputype));\n\t// bits = (strstr (typeString (sm.cputype, &sm.bits), \"64\"))? 64: 32;\n\tsm.subtype = r_read_le32 (b + 4);\n\tsm.cpu = subtypeString (sm.subtype);\n\t// eprintf (\"0x%08x subtype 0x%x -> %s\\n\", 0x44, sm.subtype, subtypeString (sm.subtype));\n\tsm.n_segments = r_read_le32 (b + 8);\n\t// int count = r_read_le32 (b + 0x48);\n\tsm.namelen = r_read_le32 (b + 0xc);\n\t// eprintf (\"0x%08x count %d\\n\", 0x48, count);\n\t// eprintf (\"0x%08x strlen %d\\n\", 0x4c, sm.namelen);\n\t// eprintf (\"0x%08x filename %s\\n\", 0x50, b + 16);\n\tint delta = 16;\n\t//sm.segments = parseSegments (buf, off + sm.namelen + delta, sm.n_segments);\n\tsm.size = (sm.n_segments * 32) + sm.namelen + delta;", "\t// hack to detect format\n\tut32 nm, nm2, nm3;\n\tr_buf_read_at (buf, off + sm.size, (ut8 *)&nm, sizeof (nm));\n\tr_buf_read_at (buf, off + sm.size + 4, (ut8 *)&nm2, sizeof (nm2));\n\tr_buf_read_at (buf, off + sm.size + 8, (ut8 *)&nm3, sizeof (nm3));\n\t// eprintf (\"0x%x next %x %x %x\\n\", off + sm.size, nm, nm2, nm3);\n\tif (r_read_le32 (&nm3) != 0xa1b22b1a) {\n\t\tsm.size -= 8;\n\t\t//\t\tis64 = true;\n\t}\n\treturn sm;\n}", "static RBinSection *bin_section_from_section(RCoreSymCacheElementSection *sect) {\n\tif (!sect->name) {\n\t\treturn NULL;\n\t}\n\tRBinSection *s = R_NEW0 (RBinSection);\n\tif (!s) {\n\t\treturn NULL;\n\t}\n\ts->name = r_str_ndup (sect->name, 256);\n\ts->size = sect->size;\n\ts->vsize = s->size;\n\ts->paddr = sect->paddr;\n\ts->vaddr = sect->vaddr;\n\ts->add = true;\n\ts->perm = strstr (s->name, \"TEXT\") ? 5 : 4;\n\ts->is_segment = false;\n\treturn s;\n}", "static RBinSection *bin_section_from_segment(RCoreSymCacheElementSegment *seg) {\n\tif (!seg->name) {\n\t\treturn NULL;\n\t}\n\tRBinSection *s = R_NEW0 (RBinSection);\n\tif (!s) {\n\t\treturn NULL;\n\t}\n\ts->name = r_str_ndup (seg->name, 16);\n\ts->size = seg->size;\n\ts->vsize = seg->vsize;\n\ts->paddr = seg->paddr;\n\ts->vaddr = seg->vaddr;\n\ts->add = true;\n\ts->perm = strstr (s->name, \"TEXT\") ? 5 : 4;\n\ts->is_segment = true;\n\treturn s;\n}", "static RBinSymbol *bin_symbol_from_symbol(RCoreSymCacheElement *element, RCoreSymCacheElementSymbol *s) {\n\tif (!s->name && !s->mangled_name) {\n\t\treturn NULL;\n\t}\n\tRBinSymbol *sym = R_NEW0 (RBinSymbol);\n\tif (sym) {\n\t\tif (s->name && s->mangled_name) {\n\t\t\tsym->dname = strdup (s->name);\n\t\t\tsym->name = strdup (s->mangled_name);\n\t\t} else if (s->name) {\n\t\t\tsym->name = strdup (s->name);\n\t\t} else if (s->mangled_name) {\n\t\t\tsym->name = s->mangled_name;\n\t\t}\n\t\tsym->paddr = s->paddr;\n\t\tsym->vaddr = r_coresym_cache_element_pa2va (element, s->paddr);\n\t\tsym->size = s->size;\n\t\tsym->type = R_BIN_TYPE_FUNC_STR;\n\t\tsym->bind = \"NONE\";\n\t}\n\treturn sym;\n}", "static RCoreSymCacheElement *parseDragons(RBinFile *bf, RBuffer *buf, int off, int bits, R_OWN char *file_name) {\n\tD eprintf (\"Dragons at 0x%x\\n\", off);\n\tut64 size = r_buf_size (buf);\n\tif (off >= size) {\n\t\treturn NULL;\n\t}\n\tsize -= off;\n\tif (!size) {\n\t\treturn NULL;\n\t}\n\tut8 *b = malloc (size);\n\tif (!b) {\n\t\treturn NULL;\n\t}\n\tint available = r_buf_read_at (buf, off, b, size);\n\tif (available != size) {\n\t\teprintf (\"Warning: r_buf_read_at failed\\n\");\n\t\treturn NULL;\n\t}\n#if 0\n\t// after the list of sections, there's a bunch of unknown\n\t// data, brobably dwords, and then the same section list again\n\t// this function aims to parse it.\n\t0x00000138 |1a2b b2a1 0300 0000 1a2b b2a1 e055 0000| .+.......+...U..\n n_segments ----. .--- how many sections ?\n\t0x00000148 |0100 0000 ca55 0000 0400 0000 1800 0000| .....U..........\n\t .---- how many symbols? 0xc7\n\t0x00000158 |c700 0000 0000 0000 0000 0000 0104 0000| ................\n\t0x00000168 |250b e803 0000 0100 0000 0000 bd55 0000| %............U..\n\t0x00000178 |91bb e903 e35a b42c 93a4 340a 8746 9489| .....Z.,..4..F..\n\t0x00000188 |0cea 4c40 0c00 0000 0900 0000 0000 0000| ..L@............\n\t0x00000198 |0000 0000 0000 0000 0000 0000 0000 0000| ................\n\t0x000001a8 |0080 0000 0000 0000 5f5f 5445 5854 0000| ........__TEXT..\n\t0x000001b8 |0000 0000 0000 0000 0080 0000 0000 0000| ................\n\t0x000001c8 |0040 0000 0000 0000 5f5f 4441 5441 0000| .@......__DATA..\n\t0x000001d8 |0000 0000 0000 0000 00c0 0000 0000 0000| ................\n\t0x000001e8 |0000 0100 0000 0000 5f5f 4c4c 564d 0000| ........__LLVM..\n\t0x000001f8 |0000 0000 0000 0000 00c0 0100 0000 0000| ................\n\t0x00000208 |00c0 0000 0000 0000 5f5f 4c49 4e4b 4544| ........__LINKED\n\t0x00000218 |4954 0000 0000 0000 0000 0000 d069 0000| IT...........i..\n#endif\n\t// eprintf (\"Dragon's magic:\\n\");\n\tint magicCombo = 0;\n\tif (!memcmp (\"\\x1a\\x2b\\xb2\\xa1\", b, 4)) { // 0x130 ?\n\t\tmagicCombo++;\n\t}\n\tif (!memcmp (\"\\x1a\\x2b\\xb2\\xa1\", b + 8, 4)) {\n\t\tmagicCombo++;\n\t}\n\tif (magicCombo != 2) {\n\t\t// hack for C22F7494\n\t\tavailable = r_buf_read_at (buf, off - 8, b, size);\n\t\tif (available != size) {\n\t\t\teprintf (\"Warning: r_buf_read_at failed\\n\");\n\t\t\treturn NULL;\n\t\t}\n\t\tif (!memcmp (\"\\x1a\\x2b\\xb2\\xa1\", b, 4)) { // 0x130 ?\n\t\t\toff -= 8;\n\t\t} else {\n\t\t\teprintf (\"0x%08x parsing error: invalid magic retry\\n\", off);\n\t\t}\n\t}\n\tD eprintf (\"0x%08x magic OK\\n\", off);\n\tD {\n\t\tconst int e0ss = r_read_le32 (b + 12);\n\t\teprintf (\"0x%08x eoss 0x%x\\n\", off + 12, e0ss);\n\t}\n\tfree (b);\n\treturn r_coresym_cache_element_new (bf, buf, off + 16, bits, file_name);\n}", "static bool load_buffer(RBinFile *bf, void **bin_obj, RBuffer *buf, ut64 loadaddr, Sdb *sdb) {\n#if 0\n\tSYMBOLS HEADER", " 0\tMAGIC\t02ff01ff\n 4\tVERSION 1 (little endian)\n 8 ffffffff\n16 002b0000 01000000 { 0x2b00, 0x0000 }\n24\tUUID 16 bytes\n40\t2621 d85b 2100 2000 0000 0000 0000 0000\n56\tffff ffff ffff ff7f 0c00 0000 0900 0000\n72\t0400 0000 6800 0000 2f76 6172 2f66 6f6c .... 4, 104 /// 104 length string\n184\n0x000000b8 5f5f 5445 5854 0000 0000 0000 0000 0000 0000 0000 0000 0000 0080 0000 0000 0000 __TEXT..........................\n0x000000d8 5f5f 4441 5441 0000 0000 0000 0000 0000 0080 0000 0000 0000 0040 0000 0000 0000 __DATA...................@......\n0x000000f8 5f5f 4c4c 564d 0000 0000 0000 0000 0000 00c0 0000 0000 0000 0000 0100 0000 0000 __LLVM..........................\n0x00000118 5f5f 4c49 4e4b 4544 4954 0000 0000 0000 00c0 0100 0000 0000 00c0 0000 0000 0000 __LINKEDIT......................", "#endif\n\t// 0 - magic check, version ...\n\tSymbolsHeader sh = parseHeader (buf);\n\tif (!sh.valid) {\n\t\teprintf (\"Invalid headers\\n\");\n\t\treturn false;\n\t}\n\tSymbolsMetadata sm = parseMetadata (buf, 0x40);\n\tchar * file_name = NULL;\n\tif (sm.namelen) {\n\t\tfile_name = calloc (sm.namelen + 1, 1);\n\t\tif (!file_name) {\n\t\t\treturn false;\n\t\t}\n\t\tif (r_buf_read_at (buf, 0x50, (ut8*)file_name, sm.namelen) != sm.namelen) {\n\t\t\treturn false;\n\t\t}\n\t}\n\tRCoreSymCacheElement *element = parseDragons (bf, buf, sm.addr + sm.size, sm.bits, file_name);\n\tif (element) {\n\t\t*bin_obj = element;\n\t\treturn true;\n\t}\n\tfree (file_name);\n\treturn false;\n}", "static RList *sections(RBinFile *bf) {\n\tRList *res = r_list_newf ((RListFree)r_bin_section_free);\n\tr_return_val_if_fail (res && bf->o && bf->o->bin_obj, res);\n\tRCoreSymCacheElement *element = bf->o->bin_obj;\n\tsize_t i;\n\tif (element->segments) {\n\t\tfor (i = 0; i < element->hdr->n_segments; i++) {\n\t\t\tRCoreSymCacheElementSegment *seg = &element->segments[i];\n\t\t\tRBinSection *s = bin_section_from_segment (seg);\n\t\t\tif (s) {\n\t\t\t\tr_list_append (res, s);\n\t\t\t}\n\t\t}\n\t}\n\tif (element->sections) {\n\t\tfor (i = 0; i < element->hdr->n_sections; i++) {\n\t\t\tRCoreSymCacheElementSection *sect = &element->sections[i];\n\t\t\tRBinSection *s = bin_section_from_section (sect);\n\t\t\tif (s) {\n\t\t\t\tr_list_append (res, s);\n\t\t\t}\n\t\t}\n\t}\n\treturn res;\n}", "static ut64 baddr(RBinFile *bf) {\n\treturn 0LL;\n}", "static RBinInfo *info(RBinFile *bf) {\n\tSymbolsMetadata sm = parseMetadata (bf->buf, 0x40);\n\tRBinInfo *ret = R_NEW0 (RBinInfo);\n\tif (!ret) {\n\t\treturn NULL;\n\t}\n\tret->file = strdup (bf->file);\n\tret->bclass = strdup (\"symbols\");\n\tret->os = strdup (\"unknown\");\n\tret->arch = sm.arch ? strdup (sm.arch) : NULL;\n\tret->bits = sm.bits;\n\tret->type = strdup (\"Symbols file\");\n\tret->subsystem = strdup (\"llvm\");\n\tret->has_va = true;", "\treturn ret;\n}", "static bool check_buffer(RBinFile *bf, RBuffer *b) {\n\tut8 buf[4];\n\tr_buf_read_at (b, 0, buf, sizeof (buf));\n\treturn !memcmp (buf, \"\\x02\\xff\\x01\\xff\", 4);\n}", "static RList *symbols(RBinFile *bf) {\n\tRList *res = r_list_newf ((RListFree)r_bin_symbol_free);\n\tr_return_val_if_fail (res && bf->o && bf->o->bin_obj, res);\n\tRCoreSymCacheElement *element = bf->o->bin_obj;\n\tsize_t i;\n\tHtUU *hash = ht_uu_new0 ();\n\tif (!hash) {\n\t\treturn res;\n\t}\n\tbool found = false;\n\tfor (i = 0; i < element->hdr->n_lined_symbols; i++) {\n\t\tRCoreSymCacheElementSymbol *sym = (RCoreSymCacheElementSymbol *)&element->lined_symbols[i];", "\t\tif (!sym) {\n\t\t\tbreak;\n\t\t}", "\t\tht_uu_find (hash, sym->paddr, &found);\n\t\tif (found) {\n\t\t\tcontinue;\n\t\t}\n\t\tRBinSymbol *s = bin_symbol_from_symbol (element, sym);\n\t\tif (s) {\n\t\t\tr_list_append (res, s);\n\t\t\tht_uu_insert (hash, sym->paddr, 1);\n\t\t}\n\t}\n\tif (element->symbols) {\n\t\tfor (i = 0; i < element->hdr->n_symbols; i++) {\n\t\t\tRCoreSymCacheElementSymbol *sym = &element->symbols[i];\n\t\t\tht_uu_find (hash, sym->paddr, &found);\n\t\t\tif (found) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tRBinSymbol *s = bin_symbol_from_symbol (element, sym);\n\t\t\tif (s) {\n\t\t\t\tr_list_append (res, s);\n\t\t\t}\n\t\t}\n\t}\n\tht_uu_free (hash);\n\treturn res;\n}", "static ut64 size(RBinFile *bf) {\n\treturn UT64_MAX;\n}", "static void destroy(RBinFile *bf) {\n\tr_coresym_cache_element_free (bf->o->bin_obj);\n}", "static void header(RBinFile *bf) {\n\tr_return_if_fail (bf && bf->o);", "\tRCoreSymCacheElement *element = bf->o->bin_obj;\n\tif (!element) {\n\t\treturn;\n\t}", "\tRBin *bin = bf->rbin;\n\tPrintfCallback p = bin->cb_printf;\n\tPJ *pj = pj_new ();\n\tif (!pj) {\n\t\treturn;\n\t}", "\tpj_o (pj);\n\tpj_kn (pj, \"cs_version\", element->hdr->version);\n\tpj_kn (pj, \"size\", element->hdr->size);\n\tif (element->file_name) {\n\t\tpj_ks (pj, \"name\", element->file_name);\n\t}\n\tif (element->binary_version) {\n\t\tpj_ks (pj, \"version\", element->binary_version);\n\t}\n\tchar uuidstr[R_UUID_LENGTH];\n\tr_hex_bin2str (element->hdr->uuid, 16, uuidstr);\n\tpj_ks (pj, \"uuid\", uuidstr);\n\tpj_kn (pj, \"segments\", element->hdr->n_segments);\n\tpj_kn (pj, \"sections\", element->hdr->n_sections);\n\tpj_kn (pj, \"symbols\", element->hdr->n_symbols);\n\tpj_kn (pj, \"lined_symbols\", element->hdr->n_lined_symbols);\n\tpj_kn (pj, \"line_info\", element->hdr->n_line_info);\n\tpj_end (pj);", "\tp (\"%s\\n\", pj_string (pj));\n\tpj_free (pj);\n}", "RBinPlugin r_bin_plugin_symbols = {\n\t.name = \"symbols\",\n\t.desc = \"Apple Symbols file\",\n\t.license = \"MIT\",\n\t.load_buffer = &load_buffer,\n\t.check_buffer = &check_buffer,\n\t.symbols = &symbols,\n\t.sections = &sections,\n\t.size = &size,\n\t.baddr = &baddr,\n\t.info = &info,\n\t.header = &header,\n\t.destroy = &destroy,\n};", "#ifndef R2_PLUGIN_INCORE\nR_API RLibStruct radare_plugin = {\n\t.type = R_LIB_TYPE_BIN,\n\t.data = &r_bin_plugin_symbols,\n\t.version = R2_VERSION\n};\n#endif" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [363], "buggy_code_start_loc": [1], "filenames": ["libr/bin/p/bin_symbols.c"], "fixing_code_end_loc": [367], "fixing_code_start_loc": [1], "message": "NULL Pointer Dereference in GitHub repository radareorg/radare2 prior to 5.6.4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:radare:radare2:*:*:*:*:*:*:*:*", "matchCriteriaId": "257C5522-E8C9-42F8-8891-50EDBDD3E873", "versionEndExcluding": "5.6.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:35:*:*:*:*:*:*:*", "matchCriteriaId": "80E516C0-98A4-4ADE-B69F-66A772E2BAAA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:36:*:*:*:*:*:*:*", "matchCriteriaId": "5C675112-476C-4D7C-BCB9-A2FB2D0BC9FD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "NULL Pointer Dereference in GitHub repository radareorg/radare2 prior to 5.6.4."}, {"lang": "es", "value": "Una Desreferencia de puntero NULL en el repositorio de GitHub radareorg/radare2 versiones anteriores a 5.6.4"}], "evaluatorComment": null, "id": "CVE-2022-0712", "lastModified": "2022-04-08T13:53:57.093", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 7.1, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:N/I:N/A:C", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "LOW", "baseScore": 5.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.5, "impactScore": 3.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-02-22T18:15:12.487", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/radareorg/radare2/commit/515e592b9bea0612bc63d8e93239ff35bcf645c7"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/1e572820-e502-49d1-af0e-81833e2eb466"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/BZTIMAS53YT66FUS4QHQAFRJOBMUFG6D/"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/E6YBRQ3UCFWJVSOYIKPVUDASZ544TFND/"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-476"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/radareorg/radare2/commit/515e592b9bea0612bc63d8e93239ff35bcf645c7"}, "type": "CWE-476"}
206
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n $imgurl = IMAGESERVE_DIR . \"/images/$type/$file.$type\";\n $protocol = isset($_SERVER['https']) && $_SERVER['https'] != \"off\" ? \"https\" : \"http\";\n?>\n<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <title><?php echo APP_NAME . \" - $file.$type\"; ?></title>\n <link rel=\"stylesheet\" href=\"/assets/css/style.css\">\n<?php if (TWITTER_CARDS) { ?>\n <meta name=\"twitter:card\" content=\"photo\" />\n <meta name=\"twitter:site\" content=\"<?php echo TWITTER_HANDLE; ?>\" />\n <meta name=\"twitter:title\" content=\"<?php echo $file . '.' . $type; ?>\" />\n <meta name=\"twitter:image\" content=\"<?php echo $protocol; ?>://<?php echo $_SERVER['SERVER_NAME'] . $imgurl; ?>\" />", " <meta name=\"twitter:url\" content=\"<?php echo $protocol; ?>://<?php echo $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; ?>\" />", "<?php } ?>\n </head>", " <body>\n <h1>\n <?php echo \"$file.$type\"; ?> &middot;", " <abbr title=\"Value rounded to the nearest kb.\">\n ~<?php echo round($filesize / 1024, 0); ?>kb\n </abbr>\n </h1>", " <div class=\"container\">\n <?php if ($type != \"webm\"): ?>\n <a href=\"<?php echo $imgurl; ?>\">\n <img src=\"<?php echo $imgurl; ?>\" alt=\"<?php echo \"$file.$type\"; ?>\">\n </a>\n <?php else: ?>\n <video width=\"1280\" height=\"720\" controls>\n <source src=\"<?php echo $imgurl; ?>\" type=\"video/webm\">\n </video>\n <?php endif; ?>\n </div>", " <?php\n $time = microtime();\n $time = explode(' ', $time);\n $time = $time[1] + $time[0];\n $finish = $time;\n $total_time = round(($finish - $start), 4);\n ?>", " <p>\n <a href=\"https://github.com/aerouk/imageserve\">\n Powered by <b>imageserve</b>\n </a>", " &middot; Page generated in <?php echo $total_time; ?> seconds\n </p>\n </body>\n</html>" ]
[ 1, 0, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [17], "buggy_code_start_loc": [16], "filenames": ["public/protected/templates/viewer.phtml"], "fixing_code_end_loc": [17], "fixing_code_start_loc": [16], "message": "A vulnerability has been found in aerouk imageserve and classified as problematic. Affected by this vulnerability is an unknown functionality. The manipulation of the argument REQUEST_URI leads to cross site scripting. The attack can be launched remotely. The exploit has been disclosed to the public and may be used. The name of the patch is 2ac3cd4f90b4df66874fab171376ca26868604c4. It is recommended to apply a patch to fix this issue. The identifier VDB-217057 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:imageserve_project:imageserve:-:*:*:*:*:*:*:*", "matchCriteriaId": "1C2BF72E-B12A-413A-A94F-82A928BF1DF2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability has been found in aerouk imageserve and classified as problematic. Affected by this vulnerability is an unknown functionality. The manipulation of the argument REQUEST_URI leads to cross site scripting. The attack can be launched remotely. The exploit has been disclosed to the public and may be used. The name of the patch is 2ac3cd4f90b4df66874fab171376ca26868604c4. It is recommended to apply a patch to fix this issue. The identifier VDB-217057 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2017-20153", "lastModified": "2023-01-09T17:47:48.423", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "HIGH", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 2.1, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:H/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 2.6, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 1.2, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T12:15:08.910", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/aerouk/imageserve/commit/2ac3cd4f90b4df66874fab171376ca26868604c4"}, {"source": "cna@vuldb.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/aerouk/imageserve/pull/27"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217057"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217057"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/aerouk/imageserve/commit/2ac3cd4f90b4df66874fab171376ca26868604c4"}, "type": "CWE-79"}
207
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n $imgurl = IMAGESERVE_DIR . \"/images/$type/$file.$type\";\n $protocol = isset($_SERVER['https']) && $_SERVER['https'] != \"off\" ? \"https\" : \"http\";\n?>\n<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <title><?php echo APP_NAME . \" - $file.$type\"; ?></title>\n <link rel=\"stylesheet\" href=\"/assets/css/style.css\">\n<?php if (TWITTER_CARDS) { ?>\n <meta name=\"twitter:card\" content=\"photo\" />\n <meta name=\"twitter:site\" content=\"<?php echo TWITTER_HANDLE; ?>\" />\n <meta name=\"twitter:title\" content=\"<?php echo $file . '.' . $type; ?>\" />\n <meta name=\"twitter:image\" content=\"<?php echo $protocol; ?>://<?php echo $_SERVER['SERVER_NAME'] . $imgurl; ?>\" />", " <meta name=\"twitter:url\" content=\"<?php echo $protocol; ?>://<?php echo $_SERVER['SERVER_NAME'] . htmlspecialchars($_SERVER['REQUEST_URI']); ?>\" />", "<?php } ?>\n </head>", " <body>\n <h1>\n <?php echo \"$file.$type\"; ?> &middot;", " <abbr title=\"Value rounded to the nearest kb.\">\n ~<?php echo round($filesize / 1024, 0); ?>kb\n </abbr>\n </h1>", " <div class=\"container\">\n <?php if ($type != \"webm\"): ?>\n <a href=\"<?php echo $imgurl; ?>\">\n <img src=\"<?php echo $imgurl; ?>\" alt=\"<?php echo \"$file.$type\"; ?>\">\n </a>\n <?php else: ?>\n <video width=\"1280\" height=\"720\" controls>\n <source src=\"<?php echo $imgurl; ?>\" type=\"video/webm\">\n </video>\n <?php endif; ?>\n </div>", " <?php\n $time = microtime();\n $time = explode(' ', $time);\n $time = $time[1] + $time[0];\n $finish = $time;\n $total_time = round(($finish - $start), 4);\n ?>", " <p>\n <a href=\"https://github.com/aerouk/imageserve\">\n Powered by <b>imageserve</b>\n </a>", " &middot; Page generated in <?php echo $total_time; ?> seconds\n </p>\n </body>\n</html>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [17], "buggy_code_start_loc": [16], "filenames": ["public/protected/templates/viewer.phtml"], "fixing_code_end_loc": [17], "fixing_code_start_loc": [16], "message": "A vulnerability has been found in aerouk imageserve and classified as problematic. Affected by this vulnerability is an unknown functionality. The manipulation of the argument REQUEST_URI leads to cross site scripting. The attack can be launched remotely. The exploit has been disclosed to the public and may be used. The name of the patch is 2ac3cd4f90b4df66874fab171376ca26868604c4. It is recommended to apply a patch to fix this issue. The identifier VDB-217057 was assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:imageserve_project:imageserve:-:*:*:*:*:*:*:*", "matchCriteriaId": "1C2BF72E-B12A-413A-A94F-82A928BF1DF2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability has been found in aerouk imageserve and classified as problematic. Affected by this vulnerability is an unknown functionality. The manipulation of the argument REQUEST_URI leads to cross site scripting. The attack can be launched remotely. The exploit has been disclosed to the public and may be used. The name of the patch is 2ac3cd4f90b4df66874fab171376ca26868604c4. It is recommended to apply a patch to fix this issue. The identifier VDB-217057 was assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2017-20153", "lastModified": "2023-01-09T17:47:48.423", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "HIGH", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 2.1, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:H/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 2.6, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 1.2, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-30T12:15:08.910", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/aerouk/imageserve/commit/2ac3cd4f90b4df66874fab171376ca26868604c4"}, {"source": "cna@vuldb.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/aerouk/imageserve/pull/27"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217057"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217057"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/aerouk/imageserve/commit/2ac3cd4f90b4df66874fab171376ca26868604c4"}, "type": "CWE-79"}
207
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/* Copyright (c) 1998-2009 ILIAS open source, Extended GPL, see docs/LICENSE */", "/**\n* Wraps $item arrays from magpie\n*\n* @author Alex Killing <alex.killing@gmx.de>\n* @version $Id$\n* @ingroup ServicesFeeds\n*/\nclass ilExternalFeedItem\n{\n\tfunction __construct()\n\t{\n\t}\n\t\n\t/**\n\t* Set Magpie Item and read it into internal variables\n\t*/\n\tfunction setMagpieItem($a_item)\n\t{\n\t\t$this->magpie_item = $a_item;", "\t\t//var_dump($a_item);\n\t\t\n\t\t// title\n\t\t$this->setTitle(\n\t\t\t$this->secureString($a_item[\"title\"]));\n\t\t\n\t\t// link\n\t\tif (isset($a_item[\"link_\"]))\n\t\t{\n\t\t\t$this->setLink(", "\t\t\t\tilUtil::secureLink($this->secureString($a_item[\"link_\"])));", "\t\t}\n\t\telse\n\t\t{\n\t\t\tif (isset($a_item[\"link\"]))\n\t\t\t{\n\t\t\t\t$this->setLink(", "\t\t\t\t\tilUtil::secureLink($this->secureString($a_item[\"link\"])));", "\t\t\t}\n\t\t}", "\t\t", "\t\t// summary\n\t\tif (isset($a_item[\"atom_content\"]))\n\t\t{\n\t\t\t$this->setSummary(\n\t\t\t\t$this->secureString($a_item[\"atom_content\"]));\n\t\t}\n\t\telse if (isset($a_item[\"summary\"]))\n\t\t{\n\t\t\t$this->setSummary(\n\t\t\t\t$this->secureString($a_item[\"summary\"]));\n\t\t}\n\t\telse if (isset($a_item[\"description\"]))\n\t\t{\n\t\t\t$this->setSummary(\n\t\t\t\t$this->secureString($a_item[\"description\"]));\n\t\t}\n\t\t\n\t\t// date\n\t\tif (isset($a_item[\"pubdate\"]))\n\t\t{\n\t\t\t$this->setDate(\n\t\t\t\t$this->secureString($a_item[\"pubdate\"]));\n\t\t}\n\t\telse if (isset($a_item[\"updated\"]))\n\t\t{\n\t\t\t$this->setDate(\n\t\t\t\t$this->secureString($a_item[\"updated\"]));\n\t\t}", "\t\t// Author\n\t\tif (isset($a_item[\"dc\"][\"creator\"]))\n\t\t{\n\t\t\t$this->setAuthor(\n\t\t\t\t$this->secureString($a_item[\"dc\"][\"creator\"]));\n\t\t}", "\t\t// id\n\t\t$this->setId(md5($this->getTitle().$this->getSummary()));", "\t}\n\t\n\tfunction secureString($a_str)\n\t{\n\t\t$a_str = ilUtil::secureString($a_str, true, \"<b><i><em><strong><br><ol><li><ul><a><img>\");\n\t\t$old_str = \"\";\n\t\t\n\t\t// set target to blank for all links\n\t\twhile($old_str != $a_str)\n\t\t{\n\t\t\t$old_str = $a_str;\n\t\t\t$a_str = preg_replace(\"/<a href=\\\"([^\\\"]*)\\\">/i\",\n\t\t\t\t\"/<a href=\\\"\\\\1\\\" target=\\\"_blank\\\" rel=\\\"noopener\\\">/\", $a_str);\n\t\t}\n\t\treturn $a_str;\n\t}\n\t\n\t/**\n\t* Get Magpie Item\n\t*\n\t* @return\tobject\tMagpie Item\n\t*/\n\tfunction getMagpieItem()\n\t{\n\t\treturn $this->magpie_item;\n\t}", "\t/**\n\t* Set Title.\n\t*\n\t* @param\tstring\t$a_title\tTitle\n\t*/\n\tfunction setTitle($a_title)\n\t{\n\t\t$this->title = $a_title;\n\t}", "\t/**\n\t* Get Title.\n\t*\n\t* @return\tstring\tTitle\n\t*/\n\tfunction getTitle()\n\t{\n\t\treturn $this->title;\n\t}", "\t/**\n\t* Set Link.\n\t*\n\t* @param\tstring\t$a_link\tLink\n\t*/\n\tfunction setLink($a_link)\n\t{\n\t\t$this->link = $a_link;\n\t}", "\t/**\n\t* Get Link.\n\t*\n\t* @return\tstring\tLink\n\t*/\n\tfunction getLink()\n\t{\n\t\treturn $this->link;\n\t}", "\t/**\n\t* Set Summary.\n\t*\n\t* @param\tstring\t$a_summary\tSummary\n\t*/\n\tfunction setSummary($a_summary)\n\t{\n\t\t$this->summary = $a_summary;\n\t}", "\t/**\n\t* Get Summary.\n\t*\n\t* @return\tstring\tSummary\n\t*/\n\tfunction getSummary()\n\t{\n\t\treturn $this->summary;\n\t}", "\t/**\n\t* Set Date.\n\t*\n\t* @param\tstring\t$a_date\tDate\n\t*/\n\tfunction setDate($a_date)\n\t{\n\t\t$this->date = $a_date;\n\t}", "\t/**\n\t* Get Date.\n\t*\n\t* @return\tstring\tDate\n\t*/\n\tfunction getDate()\n\t{\n\t\treturn $this->date;\n\t}", "\t/**\n\t* Set Id.\n\t*\n\t* @param\tstring\t$a_id\tId\n\t*/\n\tfunction setId($a_id)\n\t{\n\t\t$this->id = $a_id;\n\t}", "\t/**\n\t* Get Id.\n\t*\n\t* @return\tstring\tId\n\t*/\n\tfunction getId()\n\t{\n\t\treturn $this->id;\n\t}", "\t/**\n\t* Set Author.\n\t*\n\t* @param\tstring\t$a_author\tAuthor\n\t*/\n\tfunction setAuthor($a_author)\n\t{\n\t\t$this->author = $a_author;\n\t}", "\t/**\n\t* Get Author.\n\t*\n\t* @return\tstring\tAuthor\n\t*/\n\tfunction getAuthor()\n\t{\n\t\treturn $this->author;\n\t}\n}" ]
[ 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [46], "buggy_code_start_loc": [35], "filenames": ["Services/Feeds/classes/class.ilExternalFeedItem.php"], "fixing_code_end_loc": [44], "fixing_code_start_loc": [35], "message": "Services/Feeds/classes/class.ilExternalFeedItem.php in ILIAS 5.1.x, 5.2.x, and 5.3.x before 5.3.5 has XSS via a link attribute.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ilias:ilias:*:*:*:*:*:*:*:*", "matchCriteriaId": "0F3792D7-FE39-4C56-B7D9-B67B0B0C94E8", "versionEndExcluding": null, "versionEndIncluding": "5.1.26", "versionStartExcluding": null, "versionStartIncluding": "5.1.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:ilias:ilias:*:*:*:*:*:*:*:*", "matchCriteriaId": "5D26A1D2-92C7-4540-BE93-2FCFE7EAC5D3", "versionEndExcluding": null, "versionEndIncluding": "5.2.15", "versionStartExcluding": null, "versionStartIncluding": "5.2.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:ilias:ilias:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE2188AF-D708-4548-80E4-72AB685C4DAF", "versionEndExcluding": null, "versionEndIncluding": "5.3.4", "versionStartExcluding": null, "versionStartIncluding": "5.3.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ilias:ilias:5.1.0:beta1:*:*:*:*:*:*", "matchCriteriaId": "98C8D659-2BE5-484E-B97E-BF821B106D47", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ilias:ilias:5.2.0:beta1:*:*:*:*:*:*", "matchCriteriaId": "A89A7A96-92A8-4222-8959-FA9A27601FE1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ilias:ilias:5.2.0:beta2:*:*:*:*:*:*", "matchCriteriaId": "F373F01C-F090-44A9-ACB6-030F8CB85402", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ilias:ilias:5.2.0:beta3:*:*:*:*:*:*", "matchCriteriaId": "992F70E2-77FA-4E92-A373-592960C9DF57", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Services/Feeds/classes/class.ilExternalFeedItem.php in ILIAS 5.1.x, 5.2.x, and 5.3.x before 5.3.5 has XSS via a link attribute."}, {"lang": "es", "value": "Services/Feeds/classes/class.ilExternalFeedItem.php en ILIAS 5.1.x, 5.2.x y 5.3.x en versiones anteriores a la 5.3.5 tiene Cross-Site Scripting (XSS) mediante un atributo link."}], "evaluatorComment": null, "id": "CVE-2018-11117", "lastModified": "2018-06-15T19:37:42.600", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-05-17T13:29:00.303", "references": [{"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/ILIAS-eLearning/ILIAS/commit/ff9bf29858f2dbffe828711a6f8bf37038c00d77"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.ilias.de/docu/goto.php?target=st_229"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/ILIAS-eLearning/ILIAS/commit/ff9bf29858f2dbffe828711a6f8bf37038c00d77"}, "type": "CWE-79"}
208
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/* Copyright (c) 1998-2009 ILIAS open source, Extended GPL, see docs/LICENSE */", "/**\n* Wraps $item arrays from magpie\n*\n* @author Alex Killing <alex.killing@gmx.de>\n* @version $Id$\n* @ingroup ServicesFeeds\n*/\nclass ilExternalFeedItem\n{\n\tfunction __construct()\n\t{\n\t}\n\t\n\t/**\n\t* Set Magpie Item and read it into internal variables\n\t*/\n\tfunction setMagpieItem($a_item)\n\t{\n\t\t$this->magpie_item = $a_item;", "\t\t//var_dump($a_item);\n\t\t\n\t\t// title\n\t\t$this->setTitle(\n\t\t\t$this->secureString($a_item[\"title\"]));\n\t\t\n\t\t// link\n\t\tif (isset($a_item[\"link_\"]))\n\t\t{\n\t\t\t$this->setLink(", "\t\t\t\tilUtil::secureUrl(ilUtil::secureLink($this->secureString($a_item[\"link_\"]))));", "\t\t}\n\t\telse\n\t\t{\n\t\t\tif (isset($a_item[\"link\"]))\n\t\t\t{\n\t\t\t\t$this->setLink(", "\t\t\t\t\tilUtil::secureUrl(ilUtil::secureLink($this->secureString($a_item[\"link\"]))));", "\t\t\t}\n\t\t}", "", "\t\t// summary\n\t\tif (isset($a_item[\"atom_content\"]))\n\t\t{\n\t\t\t$this->setSummary(\n\t\t\t\t$this->secureString($a_item[\"atom_content\"]));\n\t\t}\n\t\telse if (isset($a_item[\"summary\"]))\n\t\t{\n\t\t\t$this->setSummary(\n\t\t\t\t$this->secureString($a_item[\"summary\"]));\n\t\t}\n\t\telse if (isset($a_item[\"description\"]))\n\t\t{\n\t\t\t$this->setSummary(\n\t\t\t\t$this->secureString($a_item[\"description\"]));\n\t\t}\n\t\t\n\t\t// date\n\t\tif (isset($a_item[\"pubdate\"]))\n\t\t{\n\t\t\t$this->setDate(\n\t\t\t\t$this->secureString($a_item[\"pubdate\"]));\n\t\t}\n\t\telse if (isset($a_item[\"updated\"]))\n\t\t{\n\t\t\t$this->setDate(\n\t\t\t\t$this->secureString($a_item[\"updated\"]));\n\t\t}", "\t\t// Author\n\t\tif (isset($a_item[\"dc\"][\"creator\"]))\n\t\t{\n\t\t\t$this->setAuthor(\n\t\t\t\t$this->secureString($a_item[\"dc\"][\"creator\"]));\n\t\t}", "\t\t// id\n\t\t$this->setId(md5($this->getTitle().$this->getSummary()));", "\t}\n\t\n\tfunction secureString($a_str)\n\t{\n\t\t$a_str = ilUtil::secureString($a_str, true, \"<b><i><em><strong><br><ol><li><ul><a><img>\");\n\t\t$old_str = \"\";\n\t\t\n\t\t// set target to blank for all links\n\t\twhile($old_str != $a_str)\n\t\t{\n\t\t\t$old_str = $a_str;\n\t\t\t$a_str = preg_replace(\"/<a href=\\\"([^\\\"]*)\\\">/i\",\n\t\t\t\t\"/<a href=\\\"\\\\1\\\" target=\\\"_blank\\\" rel=\\\"noopener\\\">/\", $a_str);\n\t\t}\n\t\treturn $a_str;\n\t}\n\t\n\t/**\n\t* Get Magpie Item\n\t*\n\t* @return\tobject\tMagpie Item\n\t*/\n\tfunction getMagpieItem()\n\t{\n\t\treturn $this->magpie_item;\n\t}", "\t/**\n\t* Set Title.\n\t*\n\t* @param\tstring\t$a_title\tTitle\n\t*/\n\tfunction setTitle($a_title)\n\t{\n\t\t$this->title = $a_title;\n\t}", "\t/**\n\t* Get Title.\n\t*\n\t* @return\tstring\tTitle\n\t*/\n\tfunction getTitle()\n\t{\n\t\treturn $this->title;\n\t}", "\t/**\n\t* Set Link.\n\t*\n\t* @param\tstring\t$a_link\tLink\n\t*/\n\tfunction setLink($a_link)\n\t{\n\t\t$this->link = $a_link;\n\t}", "\t/**\n\t* Get Link.\n\t*\n\t* @return\tstring\tLink\n\t*/\n\tfunction getLink()\n\t{\n\t\treturn $this->link;\n\t}", "\t/**\n\t* Set Summary.\n\t*\n\t* @param\tstring\t$a_summary\tSummary\n\t*/\n\tfunction setSummary($a_summary)\n\t{\n\t\t$this->summary = $a_summary;\n\t}", "\t/**\n\t* Get Summary.\n\t*\n\t* @return\tstring\tSummary\n\t*/\n\tfunction getSummary()\n\t{\n\t\treturn $this->summary;\n\t}", "\t/**\n\t* Set Date.\n\t*\n\t* @param\tstring\t$a_date\tDate\n\t*/\n\tfunction setDate($a_date)\n\t{\n\t\t$this->date = $a_date;\n\t}", "\t/**\n\t* Get Date.\n\t*\n\t* @return\tstring\tDate\n\t*/\n\tfunction getDate()\n\t{\n\t\treturn $this->date;\n\t}", "\t/**\n\t* Set Id.\n\t*\n\t* @param\tstring\t$a_id\tId\n\t*/\n\tfunction setId($a_id)\n\t{\n\t\t$this->id = $a_id;\n\t}", "\t/**\n\t* Get Id.\n\t*\n\t* @return\tstring\tId\n\t*/\n\tfunction getId()\n\t{\n\t\treturn $this->id;\n\t}", "\t/**\n\t* Set Author.\n\t*\n\t* @param\tstring\t$a_author\tAuthor\n\t*/\n\tfunction setAuthor($a_author)\n\t{\n\t\t$this->author = $a_author;\n\t}", "\t/**\n\t* Get Author.\n\t*\n\t* @return\tstring\tAuthor\n\t*/\n\tfunction getAuthor()\n\t{\n\t\treturn $this->author;\n\t}\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [46], "buggy_code_start_loc": [35], "filenames": ["Services/Feeds/classes/class.ilExternalFeedItem.php"], "fixing_code_end_loc": [44], "fixing_code_start_loc": [35], "message": "Services/Feeds/classes/class.ilExternalFeedItem.php in ILIAS 5.1.x, 5.2.x, and 5.3.x before 5.3.5 has XSS via a link attribute.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ilias:ilias:*:*:*:*:*:*:*:*", "matchCriteriaId": "0F3792D7-FE39-4C56-B7D9-B67B0B0C94E8", "versionEndExcluding": null, "versionEndIncluding": "5.1.26", "versionStartExcluding": null, "versionStartIncluding": "5.1.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:ilias:ilias:*:*:*:*:*:*:*:*", "matchCriteriaId": "5D26A1D2-92C7-4540-BE93-2FCFE7EAC5D3", "versionEndExcluding": null, "versionEndIncluding": "5.2.15", "versionStartExcluding": null, "versionStartIncluding": "5.2.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:ilias:ilias:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE2188AF-D708-4548-80E4-72AB685C4DAF", "versionEndExcluding": null, "versionEndIncluding": "5.3.4", "versionStartExcluding": null, "versionStartIncluding": "5.3.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ilias:ilias:5.1.0:beta1:*:*:*:*:*:*", "matchCriteriaId": "98C8D659-2BE5-484E-B97E-BF821B106D47", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ilias:ilias:5.2.0:beta1:*:*:*:*:*:*", "matchCriteriaId": "A89A7A96-92A8-4222-8959-FA9A27601FE1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ilias:ilias:5.2.0:beta2:*:*:*:*:*:*", "matchCriteriaId": "F373F01C-F090-44A9-ACB6-030F8CB85402", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ilias:ilias:5.2.0:beta3:*:*:*:*:*:*", "matchCriteriaId": "992F70E2-77FA-4E92-A373-592960C9DF57", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Services/Feeds/classes/class.ilExternalFeedItem.php in ILIAS 5.1.x, 5.2.x, and 5.3.x before 5.3.5 has XSS via a link attribute."}, {"lang": "es", "value": "Services/Feeds/classes/class.ilExternalFeedItem.php en ILIAS 5.1.x, 5.2.x y 5.3.x en versiones anteriores a la 5.3.5 tiene Cross-Site Scripting (XSS) mediante un atributo link."}], "evaluatorComment": null, "id": "CVE-2018-11117", "lastModified": "2018-06-15T19:37:42.600", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-05-17T13:29:00.303", "references": [{"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/ILIAS-eLearning/ILIAS/commit/ff9bf29858f2dbffe828711a6f8bf37038c00d77"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.ilias.de/docu/goto.php?target=st_229"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/ILIAS-eLearning/ILIAS/commit/ff9bf29858f2dbffe828711a6f8bf37038c00d77"}, "type": "CWE-79"}
208
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * AArch64-specific system calls implementation\n *\n * Copyright (C) 2012 ARM Ltd.\n * Author: Catalin Marinas <catalin.marinas@arm.com>\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License version 2 as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */", "#include <linux/compiler.h>\n#include <linux/errno.h>\n#include <linux/fs.h>\n#include <linux/mm.h>\n#include <linux/export.h>\n#include <linux/sched.h>\n#include <linux/slab.h>\n#include <linux/syscalls.h>", "asmlinkage long sys_mmap(unsigned long addr, unsigned long len,\n\t\t\t unsigned long prot, unsigned long flags,\n\t\t\t unsigned long fd, off_t off)\n{\n\tif (offset_in_page(off) != 0)\n\t\treturn -EINVAL;", "\treturn sys_mmap_pgoff(addr, len, prot, flags, fd, off >> PAGE_SHIFT);\n}", "/*\n * Wrappers to pass the pt_regs argument.\n */\nasmlinkage long sys_rt_sigreturn_wrapper(void);\n#define sys_rt_sigreturn\tsys_rt_sigreturn_wrapper", "#undef __SYSCALL\n#define __SYSCALL(nr, sym)\t[nr] = sym,", "/*\n * The sys_call_table array must be 4K aligned to be accessible from\n * kernel/entry.S.\n */", "void *sys_call_table[__NR_syscalls] __aligned(4096) = {", "\t[0 ... __NR_syscalls - 1] = sys_ni_syscall,\n#include <asm/unistd.h>\n};" ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [53], "buggy_code_start_loc": [52], "filenames": ["arch/arm64/kernel/sys.c"], "fixing_code_end_loc": [53], "fixing_code_start_loc": [52], "message": "arch/arm64/kernel/sys.c in the Linux kernel before 4.0 allows local users to bypass the \"strict page permissions\" protection mechanism and modify the system-call table, and consequently gain privileges, by leveraging write access.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:google:android:*:*:*:*:*:*:*:*", "matchCriteriaId": "595E33EF-6B21-425B-929C-6B883FA50081", "versionEndExcluding": null, "versionEndIncluding": "7.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "1B11CA0B-DBC1-4894-8B51-99F89DF86974", "versionEndExcluding": null, "versionEndIncluding": "3.18.54", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "D02683E7-DF4D-4965-817A-1416862D7959", "versionEndExcluding": null, "versionEndIncluding": "3.19.8", "versionStartExcluding": null, "versionStartIncluding": "3.19", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "arch/arm64/kernel/sys.c in the Linux kernel before 4.0 allows local users to bypass the \"strict page permissions\" protection mechanism and modify the system-call table, and consequently gain privileges, by leveraging write access."}, {"lang": "es", "value": "arch/arm64/kernel/sys.c en el kernel de Linux en versiones anteriores a 4.0 permiten a usuarios locales eludir el mecanismo de protecci\u00f3n de \"permisos de p\u00e1gina estricta\" y modificar la tabla de llamadas del sistema, y consecuentemente obtener privilegios, aprovechando el acceso de escritura."}], "evaluatorComment": null, "id": "CVE-2015-8967", "lastModified": "2023-01-19T16:07:48.723", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 9.3, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:M/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2016-12-08T21:59:01.257", "references": [{"source": "security@android.com", "tags": ["Issue Tracking", "Patch", "Vendor Advisory"], "url": "http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=c623b33b4e9599c6ac5076f7db7369eb9869aa04"}, {"source": "security@android.com", "tags": ["Third Party Advisory"], "url": "http://source.android.com/security/bulletin/2016-12-01.html"}, {"source": "security@android.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/94680"}, {"source": "security@android.com", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/torvalds/linux/commit/c623b33b4e9599c6ac5076f7db7369eb9869aa04"}], "sourceIdentifier": "security@android.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-264"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/c623b33b4e9599c6ac5076f7db7369eb9869aa04"}, "type": "CWE-264"}
209
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * AArch64-specific system calls implementation\n *\n * Copyright (C) 2012 ARM Ltd.\n * Author: Catalin Marinas <catalin.marinas@arm.com>\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License version 2 as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */", "#include <linux/compiler.h>\n#include <linux/errno.h>\n#include <linux/fs.h>\n#include <linux/mm.h>\n#include <linux/export.h>\n#include <linux/sched.h>\n#include <linux/slab.h>\n#include <linux/syscalls.h>", "asmlinkage long sys_mmap(unsigned long addr, unsigned long len,\n\t\t\t unsigned long prot, unsigned long flags,\n\t\t\t unsigned long fd, off_t off)\n{\n\tif (offset_in_page(off) != 0)\n\t\treturn -EINVAL;", "\treturn sys_mmap_pgoff(addr, len, prot, flags, fd, off >> PAGE_SHIFT);\n}", "/*\n * Wrappers to pass the pt_regs argument.\n */\nasmlinkage long sys_rt_sigreturn_wrapper(void);\n#define sys_rt_sigreturn\tsys_rt_sigreturn_wrapper", "#undef __SYSCALL\n#define __SYSCALL(nr, sym)\t[nr] = sym,", "/*\n * The sys_call_table array must be 4K aligned to be accessible from\n * kernel/entry.S.\n */", "void * const sys_call_table[__NR_syscalls] __aligned(4096) = {", "\t[0 ... __NR_syscalls - 1] = sys_ni_syscall,\n#include <asm/unistd.h>\n};" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [53], "buggy_code_start_loc": [52], "filenames": ["arch/arm64/kernel/sys.c"], "fixing_code_end_loc": [53], "fixing_code_start_loc": [52], "message": "arch/arm64/kernel/sys.c in the Linux kernel before 4.0 allows local users to bypass the \"strict page permissions\" protection mechanism and modify the system-call table, and consequently gain privileges, by leveraging write access.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:google:android:*:*:*:*:*:*:*:*", "matchCriteriaId": "595E33EF-6B21-425B-929C-6B883FA50081", "versionEndExcluding": null, "versionEndIncluding": "7.0", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "1B11CA0B-DBC1-4894-8B51-99F89DF86974", "versionEndExcluding": null, "versionEndIncluding": "3.18.54", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "D02683E7-DF4D-4965-817A-1416862D7959", "versionEndExcluding": null, "versionEndIncluding": "3.19.8", "versionStartExcluding": null, "versionStartIncluding": "3.19", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "arch/arm64/kernel/sys.c in the Linux kernel before 4.0 allows local users to bypass the \"strict page permissions\" protection mechanism and modify the system-call table, and consequently gain privileges, by leveraging write access."}, {"lang": "es", "value": "arch/arm64/kernel/sys.c en el kernel de Linux en versiones anteriores a 4.0 permiten a usuarios locales eludir el mecanismo de protecci\u00f3n de \"permisos de p\u00e1gina estricta\" y modificar la tabla de llamadas del sistema, y consecuentemente obtener privilegios, aprovechando el acceso de escritura."}], "evaluatorComment": null, "id": "CVE-2015-8967", "lastModified": "2023-01-19T16:07:48.723", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 9.3, "confidentialityImpact": "COMPLETE", "integrityImpact": "COMPLETE", "vectorString": "AV:N/AC:M/Au:N/C:C/I:C/A:C", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 10.0, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2016-12-08T21:59:01.257", "references": [{"source": "security@android.com", "tags": ["Issue Tracking", "Patch", "Vendor Advisory"], "url": "http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=c623b33b4e9599c6ac5076f7db7369eb9869aa04"}, {"source": "security@android.com", "tags": ["Third Party Advisory"], "url": "http://source.android.com/security/bulletin/2016-12-01.html"}, {"source": "security@android.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/94680"}, {"source": "security@android.com", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/torvalds/linux/commit/c623b33b4e9599c6ac5076f7db7369eb9869aa04"}], "sourceIdentifier": "security@android.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-264"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/c623b33b4e9599c6ac5076f7db7369eb9869aa04"}, "type": "CWE-264"}
209
Determine whether the {function_name} code is vulnerable or not.
[ "# developing", "", "- ORM mock. [4407](https://github.com/beego/beego/pull/4407)\n- Add sonar check and ignore test. [4432](https://github.com/beego/beego/pull/4432) [4433](https://github.com/beego/beego/pull/4433)\n- Update changlog.yml to check every PR to develop branch.[4427](https://github.com/beego/beego/pull/4427)\n- Fix 4396: Add context.param module into adapter. [4398](https://github.com/beego/beego/pull/4398)\n- Remove `duration` from prometheus labels. [4391](https://github.com/beego/beego/pull/4391)\n- Fix `unknown escape sequence` in generated code. [4385](https://github.com/beego/beego/pull/4385)\n- Using fixed name `commentRouter.go` as generated file name. [4385](https://github.com/beego/beego/pull/4385)\n- Fix 4383: ORM Adapter produces panic when using orm.RegisterModelWithPrefix. [4386](https://github.com/beego/beego/pull/4386)\n- Support 4144: Add new api for order by for supporting multiple way to query [4294](https://github.com/beego/beego/pull/4294)\n- Support session Filter chain. [4404](https://github.com/beego/beego/pull/4404)\n- Feature issue #4402 finish router get example. [4416](https://github.com/beego/beego/pull/4416)\n- Implement context.Context support and deprecate `QueryM2MWithCtx` and `QueryTableWithCtx` [4424](https://github.com/beego/beego/pull/4424)\n- Finish timeout option for tasks #4441 [4441](https://github.com/beego/beego/pull/4441)\n- Error Module brief design & using httplib module to validate this design. [4453](https://github.com/beego/beego/pull/4453)\n- Fix 4444: panic when 404 not found. [4446](https://github.com/beego/beego/pull/4446)\n- Fix 4435: fix panic when controller dir not found. [4452](https://github.com/beego/beego/pull/4452)" ]
[ 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1, 346, 140], "buggy_code_start_loc": [1, 345, 19], "filenames": ["CHANGELOG.md", "server/web/tree.go", "server/web/tree_test.go"], "fixing_code_end_loc": [3, 348, 154], "fixing_code_start_loc": [2, 345, 20], "message": "An issue was discovered in the route lookup process in beego through 2.0.1, allows attackers to bypass access control.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:beego:beego:*:*:*:*:*:*:*:*", "matchCriteriaId": "BB99A2E0-769A-4782-874E-36A21E97D17A", "versionEndExcluding": null, "versionEndIncluding": "2.0.1", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "An issue was discovered in the route lookup process in beego through 2.0.1, allows attackers to bypass access control."}, {"lang": "es", "value": "Se ha detectado un problema en el proceso de b\u00fasqueda de rutas en beego versiones hasta 2.0.1, que permite a atacantes omitir el control de acceso"}], "evaluatorComment": null, "id": "CVE-2021-30080", "lastModified": "2022-04-12T20:08:20.507", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-04-05T16:15:12.123", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/beego/beego/commit/d5df5e470d0a8ed291930ae802fd7e6b95226519"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/beego/beego/commit/d5df5e470d0a8ed291930ae802fd7e6b95226519"}, "type": "NVD-CWE-noinfo"}
210
Determine whether the {function_name} code is vulnerable or not.
[ "# developing", "- Fix: /abc.html/aaa match /abc/aaa. [4459](https://github.com/beego/beego/pull/4459)", "- ORM mock. [4407](https://github.com/beego/beego/pull/4407)\n- Add sonar check and ignore test. [4432](https://github.com/beego/beego/pull/4432) [4433](https://github.com/beego/beego/pull/4433)\n- Update changlog.yml to check every PR to develop branch.[4427](https://github.com/beego/beego/pull/4427)\n- Fix 4396: Add context.param module into adapter. [4398](https://github.com/beego/beego/pull/4398)\n- Remove `duration` from prometheus labels. [4391](https://github.com/beego/beego/pull/4391)\n- Fix `unknown escape sequence` in generated code. [4385](https://github.com/beego/beego/pull/4385)\n- Using fixed name `commentRouter.go` as generated file name. [4385](https://github.com/beego/beego/pull/4385)\n- Fix 4383: ORM Adapter produces panic when using orm.RegisterModelWithPrefix. [4386](https://github.com/beego/beego/pull/4386)\n- Support 4144: Add new api for order by for supporting multiple way to query [4294](https://github.com/beego/beego/pull/4294)\n- Support session Filter chain. [4404](https://github.com/beego/beego/pull/4404)\n- Feature issue #4402 finish router get example. [4416](https://github.com/beego/beego/pull/4416)\n- Implement context.Context support and deprecate `QueryM2MWithCtx` and `QueryTableWithCtx` [4424](https://github.com/beego/beego/pull/4424)\n- Finish timeout option for tasks #4441 [4441](https://github.com/beego/beego/pull/4441)\n- Error Module brief design & using httplib module to validate this design. [4453](https://github.com/beego/beego/pull/4453)\n- Fix 4444: panic when 404 not found. [4446](https://github.com/beego/beego/pull/4446)\n- Fix 4435: fix panic when controller dir not found. [4452](https://github.com/beego/beego/pull/4452)" ]
[ 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1, 346, 140], "buggy_code_start_loc": [1, 345, 19], "filenames": ["CHANGELOG.md", "server/web/tree.go", "server/web/tree_test.go"], "fixing_code_end_loc": [3, 348, 154], "fixing_code_start_loc": [2, 345, 20], "message": "An issue was discovered in the route lookup process in beego through 2.0.1, allows attackers to bypass access control.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:beego:beego:*:*:*:*:*:*:*:*", "matchCriteriaId": "BB99A2E0-769A-4782-874E-36A21E97D17A", "versionEndExcluding": null, "versionEndIncluding": "2.0.1", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "An issue was discovered in the route lookup process in beego through 2.0.1, allows attackers to bypass access control."}, {"lang": "es", "value": "Se ha detectado un problema en el proceso de b\u00fasqueda de rutas en beego versiones hasta 2.0.1, que permite a atacantes omitir el control de acceso"}], "evaluatorComment": null, "id": "CVE-2021-30080", "lastModified": "2022-04-12T20:08:20.507", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-04-05T16:15:12.123", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/beego/beego/commit/d5df5e470d0a8ed291930ae802fd7e6b95226519"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/beego/beego/commit/d5df5e470d0a8ed291930ae802fd7e6b95226519"}, "type": "NVD-CWE-noinfo"}
210
Determine whether the {function_name} code is vulnerable or not.
[ "// Copyright 2014 beego Author. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.", "package web", "import (\n\t\"path\"\n\t\"regexp\"\n\t\"strings\"", "\t\"github.com/beego/beego/v2/core/utils\"", "\t\"github.com/beego/beego/v2/server/web/context\"\n)", "var (\n\tallowSuffixExt = []string{\".json\", \".xml\", \".html\"}\n)", "// Tree has three elements: FixRouter/wildcard/leaves\n// fixRouter stores Fixed Router\n// wildcard stores params\n// leaves store the endpoint information\ntype Tree struct {\n\t// prefix set for static router\n\tprefix string\n\t// search fix route first\n\tfixrouters []*Tree\n\t// if set, failure to match fixrouters search then search wildcard\n\twildcard *Tree\n\t// if set, failure to match wildcard search\n\tleaves []*leafInfo\n}", "// NewTree return a new Tree\nfunc NewTree() *Tree {\n\treturn &Tree{}\n}", "// AddTree will add tree to the exist Tree\n// prefix should has no params\nfunc (t *Tree) AddTree(prefix string, tree *Tree) {\n\tt.addtree(splitPath(prefix), tree, nil, \"\")\n}", "func (t *Tree) addtree(segments []string, tree *Tree, wildcards []string, reg string) {\n\tif len(segments) == 0 {\n\t\tpanic(\"prefix should has path\")\n\t}\n\tseg := segments[0]\n\tiswild, params, regexpStr := splitSegment(seg)\n\t// if it's ? meaning can igone this, so add one more rule for it\n\tif len(params) > 0 && params[0] == \":\" {\n\t\tparams = params[1:]\n\t\tif len(segments[1:]) > 0 {\n\t\t\tt.addtree(segments[1:], tree, append(wildcards, params...), reg)\n\t\t} else {\n\t\t\tfilterTreeWithPrefix(tree, wildcards, reg)\n\t\t}\n\t}\n\t// Rule: /login/*/access match /login/2009/11/access\n\t// if already has *, and when loop the access, should as a regexpStr\n\tif !iswild && utils.InSlice(\":splat\", wildcards) {\n\t\tiswild = true\n\t\tregexpStr = seg\n\t}\n\t// Rule: /user/:id/*\n\tif seg == \"*\" && len(wildcards) > 0 && reg == \"\" {\n\t\tregexpStr = \"(.+)\"\n\t}\n\tif len(segments) == 1 {\n\t\tif iswild {\n\t\t\tif regexpStr != \"\" {\n\t\t\t\tif reg == \"\" {\n\t\t\t\t\trr := \"\"\n\t\t\t\t\tfor _, w := range wildcards {\n\t\t\t\t\t\tif w == \":splat\" {\n\t\t\t\t\t\t\trr = rr + \"(.+)/\"\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\trr = rr + \"([^/]+)/\"\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tregexpStr = rr + regexpStr\n\t\t\t\t} else {\n\t\t\t\t\tregexpStr = \"/\" + regexpStr\n\t\t\t\t}\n\t\t\t} else if reg != \"\" {\n\t\t\t\tif seg == \"*.*\" {\n\t\t\t\t\tregexpStr = \"([^.]+).(.+)\"\n\t\t\t\t} else {\n\t\t\t\t\tfor _, w := range params {\n\t\t\t\t\t\tif w == \".\" || w == \":\" {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tregexpStr = \"([^/]+)/\" + regexpStr\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treg = strings.Trim(reg+\"/\"+regexpStr, \"/\")\n\t\t\tfilterTreeWithPrefix(tree, append(wildcards, params...), reg)\n\t\t\tt.wildcard = tree\n\t\t} else {\n\t\t\treg = strings.Trim(reg+\"/\"+regexpStr, \"/\")\n\t\t\tfilterTreeWithPrefix(tree, append(wildcards, params...), reg)\n\t\t\ttree.prefix = seg\n\t\t\tt.fixrouters = append(t.fixrouters, tree)\n\t\t}\n\t\treturn\n\t}", "\tif iswild {\n\t\tif t.wildcard == nil {\n\t\t\tt.wildcard = NewTree()\n\t\t}\n\t\tif regexpStr != \"\" {\n\t\t\tif reg == \"\" {\n\t\t\t\trr := \"\"\n\t\t\t\tfor _, w := range wildcards {\n\t\t\t\t\tif w == \":splat\" {\n\t\t\t\t\t\trr = rr + \"(.+)/\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\trr = rr + \"([^/]+)/\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tregexpStr = rr + regexpStr\n\t\t\t} else {\n\t\t\t\tregexpStr = \"/\" + regexpStr\n\t\t\t}\n\t\t} else if reg != \"\" {\n\t\t\tif seg == \"*.*\" {\n\t\t\t\tregexpStr = \"([^.]+).(.+)\"\n\t\t\t\tparams = params[1:]\n\t\t\t} else {\n\t\t\t\tfor range params {\n\t\t\t\t\tregexpStr = \"([^/]+)/\" + regexpStr\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif seg == \"*.*\" {\n\t\t\t\tparams = params[1:]\n\t\t\t}\n\t\t}\n\t\treg = strings.TrimRight(strings.TrimRight(reg, \"/\")+\"/\"+regexpStr, \"/\")\n\t\tt.wildcard.addtree(segments[1:], tree, append(wildcards, params...), reg)\n\t} else {\n\t\tsubTree := NewTree()\n\t\tsubTree.prefix = seg\n\t\tt.fixrouters = append(t.fixrouters, subTree)\n\t\tsubTree.addtree(segments[1:], tree, append(wildcards, params...), reg)\n\t}\n}", "func filterTreeWithPrefix(t *Tree, wildcards []string, reg string) {\n\tfor _, v := range t.fixrouters {\n\t\tfilterTreeWithPrefix(v, wildcards, reg)\n\t}\n\tif t.wildcard != nil {\n\t\tfilterTreeWithPrefix(t.wildcard, wildcards, reg)\n\t}\n\tfor _, l := range t.leaves {\n\t\tif reg != \"\" {\n\t\t\tif l.regexps != nil {\n\t\t\t\tl.wildcards = append(wildcards, l.wildcards...)\n\t\t\t\tl.regexps = regexp.MustCompile(\"^\" + reg + \"/\" + strings.Trim(l.regexps.String(), \"^$\") + \"$\")\n\t\t\t} else {\n\t\t\t\tfor _, v := range l.wildcards {\n\t\t\t\t\tif v == \":splat\" {\n\t\t\t\t\t\treg = reg + \"/(.+)\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\treg = reg + \"/([^/]+)\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tl.regexps = regexp.MustCompile(\"^\" + reg + \"$\")\n\t\t\t\tl.wildcards = append(wildcards, l.wildcards...)\n\t\t\t}\n\t\t} else {\n\t\t\tl.wildcards = append(wildcards, l.wildcards...)\n\t\t\tif l.regexps != nil {\n\t\t\t\tfor _, w := range wildcards {\n\t\t\t\t\tif w == \":splat\" {\n\t\t\t\t\t\treg = \"(.+)/\" + reg\n\t\t\t\t\t} else {\n\t\t\t\t\t\treg = \"([^/]+)/\" + reg\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tl.regexps = regexp.MustCompile(\"^\" + reg + strings.Trim(l.regexps.String(), \"^$\") + \"$\")\n\t\t\t}\n\t\t}\n\t}\n}", "// AddRouter call addseg function\nfunc (t *Tree) AddRouter(pattern string, runObject interface{}) {\n\tt.addseg(splitPath(pattern), runObject, nil, \"\")\n}", "// \"/\"\n// \"admin\" ->\nfunc (t *Tree) addseg(segments []string, route interface{}, wildcards []string, reg string) {\n\tif len(segments) == 0 {\n\t\tif reg != \"\" {\n\t\t\tt.leaves = append([]*leafInfo{{runObject: route, wildcards: wildcards, regexps: regexp.MustCompile(\"^\" + reg + \"$\")}}, t.leaves...)\n\t\t} else {\n\t\t\tt.leaves = append([]*leafInfo{{runObject: route, wildcards: wildcards}}, t.leaves...)\n\t\t}\n\t} else {\n\t\tseg := segments[0]\n\t\tiswild, params, regexpStr := splitSegment(seg)\n\t\t// if it's ? meaning can igone this, so add one more rule for it\n\t\tif len(params) > 0 && params[0] == \":\" {\n\t\t\tt.addseg(segments[1:], route, wildcards, reg)\n\t\t\tparams = params[1:]\n\t\t}\n\t\t// Rule: /login/*/access match /login/2009/11/access\n\t\t// if already has *, and when loop the access, should as a regexpStr\n\t\tif !iswild && utils.InSlice(\":splat\", wildcards) {\n\t\t\tiswild = true\n\t\t\tregexpStr = seg\n\t\t}\n\t\t// Rule: /user/:id/*\n\t\tif seg == \"*\" && len(wildcards) > 0 && reg == \"\" {\n\t\t\tregexpStr = \"(.+)\"\n\t\t}\n\t\tif iswild {\n\t\t\tif t.wildcard == nil {\n\t\t\t\tt.wildcard = NewTree()\n\t\t\t}\n\t\t\tif regexpStr != \"\" {\n\t\t\t\tif reg == \"\" {\n\t\t\t\t\trr := \"\"\n\t\t\t\t\tfor _, w := range wildcards {\n\t\t\t\t\t\tif w == \":splat\" {\n\t\t\t\t\t\t\trr = rr + \"(.+)/\"\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\trr = rr + \"([^/]+)/\"\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tregexpStr = rr + regexpStr\n\t\t\t\t} else {\n\t\t\t\t\tregexpStr = \"/\" + regexpStr\n\t\t\t\t}\n\t\t\t} else if reg != \"\" {\n\t\t\t\tif seg == \"*.*\" {\n\t\t\t\t\tregexpStr = \"/([^.]+).(.+)\"\n\t\t\t\t\tparams = params[1:]\n\t\t\t\t} else {\n\t\t\t\t\tfor range params {\n\t\t\t\t\t\tregexpStr = \"/([^/]+)\" + regexpStr\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif seg == \"*.*\" {\n\t\t\t\t\tparams = params[1:]\n\t\t\t\t}\n\t\t\t}\n\t\t\tt.wildcard.addseg(segments[1:], route, append(wildcards, params...), reg+regexpStr)\n\t\t} else {\n\t\t\tvar subTree *Tree\n\t\t\tfor _, sub := range t.fixrouters {\n\t\t\t\tif sub.prefix == seg {\n\t\t\t\t\tsubTree = sub\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif subTree == nil {\n\t\t\t\tsubTree = NewTree()\n\t\t\t\tsubTree.prefix = seg\n\t\t\t\tt.fixrouters = append(t.fixrouters, subTree)\n\t\t\t}\n\t\t\tsubTree.addseg(segments[1:], route, wildcards, reg)\n\t\t}\n\t}\n}", "// Match router to runObject & params\nfunc (t *Tree) Match(pattern string, ctx *context.Context) (runObject interface{}) {\n\tif len(pattern) == 0 || pattern[0] != '/' {\n\t\treturn nil\n\t}\n\tw := make([]string, 0, 20)\n\treturn t.match(pattern[1:], pattern, w, ctx)\n}", "func (t *Tree) match(treePattern string, pattern string, wildcardValues []string, ctx *context.Context) (runObject interface{}) {\n\tif len(pattern) > 0 {\n\t\ti := 0\n\t\tfor ; i < len(pattern) && pattern[i] == '/'; i++ {\n\t\t}\n\t\tpattern = pattern[i:]\n\t}\n\t// Handle leaf nodes:\n\tif len(pattern) == 0 {\n\t\tfor _, l := range t.leaves {\n\t\t\tif ok := l.match(treePattern, wildcardValues, ctx); ok {\n\t\t\t\treturn l.runObject\n\t\t\t}\n\t\t}\n\t\tif t.wildcard != nil {\n\t\t\tfor _, l := range t.wildcard.leaves {\n\t\t\t\tif ok := l.match(treePattern, wildcardValues, ctx); ok {\n\t\t\t\t\treturn l.runObject\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\tvar seg string\n\ti, l := 0, len(pattern)\n\tfor ; i < l && pattern[i] != '/'; i++ {\n\t}\n\tif i == 0 {\n\t\tseg = pattern\n\t\tpattern = \"\"\n\t} else {\n\t\tseg = pattern[:i]\n\t\tpattern = pattern[i:]\n\t}\n\tfor _, subTree := range t.fixrouters {\n\t\tif subTree.prefix == seg {\n\t\t\tif len(pattern) != 0 && pattern[0] == '/' {\n\t\t\t\ttreePattern = pattern[1:]\n\t\t\t} else {\n\t\t\t\ttreePattern = pattern\n\t\t\t}\n\t\t\trunObject = subTree.match(treePattern, pattern, wildcardValues, ctx)\n\t\t\tif runObject != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif runObject == nil && len(t.fixrouters) > 0 {\n\t\t// Filter the .json .xml .html extension\n\t\tfor _, str := range allowSuffixExt {", "\t\t\tif strings.HasSuffix(seg, str) {", "\t\t\t\tfor _, subTree := range t.fixrouters {", "", "\t\t\t\t\tif subTree.prefix == seg[:len(seg)-len(str)] {\n\t\t\t\t\t\trunObject = subTree.match(treePattern, pattern, wildcardValues, ctx)\n\t\t\t\t\t\tif runObject != nil {\n\t\t\t\t\t\t\tctx.Input.SetParam(\":ext\", str[1:])\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif runObject == nil && t.wildcard != nil {\n\t\trunObject = t.wildcard.match(treePattern, pattern, append(wildcardValues, seg), ctx)\n\t}", "\tif runObject == nil && len(t.leaves) > 0 {\n\t\twildcardValues = append(wildcardValues, seg)\n\t\tstart, i := 0, 0\n\t\tfor ; i < len(pattern); i++ {\n\t\t\tif pattern[i] == '/' {\n\t\t\t\tif i != 0 && start < len(pattern) {\n\t\t\t\t\twildcardValues = append(wildcardValues, pattern[start:i])\n\t\t\t\t}\n\t\t\t\tstart = i + 1\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif start > 0 {\n\t\t\twildcardValues = append(wildcardValues, pattern[start:i])\n\t\t}\n\t\tfor _, l := range t.leaves {\n\t\t\tif ok := l.match(treePattern, wildcardValues, ctx); ok {\n\t\t\t\treturn l.runObject\n\t\t\t}\n\t\t}\n\t}\n\treturn runObject\n}", "type leafInfo struct {\n\t// names of wildcards that lead to this leaf. eg, [\"id\" \"name\"] for the wildcard \":id\" and \":name\"\n\twildcards []string", "\t// if the leaf is regexp\n\tregexps *regexp.Regexp", "\trunObject interface{}\n}", "func (leaf *leafInfo) match(treePattern string, wildcardValues []string, ctx *context.Context) (ok bool) {\n\t// fmt.Println(\"Leaf:\", wildcardValues, leaf.wildcards, leaf.regexps)\n\tif leaf.regexps == nil {\n\t\tif len(wildcardValues) == 0 && len(leaf.wildcards) == 0 { // static path\n\t\t\treturn true\n\t\t}\n\t\t// match *\n\t\tif len(leaf.wildcards) == 1 && leaf.wildcards[0] == \":splat\" {\n\t\t\tctx.Input.SetParam(\":splat\", treePattern)\n\t\t\treturn true\n\t\t}\n\t\t// match *.* or :id\n\t\tif len(leaf.wildcards) >= 2 && leaf.wildcards[len(leaf.wildcards)-2] == \":path\" && leaf.wildcards[len(leaf.wildcards)-1] == \":ext\" {\n\t\t\tif len(leaf.wildcards) == 2 {\n\t\t\t\tlastone := wildcardValues[len(wildcardValues)-1]\n\t\t\t\tstrs := strings.SplitN(lastone, \".\", 2)\n\t\t\t\tif len(strs) == 2 {\n\t\t\t\t\tctx.Input.SetParam(\":ext\", strs[1])\n\t\t\t\t}\n\t\t\t\tctx.Input.SetParam(\":path\", path.Join(path.Join(wildcardValues[:len(wildcardValues)-1]...), strs[0]))\n\t\t\t\treturn true\n\t\t\t} else if len(wildcardValues) < 2 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tvar index int\n\t\t\tfor index = 0; index < len(leaf.wildcards)-2; index++ {\n\t\t\t\tctx.Input.SetParam(leaf.wildcards[index], wildcardValues[index])\n\t\t\t}\n\t\t\tlastone := wildcardValues[len(wildcardValues)-1]\n\t\t\tstrs := strings.SplitN(lastone, \".\", 2)\n\t\t\tif len(strs) == 2 {\n\t\t\t\tctx.Input.SetParam(\":ext\", strs[1])\n\t\t\t}\n\t\t\tif index > (len(wildcardValues) - 1) {\n\t\t\t\tctx.Input.SetParam(\":path\", \"\")\n\t\t\t} else {\n\t\t\t\tctx.Input.SetParam(\":path\", path.Join(path.Join(wildcardValues[index:len(wildcardValues)-1]...), strs[0]))\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\t\t// match :id\n\t\tif len(leaf.wildcards) != len(wildcardValues) {\n\t\t\treturn false\n\t\t}\n\t\tfor j, v := range leaf.wildcards {\n\t\t\tctx.Input.SetParam(v, wildcardValues[j])\n\t\t}\n\t\treturn true\n\t}", "\tif !leaf.regexps.MatchString(path.Join(wildcardValues...)) {\n\t\treturn false\n\t}\n\tmatches := leaf.regexps.FindStringSubmatch(path.Join(wildcardValues...))\n\tfor i, match := range matches[1:] {\n\t\tif i < len(leaf.wildcards) {\n\t\t\tctx.Input.SetParam(leaf.wildcards[i], match)\n\t\t}\n\t}\n\treturn true\n}", "// \"/\" -> []\n// \"/admin\" -> [\"admin\"]\n// \"/admin/\" -> [\"admin\"]\n// \"/admin/users\" -> [\"admin\", \"users\"]\nfunc splitPath(key string) []string {\n\tkey = strings.Trim(key, \"/ \")\n\tif key == \"\" {\n\t\treturn []string{}\n\t}\n\treturn strings.Split(key, \"/\")\n}", "// \"admin\" -> false, nil, \"\"\n// \":id\" -> true, [:id], \"\"\n// \"?:id\" -> true, [: :id], \"\" : meaning can empty\n// \":id:int\" -> true, [:id], ([0-9]+)\n// \":name:string\" -> true, [:name], ([\\w]+)\n// \":id([0-9]+)\" -> true, [:id], ([0-9]+)\n// \":id([0-9]+)_:name\" -> true, [:id :name], ([0-9]+)_(.+)\n// \"cms_:id_:page.html\" -> true, [:id_ :page], cms_(.+)(.+).html\n// \"cms_:id(.+)_:page.html\" -> true, [:id :page], cms_(.+)_(.+).html\n// \"*\" -> true, [:splat], \"\"\n// \"*.*\" -> true,[. :path :ext], \"\" . meaning separator\nfunc splitSegment(key string) (bool, []string, string) {\n\tif strings.HasPrefix(key, \"*\") {\n\t\tif key == \"*.*\" {\n\t\t\treturn true, []string{\".\", \":path\", \":ext\"}, \"\"\n\t\t}\n\t\treturn true, []string{\":splat\"}, \"\"\n\t}\n\tif strings.ContainsAny(key, \":\") {\n\t\tvar paramsNum int\n\t\tvar out []rune\n\t\tvar start bool\n\t\tvar startexp bool\n\t\tvar param []rune\n\t\tvar expt []rune\n\t\tvar skipnum int\n\t\tparams := []string{}\n\t\treg := regexp.MustCompile(`[a-zA-Z0-9_]+`)\n\t\tfor i, v := range key {\n\t\t\tif skipnum > 0 {\n\t\t\t\tskipnum--\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif start {\n\t\t\t\t// :id:int and :name:string\n\t\t\t\tif v == ':' {\n\t\t\t\t\tif len(key) >= i+4 {\n\t\t\t\t\t\tif key[i+1:i+4] == \"int\" {\n\t\t\t\t\t\t\tout = append(out, []rune(\"([0-9]+)\")...)\n\t\t\t\t\t\t\tparams = append(params, \":\"+string(param))\n\t\t\t\t\t\t\tstart = false\n\t\t\t\t\t\t\tstartexp = false\n\t\t\t\t\t\t\tskipnum = 3\n\t\t\t\t\t\t\tparam = make([]rune, 0)\n\t\t\t\t\t\t\tparamsNum++\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif len(key) >= i+7 {\n\t\t\t\t\t\tif key[i+1:i+7] == \"string\" {\n\t\t\t\t\t\t\tout = append(out, []rune(`([\\w]+)`)...)\n\t\t\t\t\t\t\tparams = append(params, \":\"+string(param))\n\t\t\t\t\t\t\tparamsNum++\n\t\t\t\t\t\t\tstart = false\n\t\t\t\t\t\t\tstartexp = false\n\t\t\t\t\t\t\tskipnum = 6\n\t\t\t\t\t\t\tparam = make([]rune, 0)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// params only support a-zA-Z0-9\n\t\t\t\tif reg.MatchString(string(v)) {\n\t\t\t\t\tparam = append(param, v)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif v != '(' {\n\t\t\t\t\tout = append(out, []rune(`(.+)`)...)\n\t\t\t\t\tparams = append(params, \":\"+string(param))\n\t\t\t\t\tparam = make([]rune, 0)\n\t\t\t\t\tparamsNum++\n\t\t\t\t\tstart = false\n\t\t\t\t\tstartexp = false\n\t\t\t\t}\n\t\t\t}\n\t\t\tif startexp {\n\t\t\t\tif v != ')' {\n\t\t\t\t\texpt = append(expt, v)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Escape Sequence '\\'\n\t\t\tif i > 0 && key[i-1] == '\\\\' {\n\t\t\t\tout = append(out, v)\n\t\t\t} else if v == ':' {\n\t\t\t\tparam = make([]rune, 0)\n\t\t\t\tstart = true\n\t\t\t} else if v == '(' {\n\t\t\t\tstartexp = true\n\t\t\t\tstart = false\n\t\t\t\tif len(param) > 0 {\n\t\t\t\t\tparams = append(params, \":\"+string(param))\n\t\t\t\t\tparam = make([]rune, 0)\n\t\t\t\t}\n\t\t\t\tparamsNum++\n\t\t\t\texpt = make([]rune, 0)\n\t\t\t\texpt = append(expt, '(')\n\t\t\t} else if v == ')' {\n\t\t\t\tstartexp = false\n\t\t\t\texpt = append(expt, ')')\n\t\t\t\tout = append(out, expt...)\n\t\t\t\tparam = make([]rune, 0)\n\t\t\t} else if v == '?' {\n\t\t\t\tparams = append(params, \":\")\n\t\t\t} else {\n\t\t\t\tout = append(out, v)\n\t\t\t}\n\t\t}\n\t\tif len(param) > 0 {\n\t\t\tif paramsNum > 0 {\n\t\t\t\tout = append(out, []rune(`(.+)`)...)\n\t\t\t}\n\t\t\tparams = append(params, \":\"+string(param))\n\t\t}\n\t\treturn true, params, string(out)\n\t}\n\treturn false, nil, \"\"\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1, 346, 140], "buggy_code_start_loc": [1, 345, 19], "filenames": ["CHANGELOG.md", "server/web/tree.go", "server/web/tree_test.go"], "fixing_code_end_loc": [3, 348, 154], "fixing_code_start_loc": [2, 345, 20], "message": "An issue was discovered in the route lookup process in beego through 2.0.1, allows attackers to bypass access control.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:beego:beego:*:*:*:*:*:*:*:*", "matchCriteriaId": "BB99A2E0-769A-4782-874E-36A21E97D17A", "versionEndExcluding": null, "versionEndIncluding": "2.0.1", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "An issue was discovered in the route lookup process in beego through 2.0.1, allows attackers to bypass access control."}, {"lang": "es", "value": "Se ha detectado un problema en el proceso de b\u00fasqueda de rutas en beego versiones hasta 2.0.1, que permite a atacantes omitir el control de acceso"}], "evaluatorComment": null, "id": "CVE-2021-30080", "lastModified": "2022-04-12T20:08:20.507", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-04-05T16:15:12.123", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/beego/beego/commit/d5df5e470d0a8ed291930ae802fd7e6b95226519"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/beego/beego/commit/d5df5e470d0a8ed291930ae802fd7e6b95226519"}, "type": "NVD-CWE-noinfo"}
210
Determine whether the {function_name} code is vulnerable or not.
[ "// Copyright 2014 beego Author. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.", "package web", "import (\n\t\"path\"\n\t\"regexp\"\n\t\"strings\"", "\t\"github.com/beego/beego/v2/core/utils\"", "\t\"github.com/beego/beego/v2/server/web/context\"\n)", "var (\n\tallowSuffixExt = []string{\".json\", \".xml\", \".html\"}\n)", "// Tree has three elements: FixRouter/wildcard/leaves\n// fixRouter stores Fixed Router\n// wildcard stores params\n// leaves store the endpoint information\ntype Tree struct {\n\t// prefix set for static router\n\tprefix string\n\t// search fix route first\n\tfixrouters []*Tree\n\t// if set, failure to match fixrouters search then search wildcard\n\twildcard *Tree\n\t// if set, failure to match wildcard search\n\tleaves []*leafInfo\n}", "// NewTree return a new Tree\nfunc NewTree() *Tree {\n\treturn &Tree{}\n}", "// AddTree will add tree to the exist Tree\n// prefix should has no params\nfunc (t *Tree) AddTree(prefix string, tree *Tree) {\n\tt.addtree(splitPath(prefix), tree, nil, \"\")\n}", "func (t *Tree) addtree(segments []string, tree *Tree, wildcards []string, reg string) {\n\tif len(segments) == 0 {\n\t\tpanic(\"prefix should has path\")\n\t}\n\tseg := segments[0]\n\tiswild, params, regexpStr := splitSegment(seg)\n\t// if it's ? meaning can igone this, so add one more rule for it\n\tif len(params) > 0 && params[0] == \":\" {\n\t\tparams = params[1:]\n\t\tif len(segments[1:]) > 0 {\n\t\t\tt.addtree(segments[1:], tree, append(wildcards, params...), reg)\n\t\t} else {\n\t\t\tfilterTreeWithPrefix(tree, wildcards, reg)\n\t\t}\n\t}\n\t// Rule: /login/*/access match /login/2009/11/access\n\t// if already has *, and when loop the access, should as a regexpStr\n\tif !iswild && utils.InSlice(\":splat\", wildcards) {\n\t\tiswild = true\n\t\tregexpStr = seg\n\t}\n\t// Rule: /user/:id/*\n\tif seg == \"*\" && len(wildcards) > 0 && reg == \"\" {\n\t\tregexpStr = \"(.+)\"\n\t}\n\tif len(segments) == 1 {\n\t\tif iswild {\n\t\t\tif regexpStr != \"\" {\n\t\t\t\tif reg == \"\" {\n\t\t\t\t\trr := \"\"\n\t\t\t\t\tfor _, w := range wildcards {\n\t\t\t\t\t\tif w == \":splat\" {\n\t\t\t\t\t\t\trr = rr + \"(.+)/\"\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\trr = rr + \"([^/]+)/\"\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tregexpStr = rr + regexpStr\n\t\t\t\t} else {\n\t\t\t\t\tregexpStr = \"/\" + regexpStr\n\t\t\t\t}\n\t\t\t} else if reg != \"\" {\n\t\t\t\tif seg == \"*.*\" {\n\t\t\t\t\tregexpStr = \"([^.]+).(.+)\"\n\t\t\t\t} else {\n\t\t\t\t\tfor _, w := range params {\n\t\t\t\t\t\tif w == \".\" || w == \":\" {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tregexpStr = \"([^/]+)/\" + regexpStr\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treg = strings.Trim(reg+\"/\"+regexpStr, \"/\")\n\t\t\tfilterTreeWithPrefix(tree, append(wildcards, params...), reg)\n\t\t\tt.wildcard = tree\n\t\t} else {\n\t\t\treg = strings.Trim(reg+\"/\"+regexpStr, \"/\")\n\t\t\tfilterTreeWithPrefix(tree, append(wildcards, params...), reg)\n\t\t\ttree.prefix = seg\n\t\t\tt.fixrouters = append(t.fixrouters, tree)\n\t\t}\n\t\treturn\n\t}", "\tif iswild {\n\t\tif t.wildcard == nil {\n\t\t\tt.wildcard = NewTree()\n\t\t}\n\t\tif regexpStr != \"\" {\n\t\t\tif reg == \"\" {\n\t\t\t\trr := \"\"\n\t\t\t\tfor _, w := range wildcards {\n\t\t\t\t\tif w == \":splat\" {\n\t\t\t\t\t\trr = rr + \"(.+)/\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\trr = rr + \"([^/]+)/\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tregexpStr = rr + regexpStr\n\t\t\t} else {\n\t\t\t\tregexpStr = \"/\" + regexpStr\n\t\t\t}\n\t\t} else if reg != \"\" {\n\t\t\tif seg == \"*.*\" {\n\t\t\t\tregexpStr = \"([^.]+).(.+)\"\n\t\t\t\tparams = params[1:]\n\t\t\t} else {\n\t\t\t\tfor range params {\n\t\t\t\t\tregexpStr = \"([^/]+)/\" + regexpStr\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif seg == \"*.*\" {\n\t\t\t\tparams = params[1:]\n\t\t\t}\n\t\t}\n\t\treg = strings.TrimRight(strings.TrimRight(reg, \"/\")+\"/\"+regexpStr, \"/\")\n\t\tt.wildcard.addtree(segments[1:], tree, append(wildcards, params...), reg)\n\t} else {\n\t\tsubTree := NewTree()\n\t\tsubTree.prefix = seg\n\t\tt.fixrouters = append(t.fixrouters, subTree)\n\t\tsubTree.addtree(segments[1:], tree, append(wildcards, params...), reg)\n\t}\n}", "func filterTreeWithPrefix(t *Tree, wildcards []string, reg string) {\n\tfor _, v := range t.fixrouters {\n\t\tfilterTreeWithPrefix(v, wildcards, reg)\n\t}\n\tif t.wildcard != nil {\n\t\tfilterTreeWithPrefix(t.wildcard, wildcards, reg)\n\t}\n\tfor _, l := range t.leaves {\n\t\tif reg != \"\" {\n\t\t\tif l.regexps != nil {\n\t\t\t\tl.wildcards = append(wildcards, l.wildcards...)\n\t\t\t\tl.regexps = regexp.MustCompile(\"^\" + reg + \"/\" + strings.Trim(l.regexps.String(), \"^$\") + \"$\")\n\t\t\t} else {\n\t\t\t\tfor _, v := range l.wildcards {\n\t\t\t\t\tif v == \":splat\" {\n\t\t\t\t\t\treg = reg + \"/(.+)\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\treg = reg + \"/([^/]+)\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tl.regexps = regexp.MustCompile(\"^\" + reg + \"$\")\n\t\t\t\tl.wildcards = append(wildcards, l.wildcards...)\n\t\t\t}\n\t\t} else {\n\t\t\tl.wildcards = append(wildcards, l.wildcards...)\n\t\t\tif l.regexps != nil {\n\t\t\t\tfor _, w := range wildcards {\n\t\t\t\t\tif w == \":splat\" {\n\t\t\t\t\t\treg = \"(.+)/\" + reg\n\t\t\t\t\t} else {\n\t\t\t\t\t\treg = \"([^/]+)/\" + reg\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tl.regexps = regexp.MustCompile(\"^\" + reg + strings.Trim(l.regexps.String(), \"^$\") + \"$\")\n\t\t\t}\n\t\t}\n\t}\n}", "// AddRouter call addseg function\nfunc (t *Tree) AddRouter(pattern string, runObject interface{}) {\n\tt.addseg(splitPath(pattern), runObject, nil, \"\")\n}", "// \"/\"\n// \"admin\" ->\nfunc (t *Tree) addseg(segments []string, route interface{}, wildcards []string, reg string) {\n\tif len(segments) == 0 {\n\t\tif reg != \"\" {\n\t\t\tt.leaves = append([]*leafInfo{{runObject: route, wildcards: wildcards, regexps: regexp.MustCompile(\"^\" + reg + \"$\")}}, t.leaves...)\n\t\t} else {\n\t\t\tt.leaves = append([]*leafInfo{{runObject: route, wildcards: wildcards}}, t.leaves...)\n\t\t}\n\t} else {\n\t\tseg := segments[0]\n\t\tiswild, params, regexpStr := splitSegment(seg)\n\t\t// if it's ? meaning can igone this, so add one more rule for it\n\t\tif len(params) > 0 && params[0] == \":\" {\n\t\t\tt.addseg(segments[1:], route, wildcards, reg)\n\t\t\tparams = params[1:]\n\t\t}\n\t\t// Rule: /login/*/access match /login/2009/11/access\n\t\t// if already has *, and when loop the access, should as a regexpStr\n\t\tif !iswild && utils.InSlice(\":splat\", wildcards) {\n\t\t\tiswild = true\n\t\t\tregexpStr = seg\n\t\t}\n\t\t// Rule: /user/:id/*\n\t\tif seg == \"*\" && len(wildcards) > 0 && reg == \"\" {\n\t\t\tregexpStr = \"(.+)\"\n\t\t}\n\t\tif iswild {\n\t\t\tif t.wildcard == nil {\n\t\t\t\tt.wildcard = NewTree()\n\t\t\t}\n\t\t\tif regexpStr != \"\" {\n\t\t\t\tif reg == \"\" {\n\t\t\t\t\trr := \"\"\n\t\t\t\t\tfor _, w := range wildcards {\n\t\t\t\t\t\tif w == \":splat\" {\n\t\t\t\t\t\t\trr = rr + \"(.+)/\"\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\trr = rr + \"([^/]+)/\"\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tregexpStr = rr + regexpStr\n\t\t\t\t} else {\n\t\t\t\t\tregexpStr = \"/\" + regexpStr\n\t\t\t\t}\n\t\t\t} else if reg != \"\" {\n\t\t\t\tif seg == \"*.*\" {\n\t\t\t\t\tregexpStr = \"/([^.]+).(.+)\"\n\t\t\t\t\tparams = params[1:]\n\t\t\t\t} else {\n\t\t\t\t\tfor range params {\n\t\t\t\t\t\tregexpStr = \"/([^/]+)\" + regexpStr\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif seg == \"*.*\" {\n\t\t\t\t\tparams = params[1:]\n\t\t\t\t}\n\t\t\t}\n\t\t\tt.wildcard.addseg(segments[1:], route, append(wildcards, params...), reg+regexpStr)\n\t\t} else {\n\t\t\tvar subTree *Tree\n\t\t\tfor _, sub := range t.fixrouters {\n\t\t\t\tif sub.prefix == seg {\n\t\t\t\t\tsubTree = sub\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif subTree == nil {\n\t\t\t\tsubTree = NewTree()\n\t\t\t\tsubTree.prefix = seg\n\t\t\t\tt.fixrouters = append(t.fixrouters, subTree)\n\t\t\t}\n\t\t\tsubTree.addseg(segments[1:], route, wildcards, reg)\n\t\t}\n\t}\n}", "// Match router to runObject & params\nfunc (t *Tree) Match(pattern string, ctx *context.Context) (runObject interface{}) {\n\tif len(pattern) == 0 || pattern[0] != '/' {\n\t\treturn nil\n\t}\n\tw := make([]string, 0, 20)\n\treturn t.match(pattern[1:], pattern, w, ctx)\n}", "func (t *Tree) match(treePattern string, pattern string, wildcardValues []string, ctx *context.Context) (runObject interface{}) {\n\tif len(pattern) > 0 {\n\t\ti := 0\n\t\tfor ; i < len(pattern) && pattern[i] == '/'; i++ {\n\t\t}\n\t\tpattern = pattern[i:]\n\t}\n\t// Handle leaf nodes:\n\tif len(pattern) == 0 {\n\t\tfor _, l := range t.leaves {\n\t\t\tif ok := l.match(treePattern, wildcardValues, ctx); ok {\n\t\t\t\treturn l.runObject\n\t\t\t}\n\t\t}\n\t\tif t.wildcard != nil {\n\t\t\tfor _, l := range t.wildcard.leaves {\n\t\t\t\tif ok := l.match(treePattern, wildcardValues, ctx); ok {\n\t\t\t\t\treturn l.runObject\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\tvar seg string\n\ti, l := 0, len(pattern)\n\tfor ; i < l && pattern[i] != '/'; i++ {\n\t}\n\tif i == 0 {\n\t\tseg = pattern\n\t\tpattern = \"\"\n\t} else {\n\t\tseg = pattern[:i]\n\t\tpattern = pattern[i:]\n\t}\n\tfor _, subTree := range t.fixrouters {\n\t\tif subTree.prefix == seg {\n\t\t\tif len(pattern) != 0 && pattern[0] == '/' {\n\t\t\t\ttreePattern = pattern[1:]\n\t\t\t} else {\n\t\t\t\ttreePattern = pattern\n\t\t\t}\n\t\t\trunObject = subTree.match(treePattern, pattern, wildcardValues, ctx)\n\t\t\tif runObject != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif runObject == nil && len(t.fixrouters) > 0 {\n\t\t// Filter the .json .xml .html extension\n\t\tfor _, str := range allowSuffixExt {", "\t\t\tif strings.HasSuffix(seg, str) && strings.HasSuffix(treePattern, seg){", "\t\t\t\tfor _, subTree := range t.fixrouters {", "\t\t\t\t\t// strings.HasSuffix(treePattern, seg) avoid cases: /aaa.html/bbb could access /aaa/bbb", "\t\t\t\t\tif subTree.prefix == seg[:len(seg)-len(str)] {\n\t\t\t\t\t\trunObject = subTree.match(treePattern, pattern, wildcardValues, ctx)\n\t\t\t\t\t\tif runObject != nil {\n\t\t\t\t\t\t\tctx.Input.SetParam(\":ext\", str[1:])\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif runObject == nil && t.wildcard != nil {\n\t\trunObject = t.wildcard.match(treePattern, pattern, append(wildcardValues, seg), ctx)\n\t}", "\tif runObject == nil && len(t.leaves) > 0 {\n\t\twildcardValues = append(wildcardValues, seg)\n\t\tstart, i := 0, 0\n\t\tfor ; i < len(pattern); i++ {\n\t\t\tif pattern[i] == '/' {\n\t\t\t\tif i != 0 && start < len(pattern) {\n\t\t\t\t\twildcardValues = append(wildcardValues, pattern[start:i])\n\t\t\t\t}\n\t\t\t\tstart = i + 1\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif start > 0 {\n\t\t\twildcardValues = append(wildcardValues, pattern[start:i])\n\t\t}\n\t\tfor _, l := range t.leaves {\n\t\t\tif ok := l.match(treePattern, wildcardValues, ctx); ok {\n\t\t\t\treturn l.runObject\n\t\t\t}\n\t\t}\n\t}\n\treturn runObject\n}", "type leafInfo struct {\n\t// names of wildcards that lead to this leaf. eg, [\"id\" \"name\"] for the wildcard \":id\" and \":name\"\n\twildcards []string", "\t// if the leaf is regexp\n\tregexps *regexp.Regexp", "\trunObject interface{}\n}", "func (leaf *leafInfo) match(treePattern string, wildcardValues []string, ctx *context.Context) (ok bool) {\n\t// fmt.Println(\"Leaf:\", wildcardValues, leaf.wildcards, leaf.regexps)\n\tif leaf.regexps == nil {\n\t\tif len(wildcardValues) == 0 && len(leaf.wildcards) == 0 { // static path\n\t\t\treturn true\n\t\t}\n\t\t// match *\n\t\tif len(leaf.wildcards) == 1 && leaf.wildcards[0] == \":splat\" {\n\t\t\tctx.Input.SetParam(\":splat\", treePattern)\n\t\t\treturn true\n\t\t}\n\t\t// match *.* or :id\n\t\tif len(leaf.wildcards) >= 2 && leaf.wildcards[len(leaf.wildcards)-2] == \":path\" && leaf.wildcards[len(leaf.wildcards)-1] == \":ext\" {\n\t\t\tif len(leaf.wildcards) == 2 {\n\t\t\t\tlastone := wildcardValues[len(wildcardValues)-1]\n\t\t\t\tstrs := strings.SplitN(lastone, \".\", 2)\n\t\t\t\tif len(strs) == 2 {\n\t\t\t\t\tctx.Input.SetParam(\":ext\", strs[1])\n\t\t\t\t}\n\t\t\t\tctx.Input.SetParam(\":path\", path.Join(path.Join(wildcardValues[:len(wildcardValues)-1]...), strs[0]))\n\t\t\t\treturn true\n\t\t\t} else if len(wildcardValues) < 2 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tvar index int\n\t\t\tfor index = 0; index < len(leaf.wildcards)-2; index++ {\n\t\t\t\tctx.Input.SetParam(leaf.wildcards[index], wildcardValues[index])\n\t\t\t}\n\t\t\tlastone := wildcardValues[len(wildcardValues)-1]\n\t\t\tstrs := strings.SplitN(lastone, \".\", 2)\n\t\t\tif len(strs) == 2 {\n\t\t\t\tctx.Input.SetParam(\":ext\", strs[1])\n\t\t\t}\n\t\t\tif index > (len(wildcardValues) - 1) {\n\t\t\t\tctx.Input.SetParam(\":path\", \"\")\n\t\t\t} else {\n\t\t\t\tctx.Input.SetParam(\":path\", path.Join(path.Join(wildcardValues[index:len(wildcardValues)-1]...), strs[0]))\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\t\t// match :id\n\t\tif len(leaf.wildcards) != len(wildcardValues) {\n\t\t\treturn false\n\t\t}\n\t\tfor j, v := range leaf.wildcards {\n\t\t\tctx.Input.SetParam(v, wildcardValues[j])\n\t\t}\n\t\treturn true\n\t}", "\tif !leaf.regexps.MatchString(path.Join(wildcardValues...)) {\n\t\treturn false\n\t}\n\tmatches := leaf.regexps.FindStringSubmatch(path.Join(wildcardValues...))\n\tfor i, match := range matches[1:] {\n\t\tif i < len(leaf.wildcards) {\n\t\t\tctx.Input.SetParam(leaf.wildcards[i], match)\n\t\t}\n\t}\n\treturn true\n}", "// \"/\" -> []\n// \"/admin\" -> [\"admin\"]\n// \"/admin/\" -> [\"admin\"]\n// \"/admin/users\" -> [\"admin\", \"users\"]\nfunc splitPath(key string) []string {\n\tkey = strings.Trim(key, \"/ \")\n\tif key == \"\" {\n\t\treturn []string{}\n\t}\n\treturn strings.Split(key, \"/\")\n}", "// \"admin\" -> false, nil, \"\"\n// \":id\" -> true, [:id], \"\"\n// \"?:id\" -> true, [: :id], \"\" : meaning can empty\n// \":id:int\" -> true, [:id], ([0-9]+)\n// \":name:string\" -> true, [:name], ([\\w]+)\n// \":id([0-9]+)\" -> true, [:id], ([0-9]+)\n// \":id([0-9]+)_:name\" -> true, [:id :name], ([0-9]+)_(.+)\n// \"cms_:id_:page.html\" -> true, [:id_ :page], cms_(.+)(.+).html\n// \"cms_:id(.+)_:page.html\" -> true, [:id :page], cms_(.+)_(.+).html\n// \"*\" -> true, [:splat], \"\"\n// \"*.*\" -> true,[. :path :ext], \"\" . meaning separator\nfunc splitSegment(key string) (bool, []string, string) {\n\tif strings.HasPrefix(key, \"*\") {\n\t\tif key == \"*.*\" {\n\t\t\treturn true, []string{\".\", \":path\", \":ext\"}, \"\"\n\t\t}\n\t\treturn true, []string{\":splat\"}, \"\"\n\t}\n\tif strings.ContainsAny(key, \":\") {\n\t\tvar paramsNum int\n\t\tvar out []rune\n\t\tvar start bool\n\t\tvar startexp bool\n\t\tvar param []rune\n\t\tvar expt []rune\n\t\tvar skipnum int\n\t\tparams := []string{}\n\t\treg := regexp.MustCompile(`[a-zA-Z0-9_]+`)\n\t\tfor i, v := range key {\n\t\t\tif skipnum > 0 {\n\t\t\t\tskipnum--\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif start {\n\t\t\t\t// :id:int and :name:string\n\t\t\t\tif v == ':' {\n\t\t\t\t\tif len(key) >= i+4 {\n\t\t\t\t\t\tif key[i+1:i+4] == \"int\" {\n\t\t\t\t\t\t\tout = append(out, []rune(\"([0-9]+)\")...)\n\t\t\t\t\t\t\tparams = append(params, \":\"+string(param))\n\t\t\t\t\t\t\tstart = false\n\t\t\t\t\t\t\tstartexp = false\n\t\t\t\t\t\t\tskipnum = 3\n\t\t\t\t\t\t\tparam = make([]rune, 0)\n\t\t\t\t\t\t\tparamsNum++\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif len(key) >= i+7 {\n\t\t\t\t\t\tif key[i+1:i+7] == \"string\" {\n\t\t\t\t\t\t\tout = append(out, []rune(`([\\w]+)`)...)\n\t\t\t\t\t\t\tparams = append(params, \":\"+string(param))\n\t\t\t\t\t\t\tparamsNum++\n\t\t\t\t\t\t\tstart = false\n\t\t\t\t\t\t\tstartexp = false\n\t\t\t\t\t\t\tskipnum = 6\n\t\t\t\t\t\t\tparam = make([]rune, 0)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// params only support a-zA-Z0-9\n\t\t\t\tif reg.MatchString(string(v)) {\n\t\t\t\t\tparam = append(param, v)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif v != '(' {\n\t\t\t\t\tout = append(out, []rune(`(.+)`)...)\n\t\t\t\t\tparams = append(params, \":\"+string(param))\n\t\t\t\t\tparam = make([]rune, 0)\n\t\t\t\t\tparamsNum++\n\t\t\t\t\tstart = false\n\t\t\t\t\tstartexp = false\n\t\t\t\t}\n\t\t\t}\n\t\t\tif startexp {\n\t\t\t\tif v != ')' {\n\t\t\t\t\texpt = append(expt, v)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Escape Sequence '\\'\n\t\t\tif i > 0 && key[i-1] == '\\\\' {\n\t\t\t\tout = append(out, v)\n\t\t\t} else if v == ':' {\n\t\t\t\tparam = make([]rune, 0)\n\t\t\t\tstart = true\n\t\t\t} else if v == '(' {\n\t\t\t\tstartexp = true\n\t\t\t\tstart = false\n\t\t\t\tif len(param) > 0 {\n\t\t\t\t\tparams = append(params, \":\"+string(param))\n\t\t\t\t\tparam = make([]rune, 0)\n\t\t\t\t}\n\t\t\t\tparamsNum++\n\t\t\t\texpt = make([]rune, 0)\n\t\t\t\texpt = append(expt, '(')\n\t\t\t} else if v == ')' {\n\t\t\t\tstartexp = false\n\t\t\t\texpt = append(expt, ')')\n\t\t\t\tout = append(out, expt...)\n\t\t\t\tparam = make([]rune, 0)\n\t\t\t} else if v == '?' {\n\t\t\t\tparams = append(params, \":\")\n\t\t\t} else {\n\t\t\t\tout = append(out, v)\n\t\t\t}\n\t\t}\n\t\tif len(param) > 0 {\n\t\t\tif paramsNum > 0 {\n\t\t\t\tout = append(out, []rune(`(.+)`)...)\n\t\t\t}\n\t\t\tparams = append(params, \":\"+string(param))\n\t\t}\n\t\treturn true, params, string(out)\n\t}\n\treturn false, nil, \"\"\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1, 346, 140], "buggy_code_start_loc": [1, 345, 19], "filenames": ["CHANGELOG.md", "server/web/tree.go", "server/web/tree_test.go"], "fixing_code_end_loc": [3, 348, 154], "fixing_code_start_loc": [2, 345, 20], "message": "An issue was discovered in the route lookup process in beego through 2.0.1, allows attackers to bypass access control.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:beego:beego:*:*:*:*:*:*:*:*", "matchCriteriaId": "BB99A2E0-769A-4782-874E-36A21E97D17A", "versionEndExcluding": null, "versionEndIncluding": "2.0.1", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "An issue was discovered in the route lookup process in beego through 2.0.1, allows attackers to bypass access control."}, {"lang": "es", "value": "Se ha detectado un problema en el proceso de b\u00fasqueda de rutas en beego versiones hasta 2.0.1, que permite a atacantes omitir el control de acceso"}], "evaluatorComment": null, "id": "CVE-2021-30080", "lastModified": "2022-04-12T20:08:20.507", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-04-05T16:15:12.123", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/beego/beego/commit/d5df5e470d0a8ed291930ae802fd7e6b95226519"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/beego/beego/commit/d5df5e470d0a8ed291930ae802fd7e6b95226519"}, "type": "NVD-CWE-noinfo"}
210
Determine whether the {function_name} code is vulnerable or not.
[ "// Copyright 2014 beego Author. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.", "package web", "import (\n\t\"strings\"\n\t\"testing\"", "", "\n\t\"github.com/beego/beego/v2/server/web/context\"\n)", "type testInfo struct {\n\tpattern string\n\trequestUrl string\n\tparams map[string]string\n\tshouldMatchOrNot bool\n}", "var routers []testInfo", "func matchTestInfo(pattern, url string, params map[string]string) testInfo {\n\treturn testInfo{\n\t\tpattern: pattern,\n\t\trequestUrl: url,\n\t\tparams: params,\n\t\tshouldMatchOrNot: true,\n\t}\n}", "func notMatchTestInfo(pattern, url string) testInfo {\n\treturn testInfo{\n\t\tpattern: pattern,\n\t\trequestUrl: url,\n\t\tparams: nil,\n\t\tshouldMatchOrNot: false,\n\t}\n}", "func init() {", "\trouters = make([]testInfo, 0)", "\t// match example\n\trouters = append(routers, matchTestInfo(\"/topic/?:auth:int\", \"/topic\", nil))\n\trouters = append(routers, matchTestInfo(\"/topic/?:auth:int\", \"/topic/123\", map[string]string{\":auth\": \"123\"}))\n\trouters = append(routers, matchTestInfo(\"/topic/:id/?:auth\", \"/topic/1\", map[string]string{\":id\": \"1\"}))\n\trouters = append(routers, matchTestInfo(\"/topic/:id/?:auth\", \"/topic/1/2\", map[string]string{\":id\": \"1\", \":auth\": \"2\"}))\n\trouters = append(routers, matchTestInfo(\"/topic/:id/?:auth:int\", \"/topic/1\", map[string]string{\":id\": \"1\"}))\n\trouters = append(routers, matchTestInfo(\"/topic/:id/?:auth:int\", \"/topic/1/123\", map[string]string{\":id\": \"1\", \":auth\": \"123\"}))\n\trouters = append(routers, matchTestInfo(\"/:id\", \"/123\", map[string]string{\":id\": \"123\"}))\n\trouters = append(routers, matchTestInfo(\"/hello/?:id\", \"/hello\", map[string]string{\":id\": \"\"}))\n\trouters = append(routers, matchTestInfo(\"/\", \"/\", nil))\n\trouters = append(routers, matchTestInfo(\"/customer/login\", \"/customer/login\", nil))\n\trouters = append(routers, matchTestInfo(\"/customer/login\", \"/customer/login.json\", map[string]string{\":ext\": \"json\"}))\n\trouters = append(routers, matchTestInfo(\"/*\", \"/http://customer/123/\", map[string]string{\":splat\": \"http://customer/123/\"}))\n\trouters = append(routers, matchTestInfo(\"/*\", \"/customer/2009/12/11\", map[string]string{\":splat\": \"customer/2009/12/11\"}))\n\trouters = append(routers, matchTestInfo(\"/aa/*/bb\", \"/aa/2009/bb\", map[string]string{\":splat\": \"2009\"}))\n\trouters = append(routers, matchTestInfo(\"/cc/*/dd\", \"/cc/2009/11/dd\", map[string]string{\":splat\": \"2009/11\"}))\n\trouters = append(routers, matchTestInfo(\"/cc/:id/*\", \"/cc/2009/11/dd\", map[string]string{\":id\": \"2009\", \":splat\": \"11/dd\"}))\n\trouters = append(routers, matchTestInfo(\"/ee/:year/*/ff\", \"/ee/2009/11/ff\", map[string]string{\":year\": \"2009\", \":splat\": \"11\"}))\n\trouters = append(routers, matchTestInfo(\"/thumbnail/:size/uploads/*\", \"/thumbnail/100x100/uploads/items/2014/04/20/dPRCdChkUd651t1Hvs18.jpg\", map[string]string{\":size\": \"100x100\", \":splat\": \"items/2014/04/20/dPRCdChkUd651t1Hvs18.jpg\"}))\n\trouters = append(routers, matchTestInfo(\"/*.*\", \"/nice/api.json\", map[string]string{\":path\": \"nice/api\", \":ext\": \"json\"}))\n\trouters = append(routers, matchTestInfo(\"/:name/*.*\", \"/nice/api.json\", map[string]string{\":name\": \"nice\", \":path\": \"api\", \":ext\": \"json\"}))\n\trouters = append(routers, matchTestInfo(\"/:name/test/*.*\", \"/nice/test/api.json\", map[string]string{\":name\": \"nice\", \":path\": \"api\", \":ext\": \"json\"}))\n\trouters = append(routers, matchTestInfo(\"/dl/:width:int/:height:int/*.*\", \"/dl/48/48/05ac66d9bda00a3acf948c43e306fc9a.jpg\", map[string]string{\":width\": \"48\", \":height\": \"48\", \":ext\": \"jpg\", \":path\": \"05ac66d9bda00a3acf948c43e306fc9a\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/shop/:id:int\", \"/v1/shop/123\", map[string]string{\":id\": \"123\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/shop/:id\\\\((a|b|c)\\\\)\", \"/v1/shop/123(a)\", map[string]string{\":id\": \"123\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/shop/:id\\\\((a|b|c)\\\\)\", \"/v1/shop/123(b)\", map[string]string{\":id\": \"123\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/shop/:id\\\\((a|b|c)\\\\)\", \"/v1/shop/123(c)\", map[string]string{\":id\": \"123\"}))\n\trouters = append(routers, matchTestInfo(\"/:year:int/:month:int/:id/:endid\", \"/1111/111/aaa/aaa\", map[string]string{\":year\": \"1111\", \":month\": \"111\", \":id\": \"aaa\", \":endid\": \"aaa\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/shop/:id/:name\", \"/v1/shop/123/nike\", map[string]string{\":id\": \"123\", \":name\": \"nike\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/shop/:id/account\", \"/v1/shop/123/account\", map[string]string{\":id\": \"123\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/shop/:name:string\", \"/v1/shop/nike\", map[string]string{\":name\": \"nike\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/shop/:id([0-9]+)\", \"/v1/shop//123\", map[string]string{\":id\": \"123\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/shop/:id([0-9]+)_:name\", \"/v1/shop/123_nike\", map[string]string{\":id\": \"123\", \":name\": \"nike\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/shop/:id(.+)_cms.html\", \"/v1/shop/123_cms.html\", map[string]string{\":id\": \"123\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/shop/cms_:id(.+)_:page(.+).html\", \"/v1/shop/cms_123_1.html\", map[string]string{\":id\": \"123\", \":page\": \"1\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/:v/cms/aaa_:id(.+)_:page(.+).html\", \"/v1/2/cms/aaa_123_1.html\", map[string]string{\":v\": \"2\", \":id\": \"123\", \":page\": \"1\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/:v/cms_:id(.+)_:page(.+).html\", \"/v1/2/cms_123_1.html\", map[string]string{\":v\": \"2\", \":id\": \"123\", \":page\": \"1\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/:v(.+)_cms/ttt_:id(.+)_:page(.+).html\", \"/v1/2_cms/ttt_123_1.html\", map[string]string{\":v\": \"2\", \":id\": \"123\", \":page\": \"1\"}))\n\trouters = append(routers, matchTestInfo(\"/api/projects/:pid/members/?:mid\", \"/api/projects/1/members\", map[string]string{\":pid\": \"1\"}))\n\trouters = append(routers, matchTestInfo(\"/api/projects/:pid/members/?:mid\", \"/api/projects/1/members/2\", map[string]string{\":pid\": \"1\", \":mid\": \"2\"}))\n\trouters = append(routers, matchTestInfo(\"/?:year/?:month/?:day\", \"/2020/11/10\", map[string]string{\":year\": \"2020\", \":month\": \"11\", \":day\": \"10\"}))\n\trouters = append(routers, matchTestInfo(\"/?:year/?:month/?:day\", \"/2020/11\", map[string]string{\":year\": \"2020\", \":month\": \"11\"}))\n\trouters = append(routers, matchTestInfo(\"/?:year\", \"/2020\", map[string]string{\":year\": \"2020\"}))\n\trouters = append(routers, matchTestInfo(\"/?:year([0-9]+)/?:month([0-9]+)/mid/?:day([0-9]+)/?:hour([0-9]+)\", \"/2020/11/mid/10/24\", map[string]string{\":year\": \"2020\", \":month\": \"11\", \":day\": \"10\", \":hour\": \"24\"}))\n\trouters = append(routers, matchTestInfo(\"/?:year/?:month/mid/?:day/?:hour\", \"/2020/mid/10\", map[string]string{\":year\": \"2020\", \":day\": \"10\"}))\n\trouters = append(routers, matchTestInfo(\"/?:year/?:month/mid/?:day/?:hour\", \"/2020/11/mid\", map[string]string{\":year\": \"2020\", \":month\": \"11\"}))\n\trouters = append(routers, matchTestInfo(\"/?:year/?:month/mid/?:day/?:hour\", \"/mid/10/24\", map[string]string{\":day\": \"10\", \":hour\": \"24\"}))\n\trouters = append(routers, matchTestInfo(\"/?:year([0-9]+)/:month([0-9]+)/mid/:day([0-9]+)/?:hour([0-9]+)\", \"/2020/11/mid/10/24\", map[string]string{\":year\": \"2020\", \":month\": \"11\", \":day\": \"10\", \":hour\": \"24\"}))\n\trouters = append(routers, matchTestInfo(\"/?:year/:month/mid/:day/?:hour\", \"/11/mid/10/24\", map[string]string{\":month\": \"11\", \":day\": \"10\"}))\n\trouters = append(routers, matchTestInfo(\"/?:year/:month/mid/:day/?:hour\", \"/2020/11/mid/10\", map[string]string{\":year\": \"2020\", \":month\": \"11\", \":day\": \"10\"}))\n\trouters = append(routers, matchTestInfo(\"/?:year/:month/mid/:day/?:hour\", \"/11/mid/10\", map[string]string{\":month\": \"11\", \":day\": \"10\"}))\n\t// not match example", "\t// https://github.com/beego/beego/v2/issues/3865\n\trouters = append(routers, notMatchTestInfo(\"/read_:id:int\\\\.htm\", \"/read_222htm\"))\n\trouters = append(routers, notMatchTestInfo(\"/read_:id:int\\\\.htm\", \"/read_222_htm\"))\n\trouters = append(routers, notMatchTestInfo(\"/read_:id:int\\\\.htm\", \" /read_262shtm\"))\n", "", "}", "func TestTreeRouters(t *testing.T) {\n\tfor _, r := range routers {", "", "\t\tshouldMatch := r.shouldMatchOrNot", "", "\t\ttr := NewTree()\n\t\ttr.AddRouter(r.pattern, \"astaxie\")\n\t\tctx := context.NewContext()\n\t\tobj := tr.Match(r.requestUrl, ctx)\n\t\tif !shouldMatch {\n\t\t\tif obj != nil {\n\t\t\t\tt.Fatal(\"pattern:\", r.pattern, \", should not match\", r.requestUrl)\n\t\t\t} else {", "\t\t\t\treturn", "\t\t\t}\n\t\t}\n\t\tif obj == nil || obj.(string) != \"astaxie\" {\n\t\t\tt.Fatal(\"pattern:\", r.pattern+\", can't match obj, Expect \", r.requestUrl)\n\t\t}\n\t\tif r.params != nil {\n\t\t\tfor k, v := range r.params {\n\t\t\t\tif vv := ctx.Input.Param(k); vv != v {\n\t\t\t\t\tt.Fatal(\"The Rule: \" + r.pattern + \"\\nThe RequestURL:\" + r.requestUrl + \"\\nThe Key is \" + k + \", The Value should be: \" + v + \", but get: \" + vv)\n\t\t\t\t} else if vv == \"\" && v != \"\" {\n\t\t\t\t\tt.Fatal(r.pattern + \" \" + r.requestUrl + \" get param empty:\" + k)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "", "}", "func TestStaticPath(t *testing.T) {\n\ttr := NewTree()\n\ttr.AddRouter(\"/topic/:id\", \"wildcard\")\n\ttr.AddRouter(\"/topic\", \"static\")\n\tctx := context.NewContext()\n\tobj := tr.Match(\"/topic\", ctx)\n\tif obj == nil || obj.(string) != \"static\" {\n\t\tt.Fatal(\"/topic is a static route\")\n\t}\n\tobj = tr.Match(\"/topic/1\", ctx)\n\tif obj == nil || obj.(string) != \"wildcard\" {\n\t\tt.Fatal(\"/topic/1 is a wildcard route\")\n\t}\n}", "func TestAddTree(t *testing.T) {\n\ttr := NewTree()\n\ttr.AddRouter(\"/shop/:id/account\", \"astaxie\")\n\ttr.AddRouter(\"/shop/:sd/ttt_:id(.+)_:page(.+).html\", \"astaxie\")\n\tt1 := NewTree()\n\tt1.AddTree(\"/v1/zl\", tr)\n\tctx := context.NewContext()\n\tobj := t1.Match(\"/v1/zl/shop/123/account\", ctx)\n\tif obj == nil || obj.(string) != \"astaxie\" {\n\t\tt.Fatal(\"/v1/zl/shop/:id/account can't get obj \")\n\t}\n\tif ctx.Input.ParamsLen() == 0 {\n\t\tt.Fatal(\"get param error\")\n\t}\n\tif ctx.Input.Param(\":id\") != \"123\" {\n\t\tt.Fatal(\"get :id param error\")\n\t}\n\tctx.Input.Reset(ctx)\n\tobj = t1.Match(\"/v1/zl/shop/123/ttt_1_12.html\", ctx)\n\tif obj == nil || obj.(string) != \"astaxie\" {\n\t\tt.Fatal(\"/v1/zl//shop/:sd/ttt_:id(.+)_:page(.+).html can't get obj \")\n\t}\n\tif ctx.Input.ParamsLen() == 0 {\n\t\tt.Fatal(\"get param error\")\n\t}\n\tif ctx.Input.Param(\":sd\") != \"123\" || ctx.Input.Param(\":id\") != \"1\" || ctx.Input.Param(\":page\") != \"12\" {\n\t\tt.Fatal(\"get :sd :id :page param error\")\n\t}", "\tt2 := NewTree()\n\tt2.AddTree(\"/v1/:shopid\", tr)\n\tctx.Input.Reset(ctx)\n\tobj = t2.Match(\"/v1/zl/shop/123/account\", ctx)\n\tif obj == nil || obj.(string) != \"astaxie\" {\n\t\tt.Fatal(\"/v1/:shopid/shop/:id/account can't get obj \")\n\t}\n\tif ctx.Input.ParamsLen() == 0 {\n\t\tt.Fatal(\"get param error\")\n\t}\n\tif ctx.Input.Param(\":id\") != \"123\" || ctx.Input.Param(\":shopid\") != \"zl\" {\n\t\tt.Fatal(\"get :id :shopid param error\")\n\t}\n\tctx.Input.Reset(ctx)\n\tobj = t2.Match(\"/v1/zl/shop/123/ttt_1_12.html\", ctx)\n\tif obj == nil || obj.(string) != \"astaxie\" {\n\t\tt.Fatal(\"/v1/:shopid/shop/:sd/ttt_:id(.+)_:page(.+).html can't get obj \")\n\t}\n\tif ctx.Input.ParamsLen() == 0 {\n\t\tt.Fatal(\"get :shopid param error\")\n\t}\n\tif ctx.Input.Param(\":sd\") != \"123\" || ctx.Input.Param(\":id\") != \"1\" || ctx.Input.Param(\":page\") != \"12\" || ctx.Input.Param(\":shopid\") != \"zl\" {\n\t\tt.Fatal(\"get :sd :id :page :shopid param error\")\n\t}\n}", "func TestAddTree2(t *testing.T) {\n\ttr := NewTree()\n\ttr.AddRouter(\"/shop/:id/account\", \"astaxie\")\n\ttr.AddRouter(\"/shop/:sd/ttt_:id(.+)_:page(.+).html\", \"astaxie\")\n\tt3 := NewTree()\n\tt3.AddTree(\"/:version(v1|v2)/:prefix\", tr)\n\tctx := context.NewContext()\n\tobj := t3.Match(\"/v1/zl/shop/123/account\", ctx)\n\tif obj == nil || obj.(string) != \"astaxie\" {\n\t\tt.Fatal(\"/:version(v1|v2)/:prefix/shop/:id/account can't get obj \")\n\t}\n\tif ctx.Input.ParamsLen() == 0 {\n\t\tt.Fatal(\"get param error\")\n\t}\n\tif ctx.Input.Param(\":id\") != \"123\" || ctx.Input.Param(\":prefix\") != \"zl\" || ctx.Input.Param(\":version\") != \"v1\" {\n\t\tt.Fatal(\"get :id :prefix :version param error\")\n\t}\n}", "func TestAddTree3(t *testing.T) {\n\ttr := NewTree()\n\ttr.AddRouter(\"/create\", \"astaxie\")\n\ttr.AddRouter(\"/shop/:sd/account\", \"astaxie\")\n\tt3 := NewTree()\n\tt3.AddTree(\"/table/:num\", tr)\n\tctx := context.NewContext()\n\tobj := t3.Match(\"/table/123/shop/123/account\", ctx)\n\tif obj == nil || obj.(string) != \"astaxie\" {\n\t\tt.Fatal(\"/table/:num/shop/:sd/account can't get obj \")\n\t}\n\tif ctx.Input.ParamsLen() == 0 {\n\t\tt.Fatal(\"get param error\")\n\t}\n\tif ctx.Input.Param(\":num\") != \"123\" || ctx.Input.Param(\":sd\") != \"123\" {\n\t\tt.Fatal(\"get :num :sd param error\")\n\t}\n\tctx.Input.Reset(ctx)\n\tobj = t3.Match(\"/table/123/create\", ctx)\n\tif obj == nil || obj.(string) != \"astaxie\" {\n\t\tt.Fatal(\"/table/:num/create can't get obj \")\n\t}\n}", "func TestAddTree4(t *testing.T) {\n\ttr := NewTree()\n\ttr.AddRouter(\"/create\", \"astaxie\")\n\ttr.AddRouter(\"/shop/:sd/:account\", \"astaxie\")\n\tt4 := NewTree()\n\tt4.AddTree(\"/:info:int/:num/:id\", tr)\n\tctx := context.NewContext()\n\tobj := t4.Match(\"/12/123/456/shop/123/account\", ctx)\n\tif obj == nil || obj.(string) != \"astaxie\" {\n\t\tt.Fatal(\"/:info:int/:num/:id/shop/:sd/:account can't get obj \")\n\t}\n\tif ctx.Input.ParamsLen() == 0 {\n\t\tt.Fatal(\"get param error\")\n\t}\n\tif ctx.Input.Param(\":info\") != \"12\" || ctx.Input.Param(\":num\") != \"123\" ||\n\t\tctx.Input.Param(\":id\") != \"456\" || ctx.Input.Param(\":sd\") != \"123\" ||\n\t\tctx.Input.Param(\":account\") != \"account\" {\n\t\tt.Fatal(\"get :info :num :id :sd :account param error\")\n\t}\n\tctx.Input.Reset(ctx)\n\tobj = t4.Match(\"/12/123/456/create\", ctx)\n\tif obj == nil || obj.(string) != \"astaxie\" {\n\t\tt.Fatal(\"/:info:int/:num/:id/create can't get obj \")\n\t}\n}", "// Test for issue #1595\nfunc TestAddTree5(t *testing.T) {\n\ttr := NewTree()\n\ttr.AddRouter(\"/v1/shop/:id\", \"shopdetail\")\n\ttr.AddRouter(\"/v1/shop/\", \"shophome\")\n\tctx := context.NewContext()\n\tobj := tr.Match(\"/v1/shop/\", ctx)\n\tif obj == nil || obj.(string) != \"shophome\" {\n\t\tt.Fatal(\"url /v1/shop/ need match router /v1/shop/ \")\n\t}\n}\nfunc TestSplitPath(t *testing.T) {\n\ta := splitPath(\"\")\n\tif len(a) != 0 {\n\t\tt.Fatal(\"/ should retrun []\")\n\t}\n\ta = splitPath(\"/\")\n\tif len(a) != 0 {\n\t\tt.Fatal(\"/ should retrun []\")\n\t}\n\ta = splitPath(\"/admin\")\n\tif len(a) != 1 || a[0] != \"admin\" {\n\t\tt.Fatal(\"/admin should retrun [admin]\")\n\t}\n\ta = splitPath(\"/admin/\")\n\tif len(a) != 1 || a[0] != \"admin\" {\n\t\tt.Fatal(\"/admin/ should retrun [admin]\")\n\t}\n\ta = splitPath(\"/admin/users\")\n\tif len(a) != 2 || a[0] != \"admin\" || a[1] != \"users\" {\n\t\tt.Fatal(\"/admin should retrun [admin users]\")\n\t}\n\ta = splitPath(\"/admin/:id:int\")\n\tif len(a) != 2 || a[0] != \"admin\" || a[1] != \":id:int\" {\n\t\tt.Fatal(\"/admin should retrun [admin :id:int]\")\n\t}\n}", "func TestSplitSegment(t *testing.T) {", "\titems := map[string]struct {\n\t\tisReg bool\n\t\tparams []string\n\t\tregStr string\n\t}{\n\t\t\"admin\": {false, nil, \"\"},\n\t\t\"*\": {true, []string{\":splat\"}, \"\"},\n\t\t\"*.*\": {true, []string{\".\", \":path\", \":ext\"}, \"\"},\n\t\t\":id\": {true, []string{\":id\"}, \"\"},\n\t\t\"?:id\": {true, []string{\":\", \":id\"}, \"\"},\n\t\t\":id:int\": {true, []string{\":id\"}, \"([0-9]+)\"},\n\t\t\":name:string\": {true, []string{\":name\"}, `([\\w]+)`},\n\t\t\":id([0-9]+)\": {true, []string{\":id\"}, `([0-9]+)`},\n\t\t\":id([0-9]+)_:name\": {true, []string{\":id\", \":name\"}, `([0-9]+)_(.+)`},\n\t\t\":id(.+)_cms.html\": {true, []string{\":id\"}, `(.+)_cms.html`},\n\t\t\":id(.+)_cms\\\\.html\": {true, []string{\":id\"}, `(.+)_cms\\.html`},\n\t\t\"cms_:id(.+)_:page(.+).html\": {true, []string{\":id\", \":page\"}, `cms_(.+)_(.+).html`},\n\t\t`:app(a|b|c)`: {true, []string{\":app\"}, `(a|b|c)`},\n\t\t`:app\\((a|b|c)\\)`: {true, []string{\":app\"}, `(.+)\\((a|b|c)\\)`},\n\t}", "\tfor pattern, v := range items {\n\t\tb, w, r := splitSegment(pattern)\n\t\tif b != v.isReg || r != v.regStr || strings.Join(w, \",\") != strings.Join(v.params, \",\") {\n\t\t\tt.Fatalf(\"%s should return %t,%s,%q, got %t,%s,%q\", pattern, v.isReg, v.params, v.regStr, b, w, r)\n\t\t}\n\t}\n}" ]
[ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1, 346, 140], "buggy_code_start_loc": [1, 345, 19], "filenames": ["CHANGELOG.md", "server/web/tree.go", "server/web/tree_test.go"], "fixing_code_end_loc": [3, 348, 154], "fixing_code_start_loc": [2, 345, 20], "message": "An issue was discovered in the route lookup process in beego through 2.0.1, allows attackers to bypass access control.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:beego:beego:*:*:*:*:*:*:*:*", "matchCriteriaId": "BB99A2E0-769A-4782-874E-36A21E97D17A", "versionEndExcluding": null, "versionEndIncluding": "2.0.1", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "An issue was discovered in the route lookup process in beego through 2.0.1, allows attackers to bypass access control."}, {"lang": "es", "value": "Se ha detectado un problema en el proceso de b\u00fasqueda de rutas en beego versiones hasta 2.0.1, que permite a atacantes omitir el control de acceso"}], "evaluatorComment": null, "id": "CVE-2021-30080", "lastModified": "2022-04-12T20:08:20.507", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-04-05T16:15:12.123", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/beego/beego/commit/d5df5e470d0a8ed291930ae802fd7e6b95226519"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/beego/beego/commit/d5df5e470d0a8ed291930ae802fd7e6b95226519"}, "type": "NVD-CWE-noinfo"}
210
Determine whether the {function_name} code is vulnerable or not.
[ "// Copyright 2014 beego Author. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.", "package web", "import (\n\t\"strings\"\n\t\"testing\"", "\t\"time\"", "\n\t\"github.com/beego/beego/v2/server/web/context\"\n)", "type testInfo struct {\n\tpattern string\n\trequestUrl string\n\tparams map[string]string\n\tshouldMatchOrNot bool\n}", "var routers []testInfo", "func matchTestInfo(pattern, url string, params map[string]string) testInfo {\n\treturn testInfo{\n\t\tpattern: pattern,\n\t\trequestUrl: url,\n\t\tparams: params,\n\t\tshouldMatchOrNot: true,\n\t}\n}", "func notMatchTestInfo(pattern, url string) testInfo {\n\treturn testInfo{\n\t\tpattern: pattern,\n\t\trequestUrl: url,\n\t\tparams: nil,\n\t\tshouldMatchOrNot: false,\n\t}\n}", "func init() {", "\trouters = make([]testInfo, 0, 128)", "\t// match example\n\trouters = append(routers, matchTestInfo(\"/topic/?:auth:int\", \"/topic\", nil))\n\trouters = append(routers, matchTestInfo(\"/topic/?:auth:int\", \"/topic/123\", map[string]string{\":auth\": \"123\"}))\n\trouters = append(routers, matchTestInfo(\"/topic/:id/?:auth\", \"/topic/1\", map[string]string{\":id\": \"1\"}))\n\trouters = append(routers, matchTestInfo(\"/topic/:id/?:auth\", \"/topic/1/2\", map[string]string{\":id\": \"1\", \":auth\": \"2\"}))\n\trouters = append(routers, matchTestInfo(\"/topic/:id/?:auth:int\", \"/topic/1\", map[string]string{\":id\": \"1\"}))\n\trouters = append(routers, matchTestInfo(\"/topic/:id/?:auth:int\", \"/topic/1/123\", map[string]string{\":id\": \"1\", \":auth\": \"123\"}))\n\trouters = append(routers, matchTestInfo(\"/:id\", \"/123\", map[string]string{\":id\": \"123\"}))\n\trouters = append(routers, matchTestInfo(\"/hello/?:id\", \"/hello\", map[string]string{\":id\": \"\"}))\n\trouters = append(routers, matchTestInfo(\"/\", \"/\", nil))\n\trouters = append(routers, matchTestInfo(\"/customer/login\", \"/customer/login\", nil))\n\trouters = append(routers, matchTestInfo(\"/customer/login\", \"/customer/login.json\", map[string]string{\":ext\": \"json\"}))\n\trouters = append(routers, matchTestInfo(\"/*\", \"/http://customer/123/\", map[string]string{\":splat\": \"http://customer/123/\"}))\n\trouters = append(routers, matchTestInfo(\"/*\", \"/customer/2009/12/11\", map[string]string{\":splat\": \"customer/2009/12/11\"}))\n\trouters = append(routers, matchTestInfo(\"/aa/*/bb\", \"/aa/2009/bb\", map[string]string{\":splat\": \"2009\"}))\n\trouters = append(routers, matchTestInfo(\"/cc/*/dd\", \"/cc/2009/11/dd\", map[string]string{\":splat\": \"2009/11\"}))\n\trouters = append(routers, matchTestInfo(\"/cc/:id/*\", \"/cc/2009/11/dd\", map[string]string{\":id\": \"2009\", \":splat\": \"11/dd\"}))\n\trouters = append(routers, matchTestInfo(\"/ee/:year/*/ff\", \"/ee/2009/11/ff\", map[string]string{\":year\": \"2009\", \":splat\": \"11\"}))\n\trouters = append(routers, matchTestInfo(\"/thumbnail/:size/uploads/*\", \"/thumbnail/100x100/uploads/items/2014/04/20/dPRCdChkUd651t1Hvs18.jpg\", map[string]string{\":size\": \"100x100\", \":splat\": \"items/2014/04/20/dPRCdChkUd651t1Hvs18.jpg\"}))\n\trouters = append(routers, matchTestInfo(\"/*.*\", \"/nice/api.json\", map[string]string{\":path\": \"nice/api\", \":ext\": \"json\"}))\n\trouters = append(routers, matchTestInfo(\"/:name/*.*\", \"/nice/api.json\", map[string]string{\":name\": \"nice\", \":path\": \"api\", \":ext\": \"json\"}))\n\trouters = append(routers, matchTestInfo(\"/:name/test/*.*\", \"/nice/test/api.json\", map[string]string{\":name\": \"nice\", \":path\": \"api\", \":ext\": \"json\"}))\n\trouters = append(routers, matchTestInfo(\"/dl/:width:int/:height:int/*.*\", \"/dl/48/48/05ac66d9bda00a3acf948c43e306fc9a.jpg\", map[string]string{\":width\": \"48\", \":height\": \"48\", \":ext\": \"jpg\", \":path\": \"05ac66d9bda00a3acf948c43e306fc9a\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/shop/:id:int\", \"/v1/shop/123\", map[string]string{\":id\": \"123\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/shop/:id\\\\((a|b|c)\\\\)\", \"/v1/shop/123(a)\", map[string]string{\":id\": \"123\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/shop/:id\\\\((a|b|c)\\\\)\", \"/v1/shop/123(b)\", map[string]string{\":id\": \"123\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/shop/:id\\\\((a|b|c)\\\\)\", \"/v1/shop/123(c)\", map[string]string{\":id\": \"123\"}))\n\trouters = append(routers, matchTestInfo(\"/:year:int/:month:int/:id/:endid\", \"/1111/111/aaa/aaa\", map[string]string{\":year\": \"1111\", \":month\": \"111\", \":id\": \"aaa\", \":endid\": \"aaa\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/shop/:id/:name\", \"/v1/shop/123/nike\", map[string]string{\":id\": \"123\", \":name\": \"nike\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/shop/:id/account\", \"/v1/shop/123/account\", map[string]string{\":id\": \"123\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/shop/:name:string\", \"/v1/shop/nike\", map[string]string{\":name\": \"nike\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/shop/:id([0-9]+)\", \"/v1/shop//123\", map[string]string{\":id\": \"123\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/shop/:id([0-9]+)_:name\", \"/v1/shop/123_nike\", map[string]string{\":id\": \"123\", \":name\": \"nike\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/shop/:id(.+)_cms.html\", \"/v1/shop/123_cms.html\", map[string]string{\":id\": \"123\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/shop/cms_:id(.+)_:page(.+).html\", \"/v1/shop/cms_123_1.html\", map[string]string{\":id\": \"123\", \":page\": \"1\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/:v/cms/aaa_:id(.+)_:page(.+).html\", \"/v1/2/cms/aaa_123_1.html\", map[string]string{\":v\": \"2\", \":id\": \"123\", \":page\": \"1\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/:v/cms_:id(.+)_:page(.+).html\", \"/v1/2/cms_123_1.html\", map[string]string{\":v\": \"2\", \":id\": \"123\", \":page\": \"1\"}))\n\trouters = append(routers, matchTestInfo(\"/v1/:v(.+)_cms/ttt_:id(.+)_:page(.+).html\", \"/v1/2_cms/ttt_123_1.html\", map[string]string{\":v\": \"2\", \":id\": \"123\", \":page\": \"1\"}))\n\trouters = append(routers, matchTestInfo(\"/api/projects/:pid/members/?:mid\", \"/api/projects/1/members\", map[string]string{\":pid\": \"1\"}))\n\trouters = append(routers, matchTestInfo(\"/api/projects/:pid/members/?:mid\", \"/api/projects/1/members/2\", map[string]string{\":pid\": \"1\", \":mid\": \"2\"}))\n\trouters = append(routers, matchTestInfo(\"/?:year/?:month/?:day\", \"/2020/11/10\", map[string]string{\":year\": \"2020\", \":month\": \"11\", \":day\": \"10\"}))\n\trouters = append(routers, matchTestInfo(\"/?:year/?:month/?:day\", \"/2020/11\", map[string]string{\":year\": \"2020\", \":month\": \"11\"}))\n\trouters = append(routers, matchTestInfo(\"/?:year\", \"/2020\", map[string]string{\":year\": \"2020\"}))\n\trouters = append(routers, matchTestInfo(\"/?:year([0-9]+)/?:month([0-9]+)/mid/?:day([0-9]+)/?:hour([0-9]+)\", \"/2020/11/mid/10/24\", map[string]string{\":year\": \"2020\", \":month\": \"11\", \":day\": \"10\", \":hour\": \"24\"}))\n\trouters = append(routers, matchTestInfo(\"/?:year/?:month/mid/?:day/?:hour\", \"/2020/mid/10\", map[string]string{\":year\": \"2020\", \":day\": \"10\"}))\n\trouters = append(routers, matchTestInfo(\"/?:year/?:month/mid/?:day/?:hour\", \"/2020/11/mid\", map[string]string{\":year\": \"2020\", \":month\": \"11\"}))\n\trouters = append(routers, matchTestInfo(\"/?:year/?:month/mid/?:day/?:hour\", \"/mid/10/24\", map[string]string{\":day\": \"10\", \":hour\": \"24\"}))\n\trouters = append(routers, matchTestInfo(\"/?:year([0-9]+)/:month([0-9]+)/mid/:day([0-9]+)/?:hour([0-9]+)\", \"/2020/11/mid/10/24\", map[string]string{\":year\": \"2020\", \":month\": \"11\", \":day\": \"10\", \":hour\": \"24\"}))\n\trouters = append(routers, matchTestInfo(\"/?:year/:month/mid/:day/?:hour\", \"/11/mid/10/24\", map[string]string{\":month\": \"11\", \":day\": \"10\"}))\n\trouters = append(routers, matchTestInfo(\"/?:year/:month/mid/:day/?:hour\", \"/2020/11/mid/10\", map[string]string{\":year\": \"2020\", \":month\": \"11\", \":day\": \"10\"}))\n\trouters = append(routers, matchTestInfo(\"/?:year/:month/mid/:day/?:hour\", \"/11/mid/10\", map[string]string{\":month\": \"11\", \":day\": \"10\"}))\n\t// not match example", "\t// https://github.com/beego/beego/v2/issues/3865\n\trouters = append(routers, notMatchTestInfo(\"/read_:id:int\\\\.htm\", \"/read_222htm\"))\n\trouters = append(routers, notMatchTestInfo(\"/read_:id:int\\\\.htm\", \"/read_222_htm\"))\n\trouters = append(routers, notMatchTestInfo(\"/read_:id:int\\\\.htm\", \" /read_262shtm\"))\n", "\t// test .html, .json not suffix\n\tconst abcHtml = \"/suffix/abc.html\"\n\trouters = append(routers, notMatchTestInfo(abcHtml, \"/suffix.html/abc\"))\n\trouters = append(routers, matchTestInfo(\"/suffix/abc\", abcHtml, nil))\n\trouters = append(routers, matchTestInfo(\"/suffix/*\", abcHtml, nil))\n\trouters = append(routers, notMatchTestInfo(\"/suffix/*\", \"/suffix.html/a\"))\n\tconst abcSuffix = \"/abc/suffix/*\"\n\trouters = append(routers, notMatchTestInfo(abcSuffix, \"/abc/suffix.html/a\"))\n\trouters = append(routers, matchTestInfo(abcSuffix, \"/abc/suffix/a\", nil))\n\trouters = append(routers, notMatchTestInfo(abcSuffix, \"/abc.j/suffix/a\"))\n", "}", "func TestTreeRouters(t *testing.T) {\n\tfor _, r := range routers {", "", "\t\tshouldMatch := r.shouldMatchOrNot", "", "\t\ttr := NewTree()\n\t\ttr.AddRouter(r.pattern, \"astaxie\")\n\t\tctx := context.NewContext()\n\t\tobj := tr.Match(r.requestUrl, ctx)\n\t\tif !shouldMatch {\n\t\t\tif obj != nil {\n\t\t\t\tt.Fatal(\"pattern:\", r.pattern, \", should not match\", r.requestUrl)\n\t\t\t} else {", "\t\t\t\tcontinue", "\t\t\t}\n\t\t}\n\t\tif obj == nil || obj.(string) != \"astaxie\" {\n\t\t\tt.Fatal(\"pattern:\", r.pattern+\", can't match obj, Expect \", r.requestUrl)\n\t\t}\n\t\tif r.params != nil {\n\t\t\tfor k, v := range r.params {\n\t\t\t\tif vv := ctx.Input.Param(k); vv != v {\n\t\t\t\t\tt.Fatal(\"The Rule: \" + r.pattern + \"\\nThe RequestURL:\" + r.requestUrl + \"\\nThe Key is \" + k + \", The Value should be: \" + v + \", but get: \" + vv)\n\t\t\t\t} else if vv == \"\" && v != \"\" {\n\t\t\t\t\tt.Fatal(r.pattern + \" \" + r.requestUrl + \" get param empty:\" + k)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "\ttime.Sleep(time.Second)", "}", "func TestStaticPath(t *testing.T) {\n\ttr := NewTree()\n\ttr.AddRouter(\"/topic/:id\", \"wildcard\")\n\ttr.AddRouter(\"/topic\", \"static\")\n\tctx := context.NewContext()\n\tobj := tr.Match(\"/topic\", ctx)\n\tif obj == nil || obj.(string) != \"static\" {\n\t\tt.Fatal(\"/topic is a static route\")\n\t}\n\tobj = tr.Match(\"/topic/1\", ctx)\n\tif obj == nil || obj.(string) != \"wildcard\" {\n\t\tt.Fatal(\"/topic/1 is a wildcard route\")\n\t}\n}", "func TestAddTree(t *testing.T) {\n\ttr := NewTree()\n\ttr.AddRouter(\"/shop/:id/account\", \"astaxie\")\n\ttr.AddRouter(\"/shop/:sd/ttt_:id(.+)_:page(.+).html\", \"astaxie\")\n\tt1 := NewTree()\n\tt1.AddTree(\"/v1/zl\", tr)\n\tctx := context.NewContext()\n\tobj := t1.Match(\"/v1/zl/shop/123/account\", ctx)\n\tif obj == nil || obj.(string) != \"astaxie\" {\n\t\tt.Fatal(\"/v1/zl/shop/:id/account can't get obj \")\n\t}\n\tif ctx.Input.ParamsLen() == 0 {\n\t\tt.Fatal(\"get param error\")\n\t}\n\tif ctx.Input.Param(\":id\") != \"123\" {\n\t\tt.Fatal(\"get :id param error\")\n\t}\n\tctx.Input.Reset(ctx)\n\tobj = t1.Match(\"/v1/zl/shop/123/ttt_1_12.html\", ctx)\n\tif obj == nil || obj.(string) != \"astaxie\" {\n\t\tt.Fatal(\"/v1/zl//shop/:sd/ttt_:id(.+)_:page(.+).html can't get obj \")\n\t}\n\tif ctx.Input.ParamsLen() == 0 {\n\t\tt.Fatal(\"get param error\")\n\t}\n\tif ctx.Input.Param(\":sd\") != \"123\" || ctx.Input.Param(\":id\") != \"1\" || ctx.Input.Param(\":page\") != \"12\" {\n\t\tt.Fatal(\"get :sd :id :page param error\")\n\t}", "\tt2 := NewTree()\n\tt2.AddTree(\"/v1/:shopid\", tr)\n\tctx.Input.Reset(ctx)\n\tobj = t2.Match(\"/v1/zl/shop/123/account\", ctx)\n\tif obj == nil || obj.(string) != \"astaxie\" {\n\t\tt.Fatal(\"/v1/:shopid/shop/:id/account can't get obj \")\n\t}\n\tif ctx.Input.ParamsLen() == 0 {\n\t\tt.Fatal(\"get param error\")\n\t}\n\tif ctx.Input.Param(\":id\") != \"123\" || ctx.Input.Param(\":shopid\") != \"zl\" {\n\t\tt.Fatal(\"get :id :shopid param error\")\n\t}\n\tctx.Input.Reset(ctx)\n\tobj = t2.Match(\"/v1/zl/shop/123/ttt_1_12.html\", ctx)\n\tif obj == nil || obj.(string) != \"astaxie\" {\n\t\tt.Fatal(\"/v1/:shopid/shop/:sd/ttt_:id(.+)_:page(.+).html can't get obj \")\n\t}\n\tif ctx.Input.ParamsLen() == 0 {\n\t\tt.Fatal(\"get :shopid param error\")\n\t}\n\tif ctx.Input.Param(\":sd\") != \"123\" || ctx.Input.Param(\":id\") != \"1\" || ctx.Input.Param(\":page\") != \"12\" || ctx.Input.Param(\":shopid\") != \"zl\" {\n\t\tt.Fatal(\"get :sd :id :page :shopid param error\")\n\t}\n}", "func TestAddTree2(t *testing.T) {\n\ttr := NewTree()\n\ttr.AddRouter(\"/shop/:id/account\", \"astaxie\")\n\ttr.AddRouter(\"/shop/:sd/ttt_:id(.+)_:page(.+).html\", \"astaxie\")\n\tt3 := NewTree()\n\tt3.AddTree(\"/:version(v1|v2)/:prefix\", tr)\n\tctx := context.NewContext()\n\tobj := t3.Match(\"/v1/zl/shop/123/account\", ctx)\n\tif obj == nil || obj.(string) != \"astaxie\" {\n\t\tt.Fatal(\"/:version(v1|v2)/:prefix/shop/:id/account can't get obj \")\n\t}\n\tif ctx.Input.ParamsLen() == 0 {\n\t\tt.Fatal(\"get param error\")\n\t}\n\tif ctx.Input.Param(\":id\") != \"123\" || ctx.Input.Param(\":prefix\") != \"zl\" || ctx.Input.Param(\":version\") != \"v1\" {\n\t\tt.Fatal(\"get :id :prefix :version param error\")\n\t}\n}", "func TestAddTree3(t *testing.T) {\n\ttr := NewTree()\n\ttr.AddRouter(\"/create\", \"astaxie\")\n\ttr.AddRouter(\"/shop/:sd/account\", \"astaxie\")\n\tt3 := NewTree()\n\tt3.AddTree(\"/table/:num\", tr)\n\tctx := context.NewContext()\n\tobj := t3.Match(\"/table/123/shop/123/account\", ctx)\n\tif obj == nil || obj.(string) != \"astaxie\" {\n\t\tt.Fatal(\"/table/:num/shop/:sd/account can't get obj \")\n\t}\n\tif ctx.Input.ParamsLen() == 0 {\n\t\tt.Fatal(\"get param error\")\n\t}\n\tif ctx.Input.Param(\":num\") != \"123\" || ctx.Input.Param(\":sd\") != \"123\" {\n\t\tt.Fatal(\"get :num :sd param error\")\n\t}\n\tctx.Input.Reset(ctx)\n\tobj = t3.Match(\"/table/123/create\", ctx)\n\tif obj == nil || obj.(string) != \"astaxie\" {\n\t\tt.Fatal(\"/table/:num/create can't get obj \")\n\t}\n}", "func TestAddTree4(t *testing.T) {\n\ttr := NewTree()\n\ttr.AddRouter(\"/create\", \"astaxie\")\n\ttr.AddRouter(\"/shop/:sd/:account\", \"astaxie\")\n\tt4 := NewTree()\n\tt4.AddTree(\"/:info:int/:num/:id\", tr)\n\tctx := context.NewContext()\n\tobj := t4.Match(\"/12/123/456/shop/123/account\", ctx)\n\tif obj == nil || obj.(string) != \"astaxie\" {\n\t\tt.Fatal(\"/:info:int/:num/:id/shop/:sd/:account can't get obj \")\n\t}\n\tif ctx.Input.ParamsLen() == 0 {\n\t\tt.Fatal(\"get param error\")\n\t}\n\tif ctx.Input.Param(\":info\") != \"12\" || ctx.Input.Param(\":num\") != \"123\" ||\n\t\tctx.Input.Param(\":id\") != \"456\" || ctx.Input.Param(\":sd\") != \"123\" ||\n\t\tctx.Input.Param(\":account\") != \"account\" {\n\t\tt.Fatal(\"get :info :num :id :sd :account param error\")\n\t}\n\tctx.Input.Reset(ctx)\n\tobj = t4.Match(\"/12/123/456/create\", ctx)\n\tif obj == nil || obj.(string) != \"astaxie\" {\n\t\tt.Fatal(\"/:info:int/:num/:id/create can't get obj \")\n\t}\n}", "// Test for issue #1595\nfunc TestAddTree5(t *testing.T) {\n\ttr := NewTree()\n\ttr.AddRouter(\"/v1/shop/:id\", \"shopdetail\")\n\ttr.AddRouter(\"/v1/shop/\", \"shophome\")\n\tctx := context.NewContext()\n\tobj := tr.Match(\"/v1/shop/\", ctx)\n\tif obj == nil || obj.(string) != \"shophome\" {\n\t\tt.Fatal(\"url /v1/shop/ need match router /v1/shop/ \")\n\t}\n}\nfunc TestSplitPath(t *testing.T) {\n\ta := splitPath(\"\")\n\tif len(a) != 0 {\n\t\tt.Fatal(\"/ should retrun []\")\n\t}\n\ta = splitPath(\"/\")\n\tif len(a) != 0 {\n\t\tt.Fatal(\"/ should retrun []\")\n\t}\n\ta = splitPath(\"/admin\")\n\tif len(a) != 1 || a[0] != \"admin\" {\n\t\tt.Fatal(\"/admin should retrun [admin]\")\n\t}\n\ta = splitPath(\"/admin/\")\n\tif len(a) != 1 || a[0] != \"admin\" {\n\t\tt.Fatal(\"/admin/ should retrun [admin]\")\n\t}\n\ta = splitPath(\"/admin/users\")\n\tif len(a) != 2 || a[0] != \"admin\" || a[1] != \"users\" {\n\t\tt.Fatal(\"/admin should retrun [admin users]\")\n\t}\n\ta = splitPath(\"/admin/:id:int\")\n\tif len(a) != 2 || a[0] != \"admin\" || a[1] != \":id:int\" {\n\t\tt.Fatal(\"/admin should retrun [admin :id:int]\")\n\t}\n}", "func TestSplitSegment(t *testing.T) {", "\titems := map[string]struct {\n\t\tisReg bool\n\t\tparams []string\n\t\tregStr string\n\t}{\n\t\t\"admin\": {false, nil, \"\"},\n\t\t\"*\": {true, []string{\":splat\"}, \"\"},\n\t\t\"*.*\": {true, []string{\".\", \":path\", \":ext\"}, \"\"},\n\t\t\":id\": {true, []string{\":id\"}, \"\"},\n\t\t\"?:id\": {true, []string{\":\", \":id\"}, \"\"},\n\t\t\":id:int\": {true, []string{\":id\"}, \"([0-9]+)\"},\n\t\t\":name:string\": {true, []string{\":name\"}, `([\\w]+)`},\n\t\t\":id([0-9]+)\": {true, []string{\":id\"}, `([0-9]+)`},\n\t\t\":id([0-9]+)_:name\": {true, []string{\":id\", \":name\"}, `([0-9]+)_(.+)`},\n\t\t\":id(.+)_cms.html\": {true, []string{\":id\"}, `(.+)_cms.html`},\n\t\t\":id(.+)_cms\\\\.html\": {true, []string{\":id\"}, `(.+)_cms\\.html`},\n\t\t\"cms_:id(.+)_:page(.+).html\": {true, []string{\":id\", \":page\"}, `cms_(.+)_(.+).html`},\n\t\t`:app(a|b|c)`: {true, []string{\":app\"}, `(a|b|c)`},\n\t\t`:app\\((a|b|c)\\)`: {true, []string{\":app\"}, `(.+)\\((a|b|c)\\)`},\n\t}", "\tfor pattern, v := range items {\n\t\tb, w, r := splitSegment(pattern)\n\t\tif b != v.isReg || r != v.regStr || strings.Join(w, \",\") != strings.Join(v.params, \",\") {\n\t\t\tt.Fatalf(\"%s should return %t,%s,%q, got %t,%s,%q\", pattern, v.isReg, v.params, v.regStr, b, w, r)\n\t\t}\n\t}\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1, 346, 140], "buggy_code_start_loc": [1, 345, 19], "filenames": ["CHANGELOG.md", "server/web/tree.go", "server/web/tree_test.go"], "fixing_code_end_loc": [3, 348, 154], "fixing_code_start_loc": [2, 345, 20], "message": "An issue was discovered in the route lookup process in beego through 2.0.1, allows attackers to bypass access control.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:beego:beego:*:*:*:*:*:*:*:*", "matchCriteriaId": "BB99A2E0-769A-4782-874E-36A21E97D17A", "versionEndExcluding": null, "versionEndIncluding": "2.0.1", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "An issue was discovered in the route lookup process in beego through 2.0.1, allows attackers to bypass access control."}, {"lang": "es", "value": "Se ha detectado un problema en el proceso de b\u00fasqueda de rutas en beego versiones hasta 2.0.1, que permite a atacantes omitir el control de acceso"}], "evaluatorComment": null, "id": "CVE-2021-30080", "lastModified": "2022-04-12T20:08:20.507", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-04-05T16:15:12.123", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/beego/beego/commit/d5df5e470d0a8ed291930ae802fd7e6b95226519"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "NVD-CWE-noinfo"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/beego/beego/commit/d5df5e470d0a8ed291930ae802fd7e6b95226519"}, "type": "NVD-CWE-noinfo"}
210
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace App;", "/**\n * Some \"very\" global constants for Kimai.\n */\nclass Constants\n{\n /**\n * The current release version\n */", " public const VERSION = '1.16.0';", " /**\n * The current release: major * 10000 + minor * 100 + patch\n */", " public const VERSION_ID = 11600;", " /**\n * The current release status, either \"stable\" or \"dev\"\n */\n public const STATUS = 'prod';\n /**\n * The software name\n */\n public const SOFTWARE = 'Kimai';\n /**\n * The release name, will only change for new major version\n */\n public const NAME = 'Ayumi';\n /**\n * Used in multiple views\n */\n public const GITHUB = 'https://github.com/kevinpapst/kimai2/';\n /**\n * Homepage, used in multiple views\n */\n public const HOMEPAGE = 'https://www.kimai.org';\n /**\n * Application wide default locale\n */\n public const DEFAULT_LOCALE = 'en';\n /**\n * Default color for Customer, Project and Activity entities\n */\n public const DEFAULT_COLOR = '#d2d6de';\n}" ]
[ 1, 1, 1, 1, 0, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace App;", "/**\n * Some \"very\" global constants for Kimai.\n */\nclass Constants\n{\n /**\n * The current release version\n */", " public const VERSION = '1.16.2';", " /**\n * The current release: major * 10000 + minor * 100 + patch\n */", " public const VERSION_ID = 11602;", " /**\n * The current release status, either \"stable\" or \"dev\"\n */\n public const STATUS = 'prod';\n /**\n * The software name\n */\n public const SOFTWARE = 'Kimai';\n /**\n * The release name, will only change for new major version\n */\n public const NAME = 'Ayumi';\n /**\n * Used in multiple views\n */\n public const GITHUB = 'https://github.com/kevinpapst/kimai2/';\n /**\n * Homepage, used in multiple views\n */\n public const HOMEPAGE = 'https://www.kimai.org';\n /**\n * Application wide default locale\n */\n public const DEFAULT_LOCALE = 'en';\n /**\n * Default color for Customer, Project and Activity entities\n */\n public const DEFAULT_COLOR = '#d2d6de';\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace App\\Controller;", "use App\\Configuration\\SystemConfiguration;\nuse App\\Entity\\Customer;\nuse App\\Entity\\MetaTableTypeInterface;\nuse App\\Entity\\Project;\nuse App\\Entity\\ProjectComment;\nuse App\\Entity\\ProjectRate;\nuse App\\Entity\\Rate;\nuse App\\Entity\\Team;\nuse App\\Event\\ProjectMetaDefinitionEvent;\nuse App\\Event\\ProjectMetaDisplayEvent;\nuse App\\Export\\Spreadsheet\\EntityWithMetaFieldsExporter;\nuse App\\Export\\Spreadsheet\\Writer\\BinaryFileResponseWriter;\nuse App\\Export\\Spreadsheet\\Writer\\XlsxWriter;\nuse App\\Form\\ProjectCommentForm;\nuse App\\Form\\ProjectEditForm;\nuse App\\Form\\ProjectRateForm;\nuse App\\Form\\ProjectTeamPermissionForm;\nuse App\\Form\\Toolbar\\ProjectToolbarForm;\nuse App\\Form\\Type\\ProjectType;\nuse App\\Project\\ProjectDuplicationService;\nuse App\\Project\\ProjectService;\nuse App\\Project\\ProjectStatisticService;\nuse App\\Repository\\ActivityRepository;\nuse App\\Repository\\ProjectRateRepository;\nuse App\\Repository\\ProjectRepository;\nuse App\\Repository\\Query\\ActivityQuery;\nuse App\\Repository\\Query\\ProjectQuery;\nuse App\\Repository\\TeamRepository;\nuse Pagerfanta\\Pagerfanta;\nuse Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Security;\nuse Symfony\\Component\\EventDispatcher\\EventDispatcherInterface;\nuse Symfony\\Component\\Form\\FormInterface;\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\Routing\\Annotation\\Route;\nuse Symfony\\Component\\Security\\Csrf\\CsrfToken;\nuse Symfony\\Component\\Security\\Csrf\\CsrfTokenManagerInterface;", "/**\n * Controller used to manage projects.\n *\n * @Route(path=\"/admin/project\")\n * @Security(\"is_granted('view_project') or is_granted('view_teamlead_project') or is_granted('view_team_project')\")\n */\nfinal class ProjectController extends AbstractController\n{\n /**\n * @var ProjectRepository\n */\n private $repository;\n /**\n * @var SystemConfiguration\n */\n private $configuration;\n /**\n * @var EventDispatcherInterface\n */\n private $dispatcher;\n /**\n * @var ProjectService\n */\n private $projectService;", " public function __construct(ProjectRepository $repository, SystemConfiguration $configuration, EventDispatcherInterface $dispatcher, ProjectService $projectService)\n {\n $this->repository = $repository;\n $this->configuration = $configuration;\n $this->dispatcher = $dispatcher;\n $this->projectService = $projectService;\n }", " /**\n * @Route(path=\"/\", defaults={\"page\": 1}, name=\"admin_project\", methods={\"GET\"})\n * @Route(path=\"/page/{page}\", requirements={\"page\": \"[1-9]\\d*\"}, name=\"admin_project_paginated\", methods={\"GET\"})\n */\n public function indexAction($page, Request $request)\n {\n $query = new ProjectQuery();\n $query->setCurrentUser($this->getUser());\n $query->setPage($page);", " $form = $this->getToolbarForm($query);\n if ($this->handleSearch($form, $request)) {\n return $this->redirectToRoute('admin_project');\n }", " $entries = $this->repository->getPagerfantaForQuery($query);", " return $this->render('project/index.html.twig', [\n 'entries' => $entries,\n 'query' => $query,\n 'toolbarForm' => $form->createView(),\n 'metaColumns' => $this->findMetaColumns($query),\n 'now' => $this->getDateTimeFactory()->createDateTime(),\n ]);\n }", " /**\n * @param ProjectQuery $query\n * @return MetaTableTypeInterface[]\n */\n protected function findMetaColumns(ProjectQuery $query): array\n {\n $event = new ProjectMetaDisplayEvent($query, ProjectMetaDisplayEvent::PROJECT);\n $this->dispatcher->dispatch($event);", " return $event->getFields();\n }", " /**\n * @Route(path=\"/{id}/permissions\", name=\"admin_project_permissions\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('permissions', project)\")\n */\n public function teamPermissions(Project $project, Request $request)\n {\n $form = $this->createForm(ProjectTeamPermissionForm::class, $project, [\n 'action' => $this->generateUrl('admin_project_permissions', ['id' => $project->getId()]),\n 'method' => 'POST',\n ]);", " $form->handleRequest($request);", " if ($form->isSubmitted() && $form->isValid()) {\n try {\n $this->projectService->updateProject($project);\n $this->flashSuccess('action.update.success');", " if ($this->isGranted('view', $project)) {\n return $this->redirectToRoute('project_details', ['id' => $project->getId()]);\n }", " return $this->redirectToRoute('admin_project');\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " return $this->render('project/permissions.html.twig', [\n 'project' => $project,\n 'form' => $form->createView()\n ]);\n }", " /**\n * @Route(path=\"/create\", name=\"admin_project_create\", methods={\"GET\", \"POST\"})\n * @Route(path=\"/create/{customer}\", name=\"admin_project_create_with_customer\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('create_project')\")\n */\n public function createAction(Request $request, ?Customer $customer = null)\n {\n $project = $this->projectService->createNewProject($customer);", " $editForm = $this->createEditForm($project);\n $editForm->handleRequest($request);", " if ($editForm->isSubmitted() && $editForm->isValid()) {\n try {\n $this->projectService->saveNewProject($project);\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute('project_details', ['id' => $project->getId()]);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " return $this->render('project/edit.html.twig', [\n 'project' => $project,\n 'form' => $editForm->createView()\n ]);\n }", " /**\n * @Route(path=\"/{id}/comment_delete/{token}\", name=\"project_comment_delete\", methods={\"GET\"})\n * @Security(\"is_granted('edit', comment.getProject()) and is_granted('comments', comment.getProject())\")\n */\n public function deleteCommentAction(ProjectComment $comment, string $token, CsrfTokenManagerInterface $csrfTokenManager)\n {\n $projectId = $comment->getProject()->getId();", " if (!$csrfTokenManager->isTokenValid(new CsrfToken('project.delete_comment', $token))) {\n $this->flashError('action.csrf.error');", " return $this->redirectToRoute('project_details', ['id' => $projectId]);\n }", " $csrfTokenManager->refreshToken($token);", " try {\n $this->repository->deleteComment($comment);\n } catch (\\Exception $ex) {\n $this->flashDeleteException($ex);\n }", " return $this->redirectToRoute('project_details', ['id' => $projectId]);\n }", " /**\n * @Route(path=\"/{id}/comment_add\", name=\"project_comment_add\", methods={\"POST\"})\n * @Security(\"is_granted('comments_create', project)\")\n */\n public function addCommentAction(Project $project, Request $request)\n {\n $comment = new ProjectComment();\n $form = $this->getCommentForm($project, $comment);", " $form->handleRequest($request);", " if ($form->isSubmitted() && $form->isValid()) {\n try {\n $this->repository->saveComment($comment);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " return $this->redirectToRoute('project_details', ['id' => $project->getId()]);\n }", " /**\n * @Route(path=\"/{id}/comment_pin/{token}\", name=\"project_comment_pin\", methods={\"GET\"})\n * @Security(\"is_granted('edit', comment.getProject()) and is_granted('comments', comment.getProject())\")\n */\n public function pinCommentAction(ProjectComment $comment, string $token, CsrfTokenManagerInterface $csrfTokenManager)\n {\n $projectId = $comment->getProject()->getId();", " if (!$csrfTokenManager->isTokenValid(new CsrfToken('project.pin_comment', $token))) {\n $this->flashError('action.csrf.error');", " return $this->redirectToRoute('project_details', ['id' => $projectId]);\n }", " $csrfTokenManager->refreshToken($token);", " $comment->setPinned(!$comment->isPinned());\n try {\n $this->repository->saveComment($comment);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }", " return $this->redirectToRoute('project_details', ['id' => $projectId]);\n }", " /**\n * @Route(path=\"/{id}/create_team\", name=\"project_team_create\", methods={\"GET\"})\n * @Security(\"is_granted('create_team') and is_granted('edit', project)\")\n */\n public function createDefaultTeamAction(Project $project, TeamRepository $teamRepository)\n {\n $defaultTeam = $teamRepository->findOneBy(['name' => $project->getName()]);\n if (null !== $defaultTeam) {\n $this->flashError('action.update.error', ['%reason%' => 'Team already existing']);", " return $this->redirectToRoute('project_details', ['id' => $project->getId()]);\n }", " $defaultTeam = new Team();\n $defaultTeam->setName($project->getName());\n $defaultTeam->addTeamlead($this->getUser());\n $defaultTeam->addProject($project);", " try {\n $teamRepository->saveTeam($defaultTeam);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }", " return $this->redirectToRoute('project_details', ['id' => $project->getId()]);\n }", " /**\n * @Route(path=\"/{id}/activities/{page}\", defaults={\"page\": 1}, name=\"project_activities\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('view', project)\")\n */\n public function activitiesAction(Project $project, int $page, ActivityRepository $activityRepository)\n {\n $query = new ActivityQuery();\n $query->setCurrentUser($this->getUser());\n $query->setPage($page);\n $query->setPageSize(5);\n $query->addProject($project);\n $query->setExcludeGlobals(true);\n $query->setShowBoth();\n $query->addOrderGroup('visible', ActivityQuery::ORDER_DESC);\n $query->addOrderGroup('name', ActivityQuery::ORDER_ASC);", " /* @var $entries Pagerfanta */\n $entries = $activityRepository->getPagerfantaForQuery($query);", " return $this->render('project/embed_activities.html.twig', [\n 'project' => $project,\n 'activities' => $entries,\n 'page' => $page,\n 'now' => $this->getDateTimeFactory()->createDateTime(),\n ]);\n }", " /**\n * @Route(path=\"/{id}/details\", name=\"project_details\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('view', project)\")\n */\n public function detailsAction(Project $project, TeamRepository $teamRepository, ProjectRateRepository $rateRepository, ProjectStatisticService $statisticService)\n {\n $event = new ProjectMetaDefinitionEvent($project);\n $this->dispatcher->dispatch($event);", " $stats = null;\n $defaultTeam = null;\n $commentForm = null;\n $attachments = [];\n $comments = null;\n $teams = null;\n $rates = [];\n $now = $this->getDateTimeFactory()->createDateTime();", " if ($this->isGranted('edit', $project)) {\n if ($this->isGranted('create_team')) {\n $defaultTeam = $teamRepository->findOneBy(['name' => $project->getName()]);\n }\n $rates = $rateRepository->getRatesForProject($project);\n }", " if ($this->isGranted('budget', $project)) {\n $stats = $statisticService->getBudgetStatisticModel($project, $now);\n }", " if ($this->isGranted('comments', $project)) {\n $comments = $this->repository->getComments($project);\n }", " if ($this->isGranted('comments_create', $project)) {\n $commentForm = $this->getCommentForm($project, new ProjectComment())->createView();\n }", " if ($this->isGranted('permissions', $project) || $this->isGranted('details', $project) || $this->isGranted('view_team')) {\n $teams = $project->getTeams();\n }", " return $this->render('project/details.html.twig', [\n 'project' => $project,\n 'comments' => $comments,\n 'commentForm' => $commentForm,\n 'attachments' => $attachments,\n 'stats' => $stats,\n 'team' => $defaultTeam,\n 'teams' => $teams,\n 'rates' => $rates,\n 'now' => $now,\n ]);\n }", " /**\n * @Route(path=\"/{id}/rate\", name=\"admin_project_rate_add\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('edit', project)\")\n */\n public function addRateAction(Project $project, Request $request, ProjectRateRepository $repository)\n {\n $rate = new ProjectRate();\n $rate->setProject($project);", " $form = $this->createForm(ProjectRateForm::class, $rate, [\n 'action' => $this->generateUrl('admin_project_rate_add', ['id' => $project->getId()]),\n 'method' => 'POST',\n ]);", " $form->handleRequest($request);", " if ($form->isSubmitted() && $form->isValid()) {\n try {\n $repository->saveRate($rate);\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute('project_details', ['id' => $project->getId()]);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " return $this->render('project/rates.html.twig', [\n 'project' => $project,\n 'form' => $form->createView()\n ]);\n }", " /**\n * @Route(path=\"/{id}/edit\", name=\"admin_project_edit\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('edit', project)\")\n */\n public function editAction(Project $project, Request $request)\n {\n $editForm = $this->createEditForm($project);\n $editForm->handleRequest($request);", " if ($editForm->isSubmitted() && $editForm->isValid()) {\n try {\n $this->projectService->updateProject($project);\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute('project_details', ['id' => $project->getId()]);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " return $this->render('project/edit.html.twig', [\n 'project' => $project,\n 'form' => $editForm->createView()\n ]);\n }", " /**", " * @Route(path=\"/{id}/duplicate\", name=\"admin_project_duplicate\", methods={\"GET\", \"POST\"})", " * @Security(\"is_granted('edit', project)\")\n */", " public function duplicateAction(Project $project, Request $request, ProjectDuplicationService $projectDuplicationService)\n {", " $newProject = $projectDuplicationService->duplicate($project, $project->getName() . ' [COPY]');", "", "\n return $this->redirectToRoute('project_details', ['id' => $newProject->getId()]);\n }", " /**\n * @Route(path=\"/{id}/delete\", name=\"admin_project_delete\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('delete', project)\")\n */\n public function deleteAction(Project $project, Request $request, ProjectStatisticService $statisticService)\n {\n $stats = $statisticService->getProjectStatistics($project);", " $deleteForm = $this->createFormBuilder(null, [\n 'attr' => [\n 'data-form-event' => 'kimai.projectDelete',\n 'data-msg-success' => 'action.delete.success',\n 'data-msg-error' => 'action.delete.error',\n ]\n ])\n ->add('project', ProjectType::class, [\n 'ignore_project' => $project,\n 'customers' => $project->getCustomer(),\n 'query_builder_for_user' => true,\n 'required' => false,\n ])\n ->setAction($this->generateUrl('admin_project_delete', ['id' => $project->getId()]))\n ->setMethod('POST')\n ->getForm();", " $deleteForm->handleRequest($request);", " if ($deleteForm->isSubmitted() && $deleteForm->isValid()) {\n try {\n $this->repository->deleteProject($project, $deleteForm->get('project')->getData());\n $this->flashSuccess('action.delete.success');\n } catch (\\Exception $ex) {\n $this->flashDeleteException($ex);\n }", " return $this->redirectToRoute('admin_project');\n }", " return $this->render('project/delete.html.twig', [\n 'project' => $project,\n 'stats' => $stats,\n 'form' => $deleteForm->createView(),\n ]);\n }", " /**\n * @Route(path=\"/export\", name=\"project_export\", methods={\"GET\"})\n */\n public function exportAction(Request $request, EntityWithMetaFieldsExporter $exporter)\n {\n $query = new ProjectQuery();\n $query->setCurrentUser($this->getUser());", " $form = $this->getToolbarForm($query);\n $form->setData($query);\n $form->submit($request->query->all(), false);", " if (!$form->isValid()) {\n $query->resetByFormError($form->getErrors());\n }", " $entries = $this->repository->getProjectsForQuery($query);", " $spreadsheet = $exporter->export(\n Project::class,\n $entries,\n new ProjectMetaDisplayEvent($query, ProjectMetaDisplayEvent::EXPORT)\n );\n $writer = new BinaryFileResponseWriter(new XlsxWriter(), 'kimai-projects');", " return $writer->getFileResponse($spreadsheet);\n }", " protected function getToolbarForm(ProjectQuery $query): FormInterface\n {\n return $this->createForm(ProjectToolbarForm::class, $query, [\n 'action' => $this->generateUrl('admin_project', [\n 'page' => $query->getPage(),\n ]),\n 'method' => 'GET',\n ]);\n }", " private function getCommentForm(Project $project, ProjectComment $comment): FormInterface\n {\n if (null === $comment->getId()) {\n $comment->setProject($project);\n $comment->setCreatedBy($this->getUser());\n }", " return $this->createForm(ProjectCommentForm::class, $comment, [\n 'action' => $this->generateUrl('project_comment_add', ['id' => $project->getId()]),\n 'method' => 'POST',\n ]);\n }", " private function createEditForm(Project $project): FormInterface\n {\n $event = new ProjectMetaDefinitionEvent($project);\n $this->dispatcher->dispatch($event);", " $currency = $this->configuration->getCustomerDefaultCurrency();\n $url = $this->generateUrl('admin_project_create');", " if ($project->getId() !== null) {\n $url = $this->generateUrl('admin_project_edit', ['id' => $project->getId()]);\n $currency = $project->getCustomer()->getCurrency();\n }", " return $this->createForm(ProjectEditForm::class, $project, [\n 'action' => $url,\n 'method' => 'POST',\n 'currency' => $currency,\n 'timezone' => $this->getDateTimeFactory()->getTimezone()->getName(),\n 'include_budget' => $this->isGranted('budget', $project),\n 'time_increment' => 15,\n ]);\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace App\\Controller;", "use App\\Configuration\\SystemConfiguration;\nuse App\\Entity\\Customer;\nuse App\\Entity\\MetaTableTypeInterface;\nuse App\\Entity\\Project;\nuse App\\Entity\\ProjectComment;\nuse App\\Entity\\ProjectRate;\nuse App\\Entity\\Rate;\nuse App\\Entity\\Team;\nuse App\\Event\\ProjectMetaDefinitionEvent;\nuse App\\Event\\ProjectMetaDisplayEvent;\nuse App\\Export\\Spreadsheet\\EntityWithMetaFieldsExporter;\nuse App\\Export\\Spreadsheet\\Writer\\BinaryFileResponseWriter;\nuse App\\Export\\Spreadsheet\\Writer\\XlsxWriter;\nuse App\\Form\\ProjectCommentForm;\nuse App\\Form\\ProjectEditForm;\nuse App\\Form\\ProjectRateForm;\nuse App\\Form\\ProjectTeamPermissionForm;\nuse App\\Form\\Toolbar\\ProjectToolbarForm;\nuse App\\Form\\Type\\ProjectType;\nuse App\\Project\\ProjectDuplicationService;\nuse App\\Project\\ProjectService;\nuse App\\Project\\ProjectStatisticService;\nuse App\\Repository\\ActivityRepository;\nuse App\\Repository\\ProjectRateRepository;\nuse App\\Repository\\ProjectRepository;\nuse App\\Repository\\Query\\ActivityQuery;\nuse App\\Repository\\Query\\ProjectQuery;\nuse App\\Repository\\TeamRepository;\nuse Pagerfanta\\Pagerfanta;\nuse Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Security;\nuse Symfony\\Component\\EventDispatcher\\EventDispatcherInterface;\nuse Symfony\\Component\\Form\\FormInterface;\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\Routing\\Annotation\\Route;\nuse Symfony\\Component\\Security\\Csrf\\CsrfToken;\nuse Symfony\\Component\\Security\\Csrf\\CsrfTokenManagerInterface;", "/**\n * Controller used to manage projects.\n *\n * @Route(path=\"/admin/project\")\n * @Security(\"is_granted('view_project') or is_granted('view_teamlead_project') or is_granted('view_team_project')\")\n */\nfinal class ProjectController extends AbstractController\n{\n /**\n * @var ProjectRepository\n */\n private $repository;\n /**\n * @var SystemConfiguration\n */\n private $configuration;\n /**\n * @var EventDispatcherInterface\n */\n private $dispatcher;\n /**\n * @var ProjectService\n */\n private $projectService;", " public function __construct(ProjectRepository $repository, SystemConfiguration $configuration, EventDispatcherInterface $dispatcher, ProjectService $projectService)\n {\n $this->repository = $repository;\n $this->configuration = $configuration;\n $this->dispatcher = $dispatcher;\n $this->projectService = $projectService;\n }", " /**\n * @Route(path=\"/\", defaults={\"page\": 1}, name=\"admin_project\", methods={\"GET\"})\n * @Route(path=\"/page/{page}\", requirements={\"page\": \"[1-9]\\d*\"}, name=\"admin_project_paginated\", methods={\"GET\"})\n */\n public function indexAction($page, Request $request)\n {\n $query = new ProjectQuery();\n $query->setCurrentUser($this->getUser());\n $query->setPage($page);", " $form = $this->getToolbarForm($query);\n if ($this->handleSearch($form, $request)) {\n return $this->redirectToRoute('admin_project');\n }", " $entries = $this->repository->getPagerfantaForQuery($query);", " return $this->render('project/index.html.twig', [\n 'entries' => $entries,\n 'query' => $query,\n 'toolbarForm' => $form->createView(),\n 'metaColumns' => $this->findMetaColumns($query),\n 'now' => $this->getDateTimeFactory()->createDateTime(),\n ]);\n }", " /**\n * @param ProjectQuery $query\n * @return MetaTableTypeInterface[]\n */\n protected function findMetaColumns(ProjectQuery $query): array\n {\n $event = new ProjectMetaDisplayEvent($query, ProjectMetaDisplayEvent::PROJECT);\n $this->dispatcher->dispatch($event);", " return $event->getFields();\n }", " /**\n * @Route(path=\"/{id}/permissions\", name=\"admin_project_permissions\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('permissions', project)\")\n */\n public function teamPermissions(Project $project, Request $request)\n {\n $form = $this->createForm(ProjectTeamPermissionForm::class, $project, [\n 'action' => $this->generateUrl('admin_project_permissions', ['id' => $project->getId()]),\n 'method' => 'POST',\n ]);", " $form->handleRequest($request);", " if ($form->isSubmitted() && $form->isValid()) {\n try {\n $this->projectService->updateProject($project);\n $this->flashSuccess('action.update.success');", " if ($this->isGranted('view', $project)) {\n return $this->redirectToRoute('project_details', ['id' => $project->getId()]);\n }", " return $this->redirectToRoute('admin_project');\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " return $this->render('project/permissions.html.twig', [\n 'project' => $project,\n 'form' => $form->createView()\n ]);\n }", " /**\n * @Route(path=\"/create\", name=\"admin_project_create\", methods={\"GET\", \"POST\"})\n * @Route(path=\"/create/{customer}\", name=\"admin_project_create_with_customer\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('create_project')\")\n */\n public function createAction(Request $request, ?Customer $customer = null)\n {\n $project = $this->projectService->createNewProject($customer);", " $editForm = $this->createEditForm($project);\n $editForm->handleRequest($request);", " if ($editForm->isSubmitted() && $editForm->isValid()) {\n try {\n $this->projectService->saveNewProject($project);\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute('project_details', ['id' => $project->getId()]);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " return $this->render('project/edit.html.twig', [\n 'project' => $project,\n 'form' => $editForm->createView()\n ]);\n }", " /**\n * @Route(path=\"/{id}/comment_delete/{token}\", name=\"project_comment_delete\", methods={\"GET\"})\n * @Security(\"is_granted('edit', comment.getProject()) and is_granted('comments', comment.getProject())\")\n */\n public function deleteCommentAction(ProjectComment $comment, string $token, CsrfTokenManagerInterface $csrfTokenManager)\n {\n $projectId = $comment->getProject()->getId();", " if (!$csrfTokenManager->isTokenValid(new CsrfToken('project.delete_comment', $token))) {\n $this->flashError('action.csrf.error');", " return $this->redirectToRoute('project_details', ['id' => $projectId]);\n }", " $csrfTokenManager->refreshToken($token);", " try {\n $this->repository->deleteComment($comment);\n } catch (\\Exception $ex) {\n $this->flashDeleteException($ex);\n }", " return $this->redirectToRoute('project_details', ['id' => $projectId]);\n }", " /**\n * @Route(path=\"/{id}/comment_add\", name=\"project_comment_add\", methods={\"POST\"})\n * @Security(\"is_granted('comments_create', project)\")\n */\n public function addCommentAction(Project $project, Request $request)\n {\n $comment = new ProjectComment();\n $form = $this->getCommentForm($project, $comment);", " $form->handleRequest($request);", " if ($form->isSubmitted() && $form->isValid()) {\n try {\n $this->repository->saveComment($comment);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " return $this->redirectToRoute('project_details', ['id' => $project->getId()]);\n }", " /**\n * @Route(path=\"/{id}/comment_pin/{token}\", name=\"project_comment_pin\", methods={\"GET\"})\n * @Security(\"is_granted('edit', comment.getProject()) and is_granted('comments', comment.getProject())\")\n */\n public function pinCommentAction(ProjectComment $comment, string $token, CsrfTokenManagerInterface $csrfTokenManager)\n {\n $projectId = $comment->getProject()->getId();", " if (!$csrfTokenManager->isTokenValid(new CsrfToken('project.pin_comment', $token))) {\n $this->flashError('action.csrf.error');", " return $this->redirectToRoute('project_details', ['id' => $projectId]);\n }", " $csrfTokenManager->refreshToken($token);", " $comment->setPinned(!$comment->isPinned());\n try {\n $this->repository->saveComment($comment);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }", " return $this->redirectToRoute('project_details', ['id' => $projectId]);\n }", " /**\n * @Route(path=\"/{id}/create_team\", name=\"project_team_create\", methods={\"GET\"})\n * @Security(\"is_granted('create_team') and is_granted('edit', project)\")\n */\n public function createDefaultTeamAction(Project $project, TeamRepository $teamRepository)\n {\n $defaultTeam = $teamRepository->findOneBy(['name' => $project->getName()]);\n if (null !== $defaultTeam) {\n $this->flashError('action.update.error', ['%reason%' => 'Team already existing']);", " return $this->redirectToRoute('project_details', ['id' => $project->getId()]);\n }", " $defaultTeam = new Team();\n $defaultTeam->setName($project->getName());\n $defaultTeam->addTeamlead($this->getUser());\n $defaultTeam->addProject($project);", " try {\n $teamRepository->saveTeam($defaultTeam);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }", " return $this->redirectToRoute('project_details', ['id' => $project->getId()]);\n }", " /**\n * @Route(path=\"/{id}/activities/{page}\", defaults={\"page\": 1}, name=\"project_activities\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('view', project)\")\n */\n public function activitiesAction(Project $project, int $page, ActivityRepository $activityRepository)\n {\n $query = new ActivityQuery();\n $query->setCurrentUser($this->getUser());\n $query->setPage($page);\n $query->setPageSize(5);\n $query->addProject($project);\n $query->setExcludeGlobals(true);\n $query->setShowBoth();\n $query->addOrderGroup('visible', ActivityQuery::ORDER_DESC);\n $query->addOrderGroup('name', ActivityQuery::ORDER_ASC);", " /* @var $entries Pagerfanta */\n $entries = $activityRepository->getPagerfantaForQuery($query);", " return $this->render('project/embed_activities.html.twig', [\n 'project' => $project,\n 'activities' => $entries,\n 'page' => $page,\n 'now' => $this->getDateTimeFactory()->createDateTime(),\n ]);\n }", " /**\n * @Route(path=\"/{id}/details\", name=\"project_details\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('view', project)\")\n */\n public function detailsAction(Project $project, TeamRepository $teamRepository, ProjectRateRepository $rateRepository, ProjectStatisticService $statisticService)\n {\n $event = new ProjectMetaDefinitionEvent($project);\n $this->dispatcher->dispatch($event);", " $stats = null;\n $defaultTeam = null;\n $commentForm = null;\n $attachments = [];\n $comments = null;\n $teams = null;\n $rates = [];\n $now = $this->getDateTimeFactory()->createDateTime();", " if ($this->isGranted('edit', $project)) {\n if ($this->isGranted('create_team')) {\n $defaultTeam = $teamRepository->findOneBy(['name' => $project->getName()]);\n }\n $rates = $rateRepository->getRatesForProject($project);\n }", " if ($this->isGranted('budget', $project)) {\n $stats = $statisticService->getBudgetStatisticModel($project, $now);\n }", " if ($this->isGranted('comments', $project)) {\n $comments = $this->repository->getComments($project);\n }", " if ($this->isGranted('comments_create', $project)) {\n $commentForm = $this->getCommentForm($project, new ProjectComment())->createView();\n }", " if ($this->isGranted('permissions', $project) || $this->isGranted('details', $project) || $this->isGranted('view_team')) {\n $teams = $project->getTeams();\n }", " return $this->render('project/details.html.twig', [\n 'project' => $project,\n 'comments' => $comments,\n 'commentForm' => $commentForm,\n 'attachments' => $attachments,\n 'stats' => $stats,\n 'team' => $defaultTeam,\n 'teams' => $teams,\n 'rates' => $rates,\n 'now' => $now,\n ]);\n }", " /**\n * @Route(path=\"/{id}/rate\", name=\"admin_project_rate_add\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('edit', project)\")\n */\n public function addRateAction(Project $project, Request $request, ProjectRateRepository $repository)\n {\n $rate = new ProjectRate();\n $rate->setProject($project);", " $form = $this->createForm(ProjectRateForm::class, $rate, [\n 'action' => $this->generateUrl('admin_project_rate_add', ['id' => $project->getId()]),\n 'method' => 'POST',\n ]);", " $form->handleRequest($request);", " if ($form->isSubmitted() && $form->isValid()) {\n try {\n $repository->saveRate($rate);\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute('project_details', ['id' => $project->getId()]);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " return $this->render('project/rates.html.twig', [\n 'project' => $project,\n 'form' => $form->createView()\n ]);\n }", " /**\n * @Route(path=\"/{id}/edit\", name=\"admin_project_edit\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('edit', project)\")\n */\n public function editAction(Project $project, Request $request)\n {\n $editForm = $this->createEditForm($project);\n $editForm->handleRequest($request);", " if ($editForm->isSubmitted() && $editForm->isValid()) {\n try {\n $this->projectService->updateProject($project);\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute('project_details', ['id' => $project->getId()]);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " return $this->render('project/edit.html.twig', [\n 'project' => $project,\n 'form' => $editForm->createView()\n ]);\n }", " /**", " * @Route(path=\"/{id}/duplicate/{token}\", name=\"admin_project_duplicate\", methods={\"GET\", \"POST\"})", " * @Security(\"is_granted('edit', project)\")\n */", " public function duplicateAction(Project $project, string $token, ProjectDuplicationService $projectDuplicationService, CsrfTokenManagerInterface $csrfTokenManager)\n {\n if (!$csrfTokenManager->isTokenValid(new CsrfToken('project.duplicate', $token))) {\n $this->flashError('action.csrf.error');", " return $this->redirectToRoute('project_details', ['id' => $project->getId()]);\n }", " $csrfTokenManager->refreshToken($token);\n", " $newProject = $projectDuplicationService->duplicate($project, $project->getName() . ' [COPY]');", "\n $this->flashSuccess('action.update.success');", "\n return $this->redirectToRoute('project_details', ['id' => $newProject->getId()]);\n }", " /**\n * @Route(path=\"/{id}/delete\", name=\"admin_project_delete\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('delete', project)\")\n */\n public function deleteAction(Project $project, Request $request, ProjectStatisticService $statisticService)\n {\n $stats = $statisticService->getProjectStatistics($project);", " $deleteForm = $this->createFormBuilder(null, [\n 'attr' => [\n 'data-form-event' => 'kimai.projectDelete',\n 'data-msg-success' => 'action.delete.success',\n 'data-msg-error' => 'action.delete.error',\n ]\n ])\n ->add('project', ProjectType::class, [\n 'ignore_project' => $project,\n 'customers' => $project->getCustomer(),\n 'query_builder_for_user' => true,\n 'required' => false,\n ])\n ->setAction($this->generateUrl('admin_project_delete', ['id' => $project->getId()]))\n ->setMethod('POST')\n ->getForm();", " $deleteForm->handleRequest($request);", " if ($deleteForm->isSubmitted() && $deleteForm->isValid()) {\n try {\n $this->repository->deleteProject($project, $deleteForm->get('project')->getData());\n $this->flashSuccess('action.delete.success');\n } catch (\\Exception $ex) {\n $this->flashDeleteException($ex);\n }", " return $this->redirectToRoute('admin_project');\n }", " return $this->render('project/delete.html.twig', [\n 'project' => $project,\n 'stats' => $stats,\n 'form' => $deleteForm->createView(),\n ]);\n }", " /**\n * @Route(path=\"/export\", name=\"project_export\", methods={\"GET\"})\n */\n public function exportAction(Request $request, EntityWithMetaFieldsExporter $exporter)\n {\n $query = new ProjectQuery();\n $query->setCurrentUser($this->getUser());", " $form = $this->getToolbarForm($query);\n $form->setData($query);\n $form->submit($request->query->all(), false);", " if (!$form->isValid()) {\n $query->resetByFormError($form->getErrors());\n }", " $entries = $this->repository->getProjectsForQuery($query);", " $spreadsheet = $exporter->export(\n Project::class,\n $entries,\n new ProjectMetaDisplayEvent($query, ProjectMetaDisplayEvent::EXPORT)\n );\n $writer = new BinaryFileResponseWriter(new XlsxWriter(), 'kimai-projects');", " return $writer->getFileResponse($spreadsheet);\n }", " protected function getToolbarForm(ProjectQuery $query): FormInterface\n {\n return $this->createForm(ProjectToolbarForm::class, $query, [\n 'action' => $this->generateUrl('admin_project', [\n 'page' => $query->getPage(),\n ]),\n 'method' => 'GET',\n ]);\n }", " private function getCommentForm(Project $project, ProjectComment $comment): FormInterface\n {\n if (null === $comment->getId()) {\n $comment->setProject($project);\n $comment->setCreatedBy($this->getUser());\n }", " return $this->createForm(ProjectCommentForm::class, $comment, [\n 'action' => $this->generateUrl('project_comment_add', ['id' => $project->getId()]),\n 'method' => 'POST',\n ]);\n }", " private function createEditForm(Project $project): FormInterface\n {\n $event = new ProjectMetaDefinitionEvent($project);\n $this->dispatcher->dispatch($event);", " $currency = $this->configuration->getCustomerDefaultCurrency();\n $url = $this->generateUrl('admin_project_create');", " if ($project->getId() !== null) {\n $url = $this->generateUrl('admin_project_edit', ['id' => $project->getId()]);\n $currency = $project->getCustomer()->getCurrency();\n }", " return $this->createForm(ProjectEditForm::class, $project, [\n 'action' => $url,\n 'method' => 'POST',\n 'currency' => $currency,\n 'timezone' => $this->getDateTimeFactory()->getTimezone()->getName(),\n 'include_budget' => $this->isGranted('budget', $project),\n 'time_increment' => 15,\n ]);\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace App\\Controller;", "use App\\Entity\\Team;\nuse App\\Form\\TeamCustomerForm;\nuse App\\Form\\TeamEditForm;\nuse App\\Form\\TeamProjectForm;\nuse App\\Form\\Toolbar\\TeamToolbarForm;\nuse App\\Repository\\Query\\TeamQuery;\nuse App\\Repository\\TeamRepository;\nuse Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Security;\nuse Symfony\\Component\\Form\\FormInterface;\nuse Symfony\\Component\\HttpFoundation\\RedirectResponse;\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\HttpFoundation\\Response;\nuse Symfony\\Component\\Routing\\Annotation\\Route;", "", "\n/**\n * @Route(path=\"/admin/teams\")\n * @Security(\"is_granted('view_team')\")\n */\nfinal class TeamController extends AbstractController\n{\n /**\n * @var TeamRepository\n */\n private $repository;", " public function __construct(TeamRepository $repository)\n {\n $this->repository = $repository;\n }", " /**\n * @Route(path=\"/\", defaults={\"page\": 1}, name=\"admin_team\", methods={\"GET\"})\n * @Route(path=\"/page/{page}\", requirements={\"page\": \"[1-9]\\d*\"}, name=\"admin_team_paginated\", methods={\"GET\"})\n *\n * @param TeamRepository $repository\n * @param Request $request\n * @param int $page\n * @return Response\n */\n public function listTeams(TeamRepository $repository, Request $request, $page)\n {\n $query = new TeamQuery();\n $query->setPage($page);\n $query->setCurrentUser($this->getUser());", " $form = $this->getToolbarForm($query);\n if ($this->handleSearch($form, $request)) {\n return $this->redirectToRoute('admin_team');\n }", " $teams = $repository->getPagerfantaForQuery($query);", " return $this->render('team/index.html.twig', [\n 'teams' => $teams,\n 'query' => $query,\n 'toolbarForm' => $form->createView(),\n ]);\n }", " /**\n * @Route(path=\"/create\", name=\"admin_team_create\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('create_team')\")\n *\n * @param Request $request\n * @return RedirectResponse|Response\n */\n public function createTeam(Request $request)\n {\n return $this->renderEditScreen(new Team(), $request);\n }", " /**", " * @Route(path=\"/{id}/duplicate\", name=\"team_duplicate\", methods={\"GET\", \"POST\"})", " * @Security(\"is_granted('edit', team) and is_granted('create_team')\")\n */", " public function duplicateTeam(Team $team, Request $request)\n {", " $newTeam = clone $team;\n $newTeam->setName($team->getName() . ' [COPY]');", " try {\n $this->repository->saveTeam($newTeam);\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute('admin_team_edit', ['id' => $newTeam->getId()]);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }", " return $this->redirectToRoute('admin_team');\n }", " /**\n * @Route(path=\"/{id}/edit\", name=\"admin_team_edit\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('edit', team)\")\n */\n public function editAction(Team $team, Request $request)\n {\n return $this->renderEditScreen($team, $request);\n }", " /**\n * @Route(path=\"/{id}/edit_member\", name=\"admin_team_member\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('edit', team)\")\n */\n public function editMemberAction(Team $team, Request $request)\n {\n $editForm = $this->createForm(TeamEditForm::class, $team, [\n 'action' => $this->generateUrl('admin_team_member', ['id' => $team->getId()]),\n 'method' => 'POST',\n ]);", " $editForm->handleRequest($request);", " if ($editForm->isSubmitted() && $editForm->isValid()) {\n try {\n $this->repository->saveTeam($team);\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute('admin_team_edit', ['id' => $team->getId()]);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " return $this->render('team/edit_member.html.twig', [\n 'team' => $team,\n 'form' => $editForm->createView(),\n ]);\n }", " private function renderEditScreen(Team $team, Request $request): Response\n {\n $customerForm = null;\n $projectForm = null;", " if ($team->getId() === null) {\n $url = $this->generateUrl('admin_team_create');\n } else {\n $url = $this->generateUrl('admin_team_edit', ['id' => $team->getId()]);\n }", " $editForm = $this->createForm(TeamEditForm::class, $team, [\n 'action' => $url,\n 'method' => 'POST',\n ]);", " $editForm->handleRequest($request);", " if ($editForm->isSubmitted() && $editForm->isValid()) {\n try {\n $this->repository->saveTeam($team);\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute('admin_team_edit', ['id' => $team->getId()]);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " if (null !== $team->getId()) {\n $customerForm = $this->createForm(TeamCustomerForm::class, $team, [\n 'method' => 'POST',\n ]);\n $customerForm->handleRequest($request);", " if ($customerForm->isSubmitted() && $customerForm->isValid()) {\n try {\n $this->repository->saveTeam($team);\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute('admin_team_edit', ['id' => $team->getId()]);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " $projectForm = $this->createForm(TeamProjectForm::class, $team, [\n 'method' => 'POST',\n ]);\n $projectForm->handleRequest($request);", " if ($projectForm->isSubmitted() && $projectForm->isValid()) {\n try {\n $this->repository->saveTeam($team);\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute('admin_team_edit', ['id' => $team->getId()]);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }\n }", " return $this->render('team/edit.html.twig', [\n 'team' => $team,\n 'form' => $editForm->createView(),\n 'customerForm' => $customerForm ? $customerForm->createView() : null,\n 'projectForm' => $projectForm ? $projectForm->createView() : null,\n ]);\n }", " private function getToolbarForm(TeamQuery $query): FormInterface\n {\n return $this->createForm(TeamToolbarForm::class, $query, [\n 'action' => $this->generateUrl('admin_team', [\n 'page' => $query->getPage(),\n ]),\n 'method' => 'GET',\n ]);\n }\n}" ]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace App\\Controller;", "use App\\Entity\\Team;\nuse App\\Form\\TeamCustomerForm;\nuse App\\Form\\TeamEditForm;\nuse App\\Form\\TeamProjectForm;\nuse App\\Form\\Toolbar\\TeamToolbarForm;\nuse App\\Repository\\Query\\TeamQuery;\nuse App\\Repository\\TeamRepository;\nuse Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Security;\nuse Symfony\\Component\\Form\\FormInterface;\nuse Symfony\\Component\\HttpFoundation\\RedirectResponse;\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\HttpFoundation\\Response;\nuse Symfony\\Component\\Routing\\Annotation\\Route;", "use Symfony\\Component\\Security\\Csrf\\CsrfToken;\nuse Symfony\\Component\\Security\\Csrf\\CsrfTokenManagerInterface;", "\n/**\n * @Route(path=\"/admin/teams\")\n * @Security(\"is_granted('view_team')\")\n */\nfinal class TeamController extends AbstractController\n{\n /**\n * @var TeamRepository\n */\n private $repository;", " public function __construct(TeamRepository $repository)\n {\n $this->repository = $repository;\n }", " /**\n * @Route(path=\"/\", defaults={\"page\": 1}, name=\"admin_team\", methods={\"GET\"})\n * @Route(path=\"/page/{page}\", requirements={\"page\": \"[1-9]\\d*\"}, name=\"admin_team_paginated\", methods={\"GET\"})\n *\n * @param TeamRepository $repository\n * @param Request $request\n * @param int $page\n * @return Response\n */\n public function listTeams(TeamRepository $repository, Request $request, $page)\n {\n $query = new TeamQuery();\n $query->setPage($page);\n $query->setCurrentUser($this->getUser());", " $form = $this->getToolbarForm($query);\n if ($this->handleSearch($form, $request)) {\n return $this->redirectToRoute('admin_team');\n }", " $teams = $repository->getPagerfantaForQuery($query);", " return $this->render('team/index.html.twig', [\n 'teams' => $teams,\n 'query' => $query,\n 'toolbarForm' => $form->createView(),\n ]);\n }", " /**\n * @Route(path=\"/create\", name=\"admin_team_create\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('create_team')\")\n *\n * @param Request $request\n * @return RedirectResponse|Response\n */\n public function createTeam(Request $request)\n {\n return $this->renderEditScreen(new Team(), $request);\n }", " /**", " * @Route(path=\"/{id}/duplicate/{token}\", name=\"team_duplicate\", methods={\"GET\", \"POST\"})", " * @Security(\"is_granted('edit', team) and is_granted('create_team')\")\n */", " public function duplicateTeam(Team $team, string $token, CsrfTokenManagerInterface $csrfTokenManager)\n {\n if (!$csrfTokenManager->isTokenValid(new CsrfToken('team.duplicate', $token))) {\n $this->flashError('action.csrf.error');", " return $this->redirectToRoute('admin_team_edit', ['id' => $team->getId()]);\n }", " $csrfTokenManager->refreshToken($token);\n", " $newTeam = clone $team;\n $newTeam->setName($team->getName() . ' [COPY]');", " try {\n $this->repository->saveTeam($newTeam);\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute('admin_team_edit', ['id' => $newTeam->getId()]);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }", " return $this->redirectToRoute('admin_team');\n }", " /**\n * @Route(path=\"/{id}/edit\", name=\"admin_team_edit\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('edit', team)\")\n */\n public function editAction(Team $team, Request $request)\n {\n return $this->renderEditScreen($team, $request);\n }", " /**\n * @Route(path=\"/{id}/edit_member\", name=\"admin_team_member\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('edit', team)\")\n */\n public function editMemberAction(Team $team, Request $request)\n {\n $editForm = $this->createForm(TeamEditForm::class, $team, [\n 'action' => $this->generateUrl('admin_team_member', ['id' => $team->getId()]),\n 'method' => 'POST',\n ]);", " $editForm->handleRequest($request);", " if ($editForm->isSubmitted() && $editForm->isValid()) {\n try {\n $this->repository->saveTeam($team);\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute('admin_team_edit', ['id' => $team->getId()]);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " return $this->render('team/edit_member.html.twig', [\n 'team' => $team,\n 'form' => $editForm->createView(),\n ]);\n }", " private function renderEditScreen(Team $team, Request $request): Response\n {\n $customerForm = null;\n $projectForm = null;", " if ($team->getId() === null) {\n $url = $this->generateUrl('admin_team_create');\n } else {\n $url = $this->generateUrl('admin_team_edit', ['id' => $team->getId()]);\n }", " $editForm = $this->createForm(TeamEditForm::class, $team, [\n 'action' => $url,\n 'method' => 'POST',\n ]);", " $editForm->handleRequest($request);", " if ($editForm->isSubmitted() && $editForm->isValid()) {\n try {\n $this->repository->saveTeam($team);\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute('admin_team_edit', ['id' => $team->getId()]);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " if (null !== $team->getId()) {\n $customerForm = $this->createForm(TeamCustomerForm::class, $team, [\n 'method' => 'POST',\n ]);\n $customerForm->handleRequest($request);", " if ($customerForm->isSubmitted() && $customerForm->isValid()) {\n try {\n $this->repository->saveTeam($team);\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute('admin_team_edit', ['id' => $team->getId()]);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " $projectForm = $this->createForm(TeamProjectForm::class, $team, [\n 'method' => 'POST',\n ]);\n $projectForm->handleRequest($request);", " if ($projectForm->isSubmitted() && $projectForm->isValid()) {\n try {\n $this->repository->saveTeam($team);\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute('admin_team_edit', ['id' => $team->getId()]);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }\n }", " return $this->render('team/edit.html.twig', [\n 'team' => $team,\n 'form' => $editForm->createView(),\n 'customerForm' => $customerForm ? $customerForm->createView() : null,\n 'projectForm' => $projectForm ? $projectForm->createView() : null,\n ]);\n }", " private function getToolbarForm(TeamQuery $query): FormInterface\n {\n return $this->createForm(TeamToolbarForm::class, $query, [\n 'action' => $this->generateUrl('admin_team', [\n 'page' => $query->getPage(),\n ]),\n 'method' => 'GET',\n ]);\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace App\\Controller;", "use App\\Configuration\\SystemConfiguration;\nuse App\\Entity\\MetaTableTypeInterface;\nuse App\\Entity\\Tag;\nuse App\\Entity\\Timesheet;\nuse App\\Event\\TimesheetDuplicatePostEvent;\nuse App\\Event\\TimesheetDuplicatePreEvent;\nuse App\\Event\\TimesheetMetaDefinitionEvent;\nuse App\\Event\\TimesheetMetaDisplayEvent;\nuse App\\Export\\ServiceExport;\nuse App\\Form\\MultiUpdate\\MultiUpdateTable;\nuse App\\Form\\MultiUpdate\\MultiUpdateTableDTO;\nuse App\\Form\\MultiUpdate\\TimesheetMultiUpdate;\nuse App\\Form\\MultiUpdate\\TimesheetMultiUpdateDTO;\nuse App\\Form\\TimesheetEditForm;\nuse App\\Form\\Toolbar\\TimesheetExportToolbarForm;\nuse App\\Form\\Toolbar\\TimesheetToolbarForm;\nuse App\\Repository\\ActivityRepository;\nuse App\\Repository\\ProjectRepository;\nuse App\\Repository\\Query\\TimesheetQuery;\nuse App\\Repository\\TagRepository;\nuse App\\Repository\\TimesheetRepository;\nuse App\\Timesheet\\TimesheetService;\nuse App\\Timesheet\\TrackingMode\\TrackingModeInterface;\nuse Doctrine\\Common\\Collections\\ArrayCollection;\nuse Symfony\\Component\\EventDispatcher\\EventDispatcherInterface;\nuse Symfony\\Component\\Form\\FormError;\nuse Symfony\\Component\\Form\\FormInterface;\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\HttpFoundation\\Response;", "abstract class TimesheetAbstractController extends AbstractController\n{\n /**\n * @var TimesheetRepository\n */\n protected $repository;\n /**\n * @var EventDispatcherInterface\n */\n protected $dispatcher;\n /**\n * @var TimesheetService\n */\n protected $service;\n /**\n * @var SystemConfiguration\n */\n protected $configuration;", " public function __construct(\n TimesheetRepository $repository,\n EventDispatcherInterface $dispatcher,\n TimesheetService $timesheetService,\n SystemConfiguration $configuration\n ) {\n $this->repository = $repository;\n $this->dispatcher = $dispatcher;\n $this->service = $timesheetService;\n $this->configuration = $configuration;\n }", " protected function getTrackingMode(): TrackingModeInterface\n {\n return $this->service->getActiveTrackingMode();\n }", " protected function index(TimesheetQuery $query, Request $request, string $route, string $renderTemplate, string $location): Response\n {\n $form = $this->getToolbarForm($query);\n if ($this->handleSearch($form, $request)) {\n return $this->redirectToRoute($route);\n }", " $tags = $query->getTags(true);\n if (!empty($tags)) {\n /** @var TagRepository $tagRepo */\n $tagRepo = $this->getDoctrine()->getRepository(Tag::class);\n $query->setTags(\n new ArrayCollection(\n $tagRepo->findIdsByTagNameList(implode(',', $tags))\n )\n );\n }", " $this->prepareQuery($query);", " $pager = $this->repository->getPagerfantaForQuery($query);", " return $this->render($renderTemplate, [\n 'entries' => $pager,\n 'page' => $query->getPage(),\n 'query' => $query,\n 'toolbarForm' => $form->createView(),\n 'multiUpdateForm' => $this->getMultiUpdateActionForm()->createView(),\n 'showSummary' => $this->includeSummary(),\n 'showStartEndTime' => $this->canSeeStartEndTime(),\n 'metaColumns' => $this->findMetaColumns($query, $location),\n ]);\n }", " /**\n * @param TimesheetQuery $query\n * @param string $location\n * @return MetaTableTypeInterface[]\n */\n protected function findMetaColumns(TimesheetQuery $query, string $location): array\n {\n $event = new TimesheetMetaDisplayEvent($query, $location);\n $this->dispatcher->dispatch($event);", " return $event->getFields();\n }", " protected function edit(Timesheet $entry, Request $request, string $renderTemplate): Response\n {\n $event = new TimesheetMetaDefinitionEvent($entry);\n $this->dispatcher->dispatch($event);", " $editForm = $this->getEditForm($entry, $request->get('page'));\n $editForm->handleRequest($request);", " if ($editForm->isSubmitted() && $editForm->isValid()) {\n try {\n $this->service->updateTimesheet($entry);\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute($this->getTimesheetRoute(), ['page' => $request->get('page', 1)]);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " return $this->render($renderTemplate, [\n 'timesheet' => $entry,\n 'form' => $editForm->createView(),\n ]);\n }", " protected function getTags(TagRepository $tagRepository, $tagNames)\n {\n $tags = [];\n if (!\\is_array($tagNames)) {\n $tagNames = explode(',', $tagNames);\n }\n foreach ($tagNames as $tagName) {\n $tag = $tagRepository->findTagByName($tagName);\n if (!$tag) {\n $tag = new Tag();\n $tag->setName($tagName);\n }\n $tags[] = $tag;\n }", " return $tags;\n }", " protected function create(Request $request, string $renderTemplate, ProjectRepository $projectRepository, ActivityRepository $activityRepository, TagRepository $tagRepository): Response\n {\n $entry = $this->service->createNewTimesheet($this->getUser());", " if ($request->query->get('project')) {\n $project = $projectRepository->find($request->query->get('project'));\n $entry->setProject($project);\n }", " if ($request->query->get('activity')) {\n $activity = $activityRepository->find($request->query->get('activity'));\n $entry->setActivity($activity);\n }", " if ($request->query->get('description')) {\n $description = $request->query->get('description');\n $entry->setDescription($description);\n }", " if ($request->query->get('tags')) {\n foreach ($this->getTags($tagRepository, $request->query->get('tags')) as $tag) {\n $entry->addTag($tag);\n }\n }", " $this->service->prepareNewTimesheet($entry, $request);\n $createForm = $this->getCreateForm($entry);\n $createForm->handleRequest($request);", " if ($createForm->isSubmitted() && $createForm->isValid()) {\n try {\n $this->service->saveNewTimesheet($entry);\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute($this->getTimesheetRoute());\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " return $this->render($renderTemplate, [\n 'timesheet' => $entry,\n 'form' => $createForm->createView(),\n ]);\n }\n", " protected function duplicate(Timesheet $timesheet, Request $request, string $renderTemplate): Response", " {\n $copyTimesheet = clone $timesheet;", " $event = new TimesheetMetaDefinitionEvent($copyTimesheet);\n $this->dispatcher->dispatch($event);\n", " $form = $this->getDuplicateForm($copyTimesheet, $timesheet);", " $form->handleRequest($request);", " if ($form->isSubmitted() && $form->isValid()) {\n try {\n $this->dispatcher->dispatch(new TimesheetDuplicatePreEvent($copyTimesheet, $timesheet));\n $this->service->saveNewTimesheet($copyTimesheet);\n $this->dispatcher->dispatch(new TimesheetDuplicatePostEvent($copyTimesheet, $timesheet));\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute($this->getTimesheetRoute());\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " return $this->render($renderTemplate, [\n 'timesheet' => $copyTimesheet,\n 'form' => $form->createView(),\n ]);\n }", " protected function export(Request $request, ServiceExport $serviceExport): Response\n {\n $query = $this->createDefaultQuery();", " $form = $this->getExportForm($query);", " if ($request->isMethod(Request::METHOD_POST)) {\n $this->ignorePersistedSearch($request);\n }", " if ($this->handleSearch($form, $request)) {\n return $this->redirectToRoute($this->getExportRoute());\n }", " $this->prepareQuery($query);", " // make sure that we use the \"expected time range\"\n if (null !== $query->getBegin()) {\n $query->getBegin()->setTime(0, 0, 0);\n }\n if (null !== $query->getEnd()) {\n $query->getEnd()->setTime(23, 59, 59);\n }", " $entries = $this->repository->getTimesheetResult($query);\n $stats = $entries->getStatistic();", " // perform the real export\n if ($request->isMethod(Request::METHOD_POST)) {\n $type = $request->request->get('exporter');\n if (null !== $type) {\n $exporter = $serviceExport->getTimesheetExporterById($type);", " if (null === $exporter) {\n $form->addError(new FormError('Invalid timesheet exporter given'));\n } else {\n return $exporter->render($entries->getResults(true), $query);\n }\n }\n }", " return $this->render('timesheet/layout-export.html.twig', [\n 'form' => $form->createView(),\n 'route_back' => $this->getTimesheetRoute(),\n 'exporter' => $serviceExport->getTimesheetExporter(),\n 'stats' => $stats,\n ]);\n }", " protected function multiUpdate(Request $request, string $renderTemplate)\n {\n $dto = new TimesheetMultiUpdateDTO();", " // initial request from the listing posts a different form\n $form = $this->getMultiUpdateActionForm();\n $form->handleRequest($request);\n if ($form->isSubmitted() && $form->isValid()) {\n $dto->setEntities($form->getData()->getEntities());\n }", " // using a new timesheet to make sure we ONLY use meta-fields which are registered via events\n $fake = new Timesheet();\n $event = new TimesheetMetaDefinitionEvent($fake);\n $this->dispatcher->dispatch($event);", " foreach ($fake->getMetaFields() as $field) {\n $dto->setMetaField(clone $field);\n }", " $form = $this->getMultiUpdateForm($dto);\n $form->handleRequest($request);", " // remove all, which are not allowed to be edited\n $timesheets = [];\n $disallowed = 0;\n /** @var Timesheet $timesheet */\n foreach ($dto->getEntities() as $timesheet) {\n if (!$this->isGranted('edit', $timesheet)) {\n $disallowed++;\n continue;\n }\n $timesheets[] = $timesheet;\n }", " if ($disallowed > 0) {\n $this->flashWarning(sprintf('You are missing the permission to edit %s timesheets', $disallowed));\n }", " $dto->setEntities($timesheets);", " if (\\count($dto->getEntities()) === 0) {\n return $this->redirectToRoute($this->getTimesheetRoute());\n }", " if ($form->isSubmitted() && $form->isValid()) {\n /** @var Timesheet $timesheet */\n $execute = false;\n foreach ($dto->getEntities() as $timesheet) {\n if ($dto->isReplaceTags()) {\n foreach ($timesheet->getTags() as $tag) {\n $timesheet->removeTag($tag);\n }\n $execute = true;\n }\n foreach ($dto->getTags() as $tag) {\n $timesheet->addTag($tag);\n $execute = true;\n }\n if (null !== $dto->getActivity()) {\n $timesheet->setActivity($dto->getActivity());\n $execute = true;\n }\n if (null !== $dto->getProject()) {\n $timesheet->setProject($dto->getProject());\n $execute = true;\n }\n if (null !== $dto->getUser()) {\n $timesheet->setUser($dto->getUser());\n $execute = true;\n }\n if (null !== $dto->isExported()) {\n $timesheet->setExported($dto->isExported());\n $execute = true;\n }\n if (null !== $dto->isBillable()) {\n $timesheet->setBillable($dto->isBillable());\n $execute = true;\n }", " if ($dto->isRecalculateRates()) {\n $timesheet->setFixedRate(null);\n $timesheet->setHourlyRate(null);\n $timesheet->setInternalRate(null);\n $execute = true;\n } elseif (null !== $dto->getFixedRate()) {\n $timesheet->setFixedRate($dto->getFixedRate());\n $timesheet->setHourlyRate(null);\n $timesheet->setInternalRate(null);\n $execute = true;\n } elseif (null !== $dto->getHourlyRate()) {\n $timesheet->setFixedRate(null);\n $timesheet->setInternalRate(null);\n $timesheet->setHourlyRate($dto->getHourlyRate());\n $execute = true;\n }", " foreach ($dto->getUpdateMeta() as $metaName) {\n if (null !== ($metaField = $dto->getMetaField($metaName))) {\n if (null !== ($timesheetMeta = $timesheet->getMetaField($metaName))) {\n $timesheetMeta->setValue($metaField->getValue());\n } else {\n $timesheet->setMetaField(clone $metaField);\n }\n $execute = true;\n }\n }\n }", " if ($execute) {\n try {\n $this->service->updateMultipleTimesheets($dto->getEntities());\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute($this->getTimesheetRoute());\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }\n }", " return $this->render($renderTemplate, [\n 'form' => $form->createView(),\n 'dto' => $dto,\n ]);\n }", " protected function multiDelete(Request $request)\n {\n $form = $this->getMultiUpdateActionForm();\n $form->handleRequest($request);", " if ($form->isSubmitted() && $form->isValid()) {\n $dto = $form->getData();\n $timesheets = [];\n /** @var Timesheet $timesheet */\n foreach ($dto->getEntities() as $timesheet) {\n if (!$this->isGranted('delete', $timesheet)) {\n continue;\n }\n $timesheets[] = $timesheet;\n }\n $dto->setEntities($timesheets);", " try {\n $this->service->deleteMultipleTimesheets($dto->getEntities());\n $this->flashSuccess('action.delete.success');\n } catch (\\Exception $ex) {\n $this->flashDeleteException($ex);\n }\n }", " return $this->redirectToRoute($this->getTimesheetRoute());\n }", " protected function prepareQuery(TimesheetQuery $query)\n {\n $query->setUser($this->getUser());\n }", " protected function getMultiUpdateForm(TimesheetMultiUpdateDTO $multiUpdate): FormInterface\n {\n return $this->createForm(TimesheetMultiUpdate::class, $multiUpdate, [\n 'action' => $this->generateUrl($this->getMultiUpdateRoute(), []),\n 'method' => 'POST',\n 'include_exported' => $this->isGranted($this->getPermissionEditExport()),\n 'include_rate' => $this->isGranted($this->getPermissionEditRate()),\n 'include_user' => $this->includeUserInForms('multi'),\n ]);\n }", " protected function getMultiUpdateActionForm(): FormInterface\n {\n $dto = new MultiUpdateTableDTO();", " $dto->addUpdate($this->generateUrl($this->getMultiUpdateRoute()));\n $dto->addDelete($this->generateUrl($this->getMultiDeleteRoute()));", " return $this->createForm(MultiUpdateTable::class, $dto, [\n 'action' => $this->generateUrl($this->getTimesheetRoute()),\n 'repository' => $this->repository,\n 'method' => 'POST',\n ]);\n }", " protected function generateCreateForm(Timesheet $entry, string $formClass, string $action): FormInterface\n {\n $mode = $this->getTrackingMode();", " return $this->createForm($formClass, $entry, [\n 'action' => $action,\n 'include_rate' => $this->isGranted('edit_rate', $entry),\n 'include_exported' => $this->isGranted('edit_export', $entry),\n 'include_user' => $this->includeUserInForms('create'),\n 'allow_begin_datetime' => $mode->canEditBegin(),\n 'allow_end_datetime' => $mode->canEditEnd(),\n 'allow_duration' => $mode->canEditDuration(),\n 'duration_minutes' => $this->configuration->getTimesheetIncrementDuration(),\n 'begin_minutes' => $this->configuration->getTimesheetIncrementBegin(),\n 'end_minutes' => $this->configuration->getTimesheetIncrementEnd(),\n 'timezone' => $this->getDateTimeFactory()->getTimezone(),\n 'customer' => true,\n ]);\n }", " /**\n * @param Timesheet $entry\n * @param int $page\n * @return FormInterface\n */\n protected function getEditForm(Timesheet $entry, $page)\n {\n $mode = $this->getTrackingMode();", " return $this->createForm($this->getEditFormClassName(), $entry, [\n 'action' => $this->generateUrl($this->getEditRoute(), [\n 'id' => $entry->getId(),\n 'page' => $page,\n ]),\n 'include_rate' => $this->isGranted('edit_rate', $entry),\n 'include_exported' => $this->isGranted('edit_export', $entry),\n 'include_user' => $this->includeUserInForms('edit'),\n 'allow_begin_datetime' => $mode->canEditBegin(),\n 'allow_end_datetime' => $mode->canEditEnd(),\n 'allow_duration' => $mode->canEditDuration(),\n 'duration_minutes' => $this->configuration->getTimesheetIncrementDuration(),\n 'begin_minutes' => $this->configuration->getTimesheetIncrementBegin(),\n 'end_minutes' => $this->configuration->getTimesheetIncrementEnd(),\n 'timezone' => $this->getDateTimeFactory()->getTimezone(),\n 'customer' => true,\n ]);\n }", " protected function getToolbarForm(TimesheetQuery $query): FormInterface\n {\n return $this->createForm(TimesheetToolbarForm::class, $query, [\n 'action' => $this->generateUrl($this->getTimesheetRoute(), [\n 'page' => $query->getPage(),\n ]),\n 'timezone' => $this->getDateTimeFactory()->getTimezone()->getName(),\n 'method' => 'GET',\n 'include_user' => $this->includeUserInForms('toolbar'),\n ]);\n }", " protected function getExportForm(TimesheetQuery $query): FormInterface\n {\n return $this->createForm(TimesheetExportToolbarForm::class, $query, [\n 'action' => $this->generateUrl($this->getExportRoute()),\n 'timezone' => $this->getDateTimeFactory()->getTimezone()->getName(),\n 'method' => Request::METHOD_POST,\n 'include_user' => $this->includeUserInForms('toolbar'),\n ]);\n }", " protected function getPermissionEditExport(): string\n {\n return 'edit_export_own_timesheet';\n }", " protected function getPermissionEditRate(): string\n {\n return 'edit_rate_own_timesheet';\n }", " protected function getEditFormClassName(): string\n {\n return TimesheetEditForm::class;\n }", " protected function includeSummary(): bool\n {\n return (bool) $this->getUser()->getPreferenceValue('timesheet.daily_stats', false);\n }", " protected function includeUserInForms(string $formName): bool\n {\n return false;\n }", " protected function getTimesheetRoute(): string\n {\n return 'timesheet';\n }", " protected function getEditRoute(): string\n {\n return 'timesheet_edit';\n }", " protected function getMultiUpdateRoute(): string\n {\n return 'timesheet_multi_update';\n }", " protected function getMultiDeleteRoute(): string\n {\n return 'timesheet_multi_delete';\n }", " protected function getExportRoute(): string\n {\n return 'timesheet_export';\n }", " protected function canSeeStartEndTime(): bool\n {\n return $this->getTrackingMode()->canSeeBeginAndEndTimes();\n }", " protected function getQueryNamePrefix(): string\n {\n return 'MyTimes';\n }", " protected function createDefaultQuery(string $suffix = 'Listing'): TimesheetQuery\n {\n $query = new TimesheetQuery();\n $query->setName($this->getQueryNamePrefix() . $suffix);", " return $query;\n }\n", " abstract protected function getDuplicateForm(Timesheet $entry, Timesheet $original): FormInterface;", "\n abstract protected function getCreateForm(Timesheet $entry): FormInterface;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace App\\Controller;", "use App\\Configuration\\SystemConfiguration;\nuse App\\Entity\\MetaTableTypeInterface;\nuse App\\Entity\\Tag;\nuse App\\Entity\\Timesheet;\nuse App\\Event\\TimesheetDuplicatePostEvent;\nuse App\\Event\\TimesheetDuplicatePreEvent;\nuse App\\Event\\TimesheetMetaDefinitionEvent;\nuse App\\Event\\TimesheetMetaDisplayEvent;\nuse App\\Export\\ServiceExport;\nuse App\\Form\\MultiUpdate\\MultiUpdateTable;\nuse App\\Form\\MultiUpdate\\MultiUpdateTableDTO;\nuse App\\Form\\MultiUpdate\\TimesheetMultiUpdate;\nuse App\\Form\\MultiUpdate\\TimesheetMultiUpdateDTO;\nuse App\\Form\\TimesheetEditForm;\nuse App\\Form\\Toolbar\\TimesheetExportToolbarForm;\nuse App\\Form\\Toolbar\\TimesheetToolbarForm;\nuse App\\Repository\\ActivityRepository;\nuse App\\Repository\\ProjectRepository;\nuse App\\Repository\\Query\\TimesheetQuery;\nuse App\\Repository\\TagRepository;\nuse App\\Repository\\TimesheetRepository;\nuse App\\Timesheet\\TimesheetService;\nuse App\\Timesheet\\TrackingMode\\TrackingModeInterface;\nuse Doctrine\\Common\\Collections\\ArrayCollection;\nuse Symfony\\Component\\EventDispatcher\\EventDispatcherInterface;\nuse Symfony\\Component\\Form\\FormError;\nuse Symfony\\Component\\Form\\FormInterface;\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\HttpFoundation\\Response;", "abstract class TimesheetAbstractController extends AbstractController\n{\n /**\n * @var TimesheetRepository\n */\n protected $repository;\n /**\n * @var EventDispatcherInterface\n */\n protected $dispatcher;\n /**\n * @var TimesheetService\n */\n protected $service;\n /**\n * @var SystemConfiguration\n */\n protected $configuration;", " public function __construct(\n TimesheetRepository $repository,\n EventDispatcherInterface $dispatcher,\n TimesheetService $timesheetService,\n SystemConfiguration $configuration\n ) {\n $this->repository = $repository;\n $this->dispatcher = $dispatcher;\n $this->service = $timesheetService;\n $this->configuration = $configuration;\n }", " protected function getTrackingMode(): TrackingModeInterface\n {\n return $this->service->getActiveTrackingMode();\n }", " protected function index(TimesheetQuery $query, Request $request, string $route, string $renderTemplate, string $location): Response\n {\n $form = $this->getToolbarForm($query);\n if ($this->handleSearch($form, $request)) {\n return $this->redirectToRoute($route);\n }", " $tags = $query->getTags(true);\n if (!empty($tags)) {\n /** @var TagRepository $tagRepo */\n $tagRepo = $this->getDoctrine()->getRepository(Tag::class);\n $query->setTags(\n new ArrayCollection(\n $tagRepo->findIdsByTagNameList(implode(',', $tags))\n )\n );\n }", " $this->prepareQuery($query);", " $pager = $this->repository->getPagerfantaForQuery($query);", " return $this->render($renderTemplate, [\n 'entries' => $pager,\n 'page' => $query->getPage(),\n 'query' => $query,\n 'toolbarForm' => $form->createView(),\n 'multiUpdateForm' => $this->getMultiUpdateActionForm()->createView(),\n 'showSummary' => $this->includeSummary(),\n 'showStartEndTime' => $this->canSeeStartEndTime(),\n 'metaColumns' => $this->findMetaColumns($query, $location),\n ]);\n }", " /**\n * @param TimesheetQuery $query\n * @param string $location\n * @return MetaTableTypeInterface[]\n */\n protected function findMetaColumns(TimesheetQuery $query, string $location): array\n {\n $event = new TimesheetMetaDisplayEvent($query, $location);\n $this->dispatcher->dispatch($event);", " return $event->getFields();\n }", " protected function edit(Timesheet $entry, Request $request, string $renderTemplate): Response\n {\n $event = new TimesheetMetaDefinitionEvent($entry);\n $this->dispatcher->dispatch($event);", " $editForm = $this->getEditForm($entry, $request->get('page'));\n $editForm->handleRequest($request);", " if ($editForm->isSubmitted() && $editForm->isValid()) {\n try {\n $this->service->updateTimesheet($entry);\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute($this->getTimesheetRoute(), ['page' => $request->get('page', 1)]);\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " return $this->render($renderTemplate, [\n 'timesheet' => $entry,\n 'form' => $editForm->createView(),\n ]);\n }", " protected function getTags(TagRepository $tagRepository, $tagNames)\n {\n $tags = [];\n if (!\\is_array($tagNames)) {\n $tagNames = explode(',', $tagNames);\n }\n foreach ($tagNames as $tagName) {\n $tag = $tagRepository->findTagByName($tagName);\n if (!$tag) {\n $tag = new Tag();\n $tag->setName($tagName);\n }\n $tags[] = $tag;\n }", " return $tags;\n }", " protected function create(Request $request, string $renderTemplate, ProjectRepository $projectRepository, ActivityRepository $activityRepository, TagRepository $tagRepository): Response\n {\n $entry = $this->service->createNewTimesheet($this->getUser());", " if ($request->query->get('project')) {\n $project = $projectRepository->find($request->query->get('project'));\n $entry->setProject($project);\n }", " if ($request->query->get('activity')) {\n $activity = $activityRepository->find($request->query->get('activity'));\n $entry->setActivity($activity);\n }", " if ($request->query->get('description')) {\n $description = $request->query->get('description');\n $entry->setDescription($description);\n }", " if ($request->query->get('tags')) {\n foreach ($this->getTags($tagRepository, $request->query->get('tags')) as $tag) {\n $entry->addTag($tag);\n }\n }", " $this->service->prepareNewTimesheet($entry, $request);\n $createForm = $this->getCreateForm($entry);\n $createForm->handleRequest($request);", " if ($createForm->isSubmitted() && $createForm->isValid()) {\n try {\n $this->service->saveNewTimesheet($entry);\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute($this->getTimesheetRoute());\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " return $this->render($renderTemplate, [\n 'timesheet' => $entry,\n 'form' => $createForm->createView(),\n ]);\n }\n", " protected function duplicate(Timesheet $timesheet, Request $request, string $renderTemplate, string $token): Response", " {\n $copyTimesheet = clone $timesheet;", " $event = new TimesheetMetaDefinitionEvent($copyTimesheet);\n $this->dispatcher->dispatch($event);\n", " $form = $this->getDuplicateForm($copyTimesheet, $timesheet, $token);", " $form->handleRequest($request);", " if ($form->isSubmitted() && $form->isValid()) {\n try {\n $this->dispatcher->dispatch(new TimesheetDuplicatePreEvent($copyTimesheet, $timesheet));\n $this->service->saveNewTimesheet($copyTimesheet);\n $this->dispatcher->dispatch(new TimesheetDuplicatePostEvent($copyTimesheet, $timesheet));\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute($this->getTimesheetRoute());\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " return $this->render($renderTemplate, [\n 'timesheet' => $copyTimesheet,\n 'form' => $form->createView(),\n ]);\n }", " protected function export(Request $request, ServiceExport $serviceExport): Response\n {\n $query = $this->createDefaultQuery();", " $form = $this->getExportForm($query);", " if ($request->isMethod(Request::METHOD_POST)) {\n $this->ignorePersistedSearch($request);\n }", " if ($this->handleSearch($form, $request)) {\n return $this->redirectToRoute($this->getExportRoute());\n }", " $this->prepareQuery($query);", " // make sure that we use the \"expected time range\"\n if (null !== $query->getBegin()) {\n $query->getBegin()->setTime(0, 0, 0);\n }\n if (null !== $query->getEnd()) {\n $query->getEnd()->setTime(23, 59, 59);\n }", " $entries = $this->repository->getTimesheetResult($query);\n $stats = $entries->getStatistic();", " // perform the real export\n if ($request->isMethod(Request::METHOD_POST)) {\n $type = $request->request->get('exporter');\n if (null !== $type) {\n $exporter = $serviceExport->getTimesheetExporterById($type);", " if (null === $exporter) {\n $form->addError(new FormError('Invalid timesheet exporter given'));\n } else {\n return $exporter->render($entries->getResults(true), $query);\n }\n }\n }", " return $this->render('timesheet/layout-export.html.twig', [\n 'form' => $form->createView(),\n 'route_back' => $this->getTimesheetRoute(),\n 'exporter' => $serviceExport->getTimesheetExporter(),\n 'stats' => $stats,\n ]);\n }", " protected function multiUpdate(Request $request, string $renderTemplate)\n {\n $dto = new TimesheetMultiUpdateDTO();", " // initial request from the listing posts a different form\n $form = $this->getMultiUpdateActionForm();\n $form->handleRequest($request);\n if ($form->isSubmitted() && $form->isValid()) {\n $dto->setEntities($form->getData()->getEntities());\n }", " // using a new timesheet to make sure we ONLY use meta-fields which are registered via events\n $fake = new Timesheet();\n $event = new TimesheetMetaDefinitionEvent($fake);\n $this->dispatcher->dispatch($event);", " foreach ($fake->getMetaFields() as $field) {\n $dto->setMetaField(clone $field);\n }", " $form = $this->getMultiUpdateForm($dto);\n $form->handleRequest($request);", " // remove all, which are not allowed to be edited\n $timesheets = [];\n $disallowed = 0;\n /** @var Timesheet $timesheet */\n foreach ($dto->getEntities() as $timesheet) {\n if (!$this->isGranted('edit', $timesheet)) {\n $disallowed++;\n continue;\n }\n $timesheets[] = $timesheet;\n }", " if ($disallowed > 0) {\n $this->flashWarning(sprintf('You are missing the permission to edit %s timesheets', $disallowed));\n }", " $dto->setEntities($timesheets);", " if (\\count($dto->getEntities()) === 0) {\n return $this->redirectToRoute($this->getTimesheetRoute());\n }", " if ($form->isSubmitted() && $form->isValid()) {\n /** @var Timesheet $timesheet */\n $execute = false;\n foreach ($dto->getEntities() as $timesheet) {\n if ($dto->isReplaceTags()) {\n foreach ($timesheet->getTags() as $tag) {\n $timesheet->removeTag($tag);\n }\n $execute = true;\n }\n foreach ($dto->getTags() as $tag) {\n $timesheet->addTag($tag);\n $execute = true;\n }\n if (null !== $dto->getActivity()) {\n $timesheet->setActivity($dto->getActivity());\n $execute = true;\n }\n if (null !== $dto->getProject()) {\n $timesheet->setProject($dto->getProject());\n $execute = true;\n }\n if (null !== $dto->getUser()) {\n $timesheet->setUser($dto->getUser());\n $execute = true;\n }\n if (null !== $dto->isExported()) {\n $timesheet->setExported($dto->isExported());\n $execute = true;\n }\n if (null !== $dto->isBillable()) {\n $timesheet->setBillable($dto->isBillable());\n $execute = true;\n }", " if ($dto->isRecalculateRates()) {\n $timesheet->setFixedRate(null);\n $timesheet->setHourlyRate(null);\n $timesheet->setInternalRate(null);\n $execute = true;\n } elseif (null !== $dto->getFixedRate()) {\n $timesheet->setFixedRate($dto->getFixedRate());\n $timesheet->setHourlyRate(null);\n $timesheet->setInternalRate(null);\n $execute = true;\n } elseif (null !== $dto->getHourlyRate()) {\n $timesheet->setFixedRate(null);\n $timesheet->setInternalRate(null);\n $timesheet->setHourlyRate($dto->getHourlyRate());\n $execute = true;\n }", " foreach ($dto->getUpdateMeta() as $metaName) {\n if (null !== ($metaField = $dto->getMetaField($metaName))) {\n if (null !== ($timesheetMeta = $timesheet->getMetaField($metaName))) {\n $timesheetMeta->setValue($metaField->getValue());\n } else {\n $timesheet->setMetaField(clone $metaField);\n }\n $execute = true;\n }\n }\n }", " if ($execute) {\n try {\n $this->service->updateMultipleTimesheets($dto->getEntities());\n $this->flashSuccess('action.update.success');", " return $this->redirectToRoute($this->getTimesheetRoute());\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }\n }", " return $this->render($renderTemplate, [\n 'form' => $form->createView(),\n 'dto' => $dto,\n ]);\n }", " protected function multiDelete(Request $request)\n {\n $form = $this->getMultiUpdateActionForm();\n $form->handleRequest($request);", " if ($form->isSubmitted() && $form->isValid()) {\n $dto = $form->getData();\n $timesheets = [];\n /** @var Timesheet $timesheet */\n foreach ($dto->getEntities() as $timesheet) {\n if (!$this->isGranted('delete', $timesheet)) {\n continue;\n }\n $timesheets[] = $timesheet;\n }\n $dto->setEntities($timesheets);", " try {\n $this->service->deleteMultipleTimesheets($dto->getEntities());\n $this->flashSuccess('action.delete.success');\n } catch (\\Exception $ex) {\n $this->flashDeleteException($ex);\n }\n }", " return $this->redirectToRoute($this->getTimesheetRoute());\n }", " protected function prepareQuery(TimesheetQuery $query)\n {\n $query->setUser($this->getUser());\n }", " protected function getMultiUpdateForm(TimesheetMultiUpdateDTO $multiUpdate): FormInterface\n {\n return $this->createForm(TimesheetMultiUpdate::class, $multiUpdate, [\n 'action' => $this->generateUrl($this->getMultiUpdateRoute(), []),\n 'method' => 'POST',\n 'include_exported' => $this->isGranted($this->getPermissionEditExport()),\n 'include_rate' => $this->isGranted($this->getPermissionEditRate()),\n 'include_user' => $this->includeUserInForms('multi'),\n ]);\n }", " protected function getMultiUpdateActionForm(): FormInterface\n {\n $dto = new MultiUpdateTableDTO();", " $dto->addUpdate($this->generateUrl($this->getMultiUpdateRoute()));\n $dto->addDelete($this->generateUrl($this->getMultiDeleteRoute()));", " return $this->createForm(MultiUpdateTable::class, $dto, [\n 'action' => $this->generateUrl($this->getTimesheetRoute()),\n 'repository' => $this->repository,\n 'method' => 'POST',\n ]);\n }", " protected function generateCreateForm(Timesheet $entry, string $formClass, string $action): FormInterface\n {\n $mode = $this->getTrackingMode();", " return $this->createForm($formClass, $entry, [\n 'action' => $action,\n 'include_rate' => $this->isGranted('edit_rate', $entry),\n 'include_exported' => $this->isGranted('edit_export', $entry),\n 'include_user' => $this->includeUserInForms('create'),\n 'allow_begin_datetime' => $mode->canEditBegin(),\n 'allow_end_datetime' => $mode->canEditEnd(),\n 'allow_duration' => $mode->canEditDuration(),\n 'duration_minutes' => $this->configuration->getTimesheetIncrementDuration(),\n 'begin_minutes' => $this->configuration->getTimesheetIncrementBegin(),\n 'end_minutes' => $this->configuration->getTimesheetIncrementEnd(),\n 'timezone' => $this->getDateTimeFactory()->getTimezone(),\n 'customer' => true,\n ]);\n }", " /**\n * @param Timesheet $entry\n * @param int $page\n * @return FormInterface\n */\n protected function getEditForm(Timesheet $entry, $page)\n {\n $mode = $this->getTrackingMode();", " return $this->createForm($this->getEditFormClassName(), $entry, [\n 'action' => $this->generateUrl($this->getEditRoute(), [\n 'id' => $entry->getId(),\n 'page' => $page,\n ]),\n 'include_rate' => $this->isGranted('edit_rate', $entry),\n 'include_exported' => $this->isGranted('edit_export', $entry),\n 'include_user' => $this->includeUserInForms('edit'),\n 'allow_begin_datetime' => $mode->canEditBegin(),\n 'allow_end_datetime' => $mode->canEditEnd(),\n 'allow_duration' => $mode->canEditDuration(),\n 'duration_minutes' => $this->configuration->getTimesheetIncrementDuration(),\n 'begin_minutes' => $this->configuration->getTimesheetIncrementBegin(),\n 'end_minutes' => $this->configuration->getTimesheetIncrementEnd(),\n 'timezone' => $this->getDateTimeFactory()->getTimezone(),\n 'customer' => true,\n ]);\n }", " protected function getToolbarForm(TimesheetQuery $query): FormInterface\n {\n return $this->createForm(TimesheetToolbarForm::class, $query, [\n 'action' => $this->generateUrl($this->getTimesheetRoute(), [\n 'page' => $query->getPage(),\n ]),\n 'timezone' => $this->getDateTimeFactory()->getTimezone()->getName(),\n 'method' => 'GET',\n 'include_user' => $this->includeUserInForms('toolbar'),\n ]);\n }", " protected function getExportForm(TimesheetQuery $query): FormInterface\n {\n return $this->createForm(TimesheetExportToolbarForm::class, $query, [\n 'action' => $this->generateUrl($this->getExportRoute()),\n 'timezone' => $this->getDateTimeFactory()->getTimezone()->getName(),\n 'method' => Request::METHOD_POST,\n 'include_user' => $this->includeUserInForms('toolbar'),\n ]);\n }", " protected function getPermissionEditExport(): string\n {\n return 'edit_export_own_timesheet';\n }", " protected function getPermissionEditRate(): string\n {\n return 'edit_rate_own_timesheet';\n }", " protected function getEditFormClassName(): string\n {\n return TimesheetEditForm::class;\n }", " protected function includeSummary(): bool\n {\n return (bool) $this->getUser()->getPreferenceValue('timesheet.daily_stats', false);\n }", " protected function includeUserInForms(string $formName): bool\n {\n return false;\n }", " protected function getTimesheetRoute(): string\n {\n return 'timesheet';\n }", " protected function getEditRoute(): string\n {\n return 'timesheet_edit';\n }", " protected function getMultiUpdateRoute(): string\n {\n return 'timesheet_multi_update';\n }", " protected function getMultiDeleteRoute(): string\n {\n return 'timesheet_multi_delete';\n }", " protected function getExportRoute(): string\n {\n return 'timesheet_export';\n }", " protected function canSeeStartEndTime(): bool\n {\n return $this->getTrackingMode()->canSeeBeginAndEndTimes();\n }", " protected function getQueryNamePrefix(): string\n {\n return 'MyTimes';\n }", " protected function createDefaultQuery(string $suffix = 'Listing'): TimesheetQuery\n {\n $query = new TimesheetQuery();\n $query->setName($this->getQueryNamePrefix() . $suffix);", " return $query;\n }\n", " abstract protected function getDuplicateForm(Timesheet $entry, Timesheet $original, string $token): FormInterface;", "\n abstract protected function getCreateForm(Timesheet $entry): FormInterface;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace App\\Controller;", "use App\\Entity\\Timesheet;\nuse App\\Event\\TimesheetMetaDisplayEvent;\nuse App\\Export\\ServiceExport;\nuse App\\Form\\TimesheetEditForm;\nuse App\\Repository\\ActivityRepository;\nuse App\\Repository\\ProjectRepository;\nuse App\\Repository\\TagRepository;\nuse Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Security;\nuse Symfony\\Component\\Form\\FormInterface;\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\HttpFoundation\\Response;\nuse Symfony\\Component\\Routing\\Annotation\\Route;", "", "\n/**\n * @Route(path=\"/timesheet\")\n * @Security(\"is_granted('view_own_timesheet')\")\n */\nclass TimesheetController extends TimesheetAbstractController\n{\n /**\n * @Route(path=\"/\", defaults={\"page\": 1}, name=\"timesheet\", methods={\"GET\"})\n * @Route(path=\"/page/{page}\", requirements={\"page\": \"[1-9]\\d*\"}, name=\"timesheet_paginated\", methods={\"GET\"})\n * @Security(\"is_granted('view_own_timesheet')\")\n */\n public function indexAction(int $page, Request $request): Response\n {\n $query = $this->createDefaultQuery();\n $query->setPage($page);", " return $this->index($query, $request, 'timesheet', 'timesheet/index.html.twig', TimesheetMetaDisplayEvent::TIMESHEET);\n }", " /**\n * @Route(path=\"/export/\", name=\"timesheet_export\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('export_own_timesheet')\")\n */\n public function exportAction(Request $request, ServiceExport $serviceExport): Response\n {\n return $this->export($request, $serviceExport);\n }", " /**\n * @Route(path=\"/{id}/edit\", name=\"timesheet_edit\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('edit', entry)\")\n */\n public function editAction(Timesheet $entry, Request $request): Response\n {\n return $this->edit($entry, $request, 'timesheet/edit.html.twig');\n }", " /**", " * @Route(path=\"/{id}/duplicate\", name=\"timesheet_duplicate\", methods={\"GET\", \"POST\"})", " * @Security(\"is_granted('duplicate', entry)\")\n */", " public function duplicateAction(Timesheet $entry, Request $request): Response", " {", " return $this->duplicate($entry, $request, 'timesheet/edit.html.twig');", " }", " /**\n * @Route(path=\"/multi-update\", name=\"timesheet_multi_update\", methods={\"POST\"})\n * @Security(\"is_granted('edit_own_timesheet')\")\n */\n public function multiUpdateAction(Request $request): Response\n {\n return $this->multiUpdate($request, 'timesheet/multi-update.html.twig');\n }", " /**\n * @Route(path=\"/multi-delete\", name=\"timesheet_multi_delete\", methods={\"POST\"})\n * @Security(\"is_granted('delete_own_timesheet')\")\n */\n public function multiDeleteAction(Request $request): Response\n {\n return $this->multiDelete($request);\n }", " /**\n * @Route(path=\"/create\", name=\"timesheet_create\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('create_own_timesheet')\")\n */\n public function createAction(Request $request, ProjectRepository $projectRepository, ActivityRepository $activityRepository, TagRepository $tagRepository): Response\n {\n return $this->create($request, 'timesheet/edit.html.twig', $projectRepository, $activityRepository, $tagRepository);\n }", " protected function getCreateForm(Timesheet $entry): FormInterface\n {\n return $this->generateCreateForm($entry, TimesheetEditForm::class, $this->generateUrl('timesheet_create'));\n }\n", " protected function getDuplicateForm(Timesheet $entry, Timesheet $original): FormInterface", " {", " return $this->generateCreateForm($entry, TimesheetEditForm::class, $this->generateUrl('timesheet_duplicate', ['id' => $original->getId()]));", " }\n}" ]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace App\\Controller;", "use App\\Entity\\Timesheet;\nuse App\\Event\\TimesheetMetaDisplayEvent;\nuse App\\Export\\ServiceExport;\nuse App\\Form\\TimesheetEditForm;\nuse App\\Repository\\ActivityRepository;\nuse App\\Repository\\ProjectRepository;\nuse App\\Repository\\TagRepository;\nuse Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Security;\nuse Symfony\\Component\\Form\\FormInterface;\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\HttpFoundation\\Response;\nuse Symfony\\Component\\Routing\\Annotation\\Route;", "use Symfony\\Component\\Security\\Csrf\\CsrfToken;\nuse Symfony\\Component\\Security\\Csrf\\CsrfTokenManagerInterface;", "\n/**\n * @Route(path=\"/timesheet\")\n * @Security(\"is_granted('view_own_timesheet')\")\n */\nclass TimesheetController extends TimesheetAbstractController\n{\n /**\n * @Route(path=\"/\", defaults={\"page\": 1}, name=\"timesheet\", methods={\"GET\"})\n * @Route(path=\"/page/{page}\", requirements={\"page\": \"[1-9]\\d*\"}, name=\"timesheet_paginated\", methods={\"GET\"})\n * @Security(\"is_granted('view_own_timesheet')\")\n */\n public function indexAction(int $page, Request $request): Response\n {\n $query = $this->createDefaultQuery();\n $query->setPage($page);", " return $this->index($query, $request, 'timesheet', 'timesheet/index.html.twig', TimesheetMetaDisplayEvent::TIMESHEET);\n }", " /**\n * @Route(path=\"/export/\", name=\"timesheet_export\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('export_own_timesheet')\")\n */\n public function exportAction(Request $request, ServiceExport $serviceExport): Response\n {\n return $this->export($request, $serviceExport);\n }", " /**\n * @Route(path=\"/{id}/edit\", name=\"timesheet_edit\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('edit', entry)\")\n */\n public function editAction(Timesheet $entry, Request $request): Response\n {\n return $this->edit($entry, $request, 'timesheet/edit.html.twig');\n }", " /**", " * @Route(path=\"/{id}/duplicate/{token}\", name=\"timesheet_duplicate\", methods={\"GET\", \"POST\"})", " * @Security(\"is_granted('duplicate', entry)\")\n */", " public function duplicateAction(Timesheet $entry, Request $request, string $token, CsrfTokenManagerInterface $csrfTokenManager): Response", " {", " if (!$csrfTokenManager->isTokenValid(new CsrfToken('timesheet.duplicate', $token))) {\n $this->flashError('action.csrf.error');", " return $this->redirectToRoute('timesheet');\n }", " $csrfTokenManager->refreshToken($token);", " return $this->duplicate($entry, $request, 'timesheet/edit.html.twig', $token);", " }", " /**\n * @Route(path=\"/multi-update\", name=\"timesheet_multi_update\", methods={\"POST\"})\n * @Security(\"is_granted('edit_own_timesheet')\")\n */\n public function multiUpdateAction(Request $request): Response\n {\n return $this->multiUpdate($request, 'timesheet/multi-update.html.twig');\n }", " /**\n * @Route(path=\"/multi-delete\", name=\"timesheet_multi_delete\", methods={\"POST\"})\n * @Security(\"is_granted('delete_own_timesheet')\")\n */\n public function multiDeleteAction(Request $request): Response\n {\n return $this->multiDelete($request);\n }", " /**\n * @Route(path=\"/create\", name=\"timesheet_create\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('create_own_timesheet')\")\n */\n public function createAction(Request $request, ProjectRepository $projectRepository, ActivityRepository $activityRepository, TagRepository $tagRepository): Response\n {\n return $this->create($request, 'timesheet/edit.html.twig', $projectRepository, $activityRepository, $tagRepository);\n }", " protected function getCreateForm(Timesheet $entry): FormInterface\n {\n return $this->generateCreateForm($entry, TimesheetEditForm::class, $this->generateUrl('timesheet_create'));\n }\n", " protected function getDuplicateForm(Timesheet $entry, Timesheet $original, string $token): FormInterface", " {", " return $this->generateCreateForm($entry, TimesheetEditForm::class, $this->generateUrl('timesheet_duplicate', ['id' => $original->getId(), 'token' => $token]));", " }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace App\\Controller;", "use App\\Entity\\Tag;\nuse App\\Entity\\Team;\nuse App\\Entity\\Timesheet;\nuse App\\Entity\\User;\nuse App\\Event\\TimesheetMetaDisplayEvent;\nuse App\\Export\\ServiceExport;\nuse App\\Form\\Model\\MultiUserTimesheet;\nuse App\\Form\\TimesheetAdminEditForm;\nuse App\\Form\\TimesheetMultiUserEditForm;\nuse App\\Repository\\ActivityRepository;\nuse App\\Repository\\ProjectRepository;\nuse App\\Repository\\Query\\TimesheetQuery;\nuse App\\Repository\\TagRepository;\nuse Doctrine\\Common\\Collections\\ArrayCollection;\nuse Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Security;\nuse Symfony\\Component\\Form\\FormInterface;\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\HttpFoundation\\Response;\nuse Symfony\\Component\\Routing\\Annotation\\Route;", "", "\n/**\n * @Route(path=\"/team/timesheet\")\n * @Security(\"is_granted('view_other_timesheet')\")\n */\nclass TimesheetTeamController extends TimesheetAbstractController\n{\n /**\n * @Route(path=\"/\", defaults={\"page\": 1}, name=\"admin_timesheet\", methods={\"GET\"})\n * @Route(path=\"/page/{page}\", requirements={\"page\": \"[1-9]\\d*\"}, name=\"admin_timesheet_paginated\", methods={\"GET\"})\n * @Security(\"is_granted('view_other_timesheet')\")\n *\n * @param int $page\n * @param Request $request\n * @return Response\n */\n public function indexAction(int $page, Request $request): Response\n {\n $query = $this->createDefaultQuery();\n $query->setPage($page);", " return $this->index($query, $request, 'admin_timesheet', 'timesheet-team/index.html.twig', TimesheetMetaDisplayEvent::TEAM_TIMESHEET);\n }", " /**\n * @Route(path=\"/export/\", name=\"admin_timesheet_export\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('export_other_timesheet')\")\n */\n public function exportAction(Request $request, ServiceExport $serviceExport): Response\n {\n return $this->export($request, $serviceExport);\n }", " /**\n * @Route(path=\"/{id}/edit\", name=\"admin_timesheet_edit\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('edit', entry)\")\n */\n public function editAction(Timesheet $entry, Request $request): Response\n {\n return $this->edit($entry, $request, 'timesheet-team/edit.html.twig');\n }", " /**", " * @Route(path=\"/{id}/duplicate\", name=\"admin_timesheet_duplicate\", methods={\"GET\", \"POST\"})", " * @Security(\"is_granted('duplicate', entry)\")\n */", " public function duplicateAction(Timesheet $entry, Request $request): Response\n {\n return $this->duplicate($entry, $request, 'timesheet-team/edit.html.twig');", " }", " /**\n * @Route(path=\"/create\", name=\"admin_timesheet_create\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('create_other_timesheet')\")\n */\n public function createAction(Request $request, ProjectRepository $projectRepository, ActivityRepository $activityRepository, TagRepository $tagRepository): Response\n {\n return $this->create($request, 'timesheet-team/edit.html.twig', $projectRepository, $activityRepository, $tagRepository);\n }", " /**\n * @Route(path=\"/create_mu\", name=\"admin_timesheet_create_multiuser\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('create_other_timesheet')\")\n */\n public function createForMultiUserAction(Request $request): Response\n {\n $entry = new MultiUserTimesheet();\n $entry->setUser($this->getUser());\n $this->service->prepareNewTimesheet($entry, $request);", " $createForm = $this->getMultiUserCreateForm($entry);\n $createForm->handleRequest($request);", " if ($createForm->isSubmitted() && $createForm->isValid()) {\n try {\n /** @var ArrayCollection<User> $users */\n $users = $createForm->get('users')->getData();\n /** @var ArrayCollection<Team> $teams */\n $teams = $createForm->get('teams')->getData();", " $allUsers = $users->toArray();\n /** @var Team $team */\n foreach ($teams as $team) {\n $allUsers = array_merge($allUsers, $team->getUsers());\n }\n $allUsers = array_unique($allUsers);", " /** @var Tag[] $tags */\n $tags = [];\n /** @var Tag $tag */\n foreach ($entry->getTags() as $tag) {\n $tag->removeTimesheet($entry);\n $tags[] = $tag;\n }", " foreach ($allUsers as $user) {\n $newTimesheet = $entry->createCopy();\n $newTimesheet->setUser($user);\n foreach ($tags as $tag) {\n $newTimesheet->addTag($tag);\n }\n $this->service->prepareNewTimesheet($newTimesheet, $request);\n $this->service->saveNewTimesheet($newTimesheet);\n }", " $this->flashSuccess('action.update.success');", " return $this->redirectToRoute($this->getTimesheetRoute());\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " return $this->render('timesheet-team/edit.html.twig', [\n 'timesheet' => $entry,\n 'form' => $createForm->createView(),\n ]);\n }", " protected function getMultiUserCreateForm(MultiUserTimesheet $entry): FormInterface\n {\n $mode = $this->getTrackingMode();", " return $this->createForm(TimesheetMultiUserEditForm::class, $entry, [\n 'action' => $this->generateUrl('admin_timesheet_create_multiuser'),\n 'include_rate' => $this->isGranted('edit_rate', $entry),\n 'include_exported' => $this->isGranted('edit_export', $entry),\n 'include_user' => $this->includeUserInForms('create'),\n 'allow_begin_datetime' => $mode->canEditBegin(),\n 'allow_end_datetime' => $mode->canEditEnd(),\n 'allow_duration' => $mode->canEditDuration(),\n 'duration_minutes' => $this->configuration->getTimesheetIncrementDuration(),\n 'begin_minutes' => $this->configuration->getTimesheetIncrementBegin(),\n 'end_minutes' => $this->configuration->getTimesheetIncrementEnd(),\n 'timezone' => $this->getDateTimeFactory()->getTimezone()->getName(),\n 'customer' => true,\n ]);\n }", " /**\n * @Route(path=\"/multi-update\", name=\"admin_timesheet_multi_update\", methods={\"POST\"})\n * @Security(\"is_granted('edit_other_timesheet')\")\n */\n public function multiUpdateAction(Request $request): Response\n {\n return $this->multiUpdate($request, 'timesheet-team/multi-update.html.twig');\n }", " /**\n * @Route(path=\"/multi-delete\", name=\"admin_timesheet_multi_delete\", methods={\"POST\"})\n * @Security(\"is_granted('delete_other_timesheet')\")\n */\n public function multiDeleteAction(Request $request): Response\n {\n return $this->multiDelete($request);\n }", " protected function prepareQuery(TimesheetQuery $query)\n {\n $query->setCurrentUser($this->getUser());\n }", " protected function getCreateForm(Timesheet $entry): FormInterface\n {\n return $this->generateCreateForm($entry, TimesheetAdminEditForm::class, $this->generateUrl('admin_timesheet_create'));\n }\n", " protected function getDuplicateForm(Timesheet $entry, Timesheet $original): FormInterface\n {\n return $this->generateCreateForm($entry, TimesheetAdminEditForm::class, $this->generateUrl('admin_timesheet_duplicate', ['id' => $original->getId()]));", " }", " protected function getPermissionEditExport(): string\n {\n return 'edit_export_other_timesheet';\n }", " protected function getPermissionEditRate(): string\n {\n return 'edit_rate_other_timesheet';\n }", " protected function getEditFormClassName(): string\n {\n return TimesheetAdminEditForm::class;\n }", " protected function includeUserInForms(string $formName): bool\n {\n if ($formName === 'toolbar') {\n return true;\n }", " return $this->isGranted('edit_other_timesheet');\n }", " protected function getTimesheetRoute(): string\n {\n return 'admin_timesheet';\n }", " protected function getEditRoute(): string\n {\n return 'admin_timesheet_edit';\n }", " protected function getExportRoute(): string\n {\n return 'admin_timesheet_export';\n }", " protected function getMultiUpdateRoute(): string\n {\n return 'admin_timesheet_multi_update';\n }", " protected function getMultiDeleteRoute(): string\n {\n return 'admin_timesheet_multi_delete';\n }", " protected function canSeeStartEndTime(): bool\n {\n return true;\n }", " protected function getQueryNamePrefix(): string\n {\n return 'TeamTimes';\n }\n}" ]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace App\\Controller;", "use App\\Entity\\Tag;\nuse App\\Entity\\Team;\nuse App\\Entity\\Timesheet;\nuse App\\Entity\\User;\nuse App\\Event\\TimesheetMetaDisplayEvent;\nuse App\\Export\\ServiceExport;\nuse App\\Form\\Model\\MultiUserTimesheet;\nuse App\\Form\\TimesheetAdminEditForm;\nuse App\\Form\\TimesheetMultiUserEditForm;\nuse App\\Repository\\ActivityRepository;\nuse App\\Repository\\ProjectRepository;\nuse App\\Repository\\Query\\TimesheetQuery;\nuse App\\Repository\\TagRepository;\nuse Doctrine\\Common\\Collections\\ArrayCollection;\nuse Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Security;\nuse Symfony\\Component\\Form\\FormInterface;\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\HttpFoundation\\Response;\nuse Symfony\\Component\\Routing\\Annotation\\Route;", "use Symfony\\Component\\Security\\Csrf\\CsrfToken;\nuse Symfony\\Component\\Security\\Csrf\\CsrfTokenManagerInterface;", "\n/**\n * @Route(path=\"/team/timesheet\")\n * @Security(\"is_granted('view_other_timesheet')\")\n */\nclass TimesheetTeamController extends TimesheetAbstractController\n{\n /**\n * @Route(path=\"/\", defaults={\"page\": 1}, name=\"admin_timesheet\", methods={\"GET\"})\n * @Route(path=\"/page/{page}\", requirements={\"page\": \"[1-9]\\d*\"}, name=\"admin_timesheet_paginated\", methods={\"GET\"})\n * @Security(\"is_granted('view_other_timesheet')\")\n *\n * @param int $page\n * @param Request $request\n * @return Response\n */\n public function indexAction(int $page, Request $request): Response\n {\n $query = $this->createDefaultQuery();\n $query->setPage($page);", " return $this->index($query, $request, 'admin_timesheet', 'timesheet-team/index.html.twig', TimesheetMetaDisplayEvent::TEAM_TIMESHEET);\n }", " /**\n * @Route(path=\"/export/\", name=\"admin_timesheet_export\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('export_other_timesheet')\")\n */\n public function exportAction(Request $request, ServiceExport $serviceExport): Response\n {\n return $this->export($request, $serviceExport);\n }", " /**\n * @Route(path=\"/{id}/edit\", name=\"admin_timesheet_edit\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('edit', entry)\")\n */\n public function editAction(Timesheet $entry, Request $request): Response\n {\n return $this->edit($entry, $request, 'timesheet-team/edit.html.twig');\n }", " /**", " * @Route(path=\"/{id}/duplicate/{token}\", name=\"admin_timesheet_duplicate\", methods={\"GET\", \"POST\"})", " * @Security(\"is_granted('duplicate', entry)\")\n */", " public function duplicateAction(Timesheet $entry, Request $request, string $token, CsrfTokenManagerInterface $csrfTokenManager): Response\n {\n if (!$csrfTokenManager->isTokenValid(new CsrfToken('admin_timesheet.duplicate', $token))) {\n $this->flashError('action.csrf.error');", " return $this->redirectToRoute('admin_timesheet');\n }", " $csrfTokenManager->refreshToken($token);", " return $this->duplicate($entry, $request, 'timesheet-team/edit.html.twig', $token);", " }", " /**\n * @Route(path=\"/create\", name=\"admin_timesheet_create\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('create_other_timesheet')\")\n */\n public function createAction(Request $request, ProjectRepository $projectRepository, ActivityRepository $activityRepository, TagRepository $tagRepository): Response\n {\n return $this->create($request, 'timesheet-team/edit.html.twig', $projectRepository, $activityRepository, $tagRepository);\n }", " /**\n * @Route(path=\"/create_mu\", name=\"admin_timesheet_create_multiuser\", methods={\"GET\", \"POST\"})\n * @Security(\"is_granted('create_other_timesheet')\")\n */\n public function createForMultiUserAction(Request $request): Response\n {\n $entry = new MultiUserTimesheet();\n $entry->setUser($this->getUser());\n $this->service->prepareNewTimesheet($entry, $request);", " $createForm = $this->getMultiUserCreateForm($entry);\n $createForm->handleRequest($request);", " if ($createForm->isSubmitted() && $createForm->isValid()) {\n try {\n /** @var ArrayCollection<User> $users */\n $users = $createForm->get('users')->getData();\n /** @var ArrayCollection<Team> $teams */\n $teams = $createForm->get('teams')->getData();", " $allUsers = $users->toArray();\n /** @var Team $team */\n foreach ($teams as $team) {\n $allUsers = array_merge($allUsers, $team->getUsers());\n }\n $allUsers = array_unique($allUsers);", " /** @var Tag[] $tags */\n $tags = [];\n /** @var Tag $tag */\n foreach ($entry->getTags() as $tag) {\n $tag->removeTimesheet($entry);\n $tags[] = $tag;\n }", " foreach ($allUsers as $user) {\n $newTimesheet = $entry->createCopy();\n $newTimesheet->setUser($user);\n foreach ($tags as $tag) {\n $newTimesheet->addTag($tag);\n }\n $this->service->prepareNewTimesheet($newTimesheet, $request);\n $this->service->saveNewTimesheet($newTimesheet);\n }", " $this->flashSuccess('action.update.success');", " return $this->redirectToRoute($this->getTimesheetRoute());\n } catch (\\Exception $ex) {\n $this->flashUpdateException($ex);\n }\n }", " return $this->render('timesheet-team/edit.html.twig', [\n 'timesheet' => $entry,\n 'form' => $createForm->createView(),\n ]);\n }", " protected function getMultiUserCreateForm(MultiUserTimesheet $entry): FormInterface\n {\n $mode = $this->getTrackingMode();", " return $this->createForm(TimesheetMultiUserEditForm::class, $entry, [\n 'action' => $this->generateUrl('admin_timesheet_create_multiuser'),\n 'include_rate' => $this->isGranted('edit_rate', $entry),\n 'include_exported' => $this->isGranted('edit_export', $entry),\n 'include_user' => $this->includeUserInForms('create'),\n 'allow_begin_datetime' => $mode->canEditBegin(),\n 'allow_end_datetime' => $mode->canEditEnd(),\n 'allow_duration' => $mode->canEditDuration(),\n 'duration_minutes' => $this->configuration->getTimesheetIncrementDuration(),\n 'begin_minutes' => $this->configuration->getTimesheetIncrementBegin(),\n 'end_minutes' => $this->configuration->getTimesheetIncrementEnd(),\n 'timezone' => $this->getDateTimeFactory()->getTimezone()->getName(),\n 'customer' => true,\n ]);\n }", " /**\n * @Route(path=\"/multi-update\", name=\"admin_timesheet_multi_update\", methods={\"POST\"})\n * @Security(\"is_granted('edit_other_timesheet')\")\n */\n public function multiUpdateAction(Request $request): Response\n {\n return $this->multiUpdate($request, 'timesheet-team/multi-update.html.twig');\n }", " /**\n * @Route(path=\"/multi-delete\", name=\"admin_timesheet_multi_delete\", methods={\"POST\"})\n * @Security(\"is_granted('delete_other_timesheet')\")\n */\n public function multiDeleteAction(Request $request): Response\n {\n return $this->multiDelete($request);\n }", " protected function prepareQuery(TimesheetQuery $query)\n {\n $query->setCurrentUser($this->getUser());\n }", " protected function getCreateForm(Timesheet $entry): FormInterface\n {\n return $this->generateCreateForm($entry, TimesheetAdminEditForm::class, $this->generateUrl('admin_timesheet_create'));\n }\n", " protected function getDuplicateForm(Timesheet $entry, Timesheet $original, string $token): FormInterface\n {\n return $this->generateCreateForm($entry, TimesheetAdminEditForm::class, $this->generateUrl('admin_timesheet_duplicate', ['id' => $original->getId(), 'token' => $token]));", " }", " protected function getPermissionEditExport(): string\n {\n return 'edit_export_other_timesheet';\n }", " protected function getPermissionEditRate(): string\n {\n return 'edit_rate_other_timesheet';\n }", " protected function getEditFormClassName(): string\n {\n return TimesheetAdminEditForm::class;\n }", " protected function includeUserInForms(string $formName): bool\n {\n if ($formName === 'toolbar') {\n return true;\n }", " return $this->isGranted('edit_other_timesheet');\n }", " protected function getTimesheetRoute(): string\n {\n return 'admin_timesheet';\n }", " protected function getEditRoute(): string\n {\n return 'admin_timesheet_edit';\n }", " protected function getExportRoute(): string\n {\n return 'admin_timesheet_export';\n }", " protected function getMultiUpdateRoute(): string\n {\n return 'admin_timesheet_multi_update';\n }", " protected function getMultiDeleteRoute(): string\n {\n return 'admin_timesheet_multi_delete';\n }", " protected function canSeeStartEndTime(): bool\n {\n return true;\n }", " protected function getQueryNamePrefix(): string\n {\n return 'TeamTimes';\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace App\\EventSubscriber\\Actions;", "use App\\Entity\\Timesheet;\nuse App\\Event\\PageActionsEvent;", "/**\n * @internal\n */\nabstract class AbstractTimesheetSubscriber extends AbstractActionsSubscriber\n{\n protected function timesheetActions(PageActionsEvent $event, string $routeEdit, string $routeDuplicate): void\n {\n $payload = $event->getPayload();", " /** @var Timesheet $timesheet */\n $timesheet = $payload['timesheet'];\n if ($timesheet->getId() !== null) {\n if ($timesheet->isRunning() && $this->isGranted('stop', $timesheet)) {\n $event->addAction('stop', ['url' => $this->path('stop_timesheet', ['id' => $timesheet->getId()]), 'class' => 'api-link', 'attr' => ['data-event' => 'kimai.timesheetStop kimai.timesheetUpdate', 'data-method' => 'PATCH', 'data-msg-error' => 'timesheet.stop.error', 'data-msg-success' => 'timesheet.stop.success']]);\n }", " if (!$timesheet->isRunning() && $this->isGranted('start', $timesheet)) {\n $event->addAction('repeat', ['url' => $this->path('restart_timesheet', ['id' => $timesheet->getId()]), 'class' => 'api-link', 'attr' => ['data-payload' => '{\"copy\": \"all\"}', 'data-event' => 'kimai.timesheetStart kimai.timesheetUpdate', 'data-method' => 'PATCH', 'data-msg-error' => 'timesheet.start.error', 'data-msg-success' => 'timesheet.start.success']]);\n }", " if ($this->isGranted('edit', $timesheet)) {\n $class = $event->isView('edit') ? '' : 'modal-ajax-form';\n $event->addAction('edit', ['url' => $this->path($routeEdit, ['id' => $timesheet->getId()]), 'class' => $class]);\n }", " if ($this->isGranted('duplicate', $timesheet)) {\n $class = $event->isView('edit') ? '' : 'modal-ajax-form';", " $event->addAction('copy', ['url' => $this->path($routeDuplicate, ['id' => $timesheet->getId()]), 'class' => $class]);", " }", " if ($event->countActions() > 0) {\n $event->addDivider();\n }", " if ($event->isIndexView() && $this->isGranted('delete', $timesheet)) {\n $event->addAction('trash', [\n 'url' => $this->path('delete_timesheet', ['id' => $timesheet->getId()]),\n 'class' => 'api-link',\n 'attr' => [\n 'data-event' => 'kimai.timesheetDelete',\n 'data-method' => 'DELETE',\n 'data-question' => 'confirm.delete',\n 'data-msg-error' => 'action.delete.error',\n 'data-msg-success' => 'action.delete.success'\n ]\n ]);\n }\n }", " if (!$event->isIndexView()) {\n $event->addHelp($this->documentationLink('timesheet.html'));\n }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace App\\EventSubscriber\\Actions;", "use App\\Entity\\Timesheet;\nuse App\\Event\\PageActionsEvent;", "/**\n * @internal\n */\nabstract class AbstractTimesheetSubscriber extends AbstractActionsSubscriber\n{\n protected function timesheetActions(PageActionsEvent $event, string $routeEdit, string $routeDuplicate): void\n {\n $payload = $event->getPayload();", " /** @var Timesheet $timesheet */\n $timesheet = $payload['timesheet'];\n if ($timesheet->getId() !== null) {\n if ($timesheet->isRunning() && $this->isGranted('stop', $timesheet)) {\n $event->addAction('stop', ['url' => $this->path('stop_timesheet', ['id' => $timesheet->getId()]), 'class' => 'api-link', 'attr' => ['data-event' => 'kimai.timesheetStop kimai.timesheetUpdate', 'data-method' => 'PATCH', 'data-msg-error' => 'timesheet.stop.error', 'data-msg-success' => 'timesheet.stop.success']]);\n }", " if (!$timesheet->isRunning() && $this->isGranted('start', $timesheet)) {\n $event->addAction('repeat', ['url' => $this->path('restart_timesheet', ['id' => $timesheet->getId()]), 'class' => 'api-link', 'attr' => ['data-payload' => '{\"copy\": \"all\"}', 'data-event' => 'kimai.timesheetStart kimai.timesheetUpdate', 'data-method' => 'PATCH', 'data-msg-error' => 'timesheet.start.error', 'data-msg-success' => 'timesheet.start.success']]);\n }", " if ($this->isGranted('edit', $timesheet)) {\n $class = $event->isView('edit') ? '' : 'modal-ajax-form';\n $event->addAction('edit', ['url' => $this->path($routeEdit, ['id' => $timesheet->getId()]), 'class' => $class]);\n }", " if ($this->isGranted('duplicate', $timesheet)) {\n $class = $event->isView('edit') ? '' : 'modal-ajax-form';", " $event->addAction('copy', ['url' => $this->path($routeDuplicate, ['id' => $timesheet->getId(), 'token' => $payload['token']]), 'class' => $class]);", " }", " if ($event->countActions() > 0) {\n $event->addDivider();\n }", " if ($event->isIndexView() && $this->isGranted('delete', $timesheet)) {\n $event->addAction('trash', [\n 'url' => $this->path('delete_timesheet', ['id' => $timesheet->getId()]),\n 'class' => 'api-link',\n 'attr' => [\n 'data-event' => 'kimai.timesheetDelete',\n 'data-method' => 'DELETE',\n 'data-question' => 'confirm.delete',\n 'data-msg-error' => 'action.delete.error',\n 'data-msg-success' => 'action.delete.success'\n ]\n ]);\n }\n }", " if (!$event->isIndexView()) {\n $event->addHelp($this->documentationLink('timesheet.html'));\n }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace App\\EventSubscriber\\Actions;", "use App\\Entity\\Project;\nuse App\\Event\\PageActionsEvent;", "class ProjectSubscriber extends AbstractActionsSubscriber\n{\n public static function getActionName(): string\n {\n return 'project';\n }", " public function onActions(PageActionsEvent $event): void\n {\n $payload = $event->getPayload();", " /** @var Project $project */\n $project = $payload['project'];", " if ($project->getId() === null) {\n return;\n }", " if (!$event->isView('project_details') && $this->isGranted('view', $project)) {\n $event->addAction('details', ['url' => $this->path('project_details', ['id' => $project->getId()])]);\n }", " if ($this->isGranted('edit', $project)) {\n $class = $event->isView('edit') ? '' : 'modal-ajax-form';\n $event->addAction('edit', ['url' => $this->path('admin_project_edit', ['id' => $project->getId()]), 'class' => $class]);\n }", " if ($this->isGranted('permissions', $project)) {\n $class = $event->isView('permissions') ? '' : 'modal-ajax-form';\n $event->addAction('permissions', ['url' => $this->path('admin_project_permissions', ['id' => $project->getId()]), 'class' => $class]);\n }", " if ($event->countActions() > 0) {\n $event->addDivider();\n }", " if ($this->isGranted('view_activity')) {\n $event->addActionToSubmenu('filter', 'activity', ['title' => 'activity', 'translation_domain' => 'actions', 'url' => $this->path('admin_activity', ['customers[]' => $project->getCustomer()->getId(), 'projects[]' => $project->getId()])]);\n }", " if ($this->isGranted('view_other_timesheet')) {\n $event->addActionToSubmenu('filter', 'timesheet', ['title' => 'timesheet', 'translation_domain' => 'actions', 'url' => $this->path('admin_timesheet', ['customers[]' => $project->getCustomer()->getId(), 'projects[]' => $project->getId()])]);\n }", " if ($event->hasSubmenu('filter')) {\n $event->addDivider();\n }", " if (!$event->isView('project_details')) {\n if ($project->isVisible() && $project->getCustomer()->isVisible() && $this->isGranted('create_activity')) {\n $event->addAction('create-activity', [\n 'icon' => 'create',\n 'url' => $this->path('admin_activity_create_with_project', ['project' => $project->getId()]),\n 'class' => 'modal-ajax-form'\n ]);\n }\n }", " if ($this->isGranted('edit', $project) && $this->isGranted('create_project')) {\n $event->addAction(\n 'copy',", " ['url' => $this->path('admin_project_duplicate', ['id' => $project->getId()])]", " );\n }", " if (($event->isIndexView() || $event->isView('customer_details')) && $this->isGranted('delete', $project)) {\n $event->addDelete($this->path('admin_project_delete', ['id' => $project->getId()]));\n }", " if ($project->isVisible() && $this->isGranted('view_reporting') && $this->isGranted('details', $project)) {\n $event->addAction('report_project_details', ['url' => $this->path('report_project_details', ['project' => $project->getId()]), 'icon' => 'reporting', 'translation_domain' => 'reporting']);\n }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace App\\EventSubscriber\\Actions;", "use App\\Entity\\Project;\nuse App\\Event\\PageActionsEvent;", "class ProjectSubscriber extends AbstractActionsSubscriber\n{\n public static function getActionName(): string\n {\n return 'project';\n }", " public function onActions(PageActionsEvent $event): void\n {\n $payload = $event->getPayload();", " /** @var Project $project */\n $project = $payload['project'];", " if ($project->getId() === null) {\n return;\n }", " if (!$event->isView('project_details') && $this->isGranted('view', $project)) {\n $event->addAction('details', ['url' => $this->path('project_details', ['id' => $project->getId()])]);\n }", " if ($this->isGranted('edit', $project)) {\n $class = $event->isView('edit') ? '' : 'modal-ajax-form';\n $event->addAction('edit', ['url' => $this->path('admin_project_edit', ['id' => $project->getId()]), 'class' => $class]);\n }", " if ($this->isGranted('permissions', $project)) {\n $class = $event->isView('permissions') ? '' : 'modal-ajax-form';\n $event->addAction('permissions', ['url' => $this->path('admin_project_permissions', ['id' => $project->getId()]), 'class' => $class]);\n }", " if ($event->countActions() > 0) {\n $event->addDivider();\n }", " if ($this->isGranted('view_activity')) {\n $event->addActionToSubmenu('filter', 'activity', ['title' => 'activity', 'translation_domain' => 'actions', 'url' => $this->path('admin_activity', ['customers[]' => $project->getCustomer()->getId(), 'projects[]' => $project->getId()])]);\n }", " if ($this->isGranted('view_other_timesheet')) {\n $event->addActionToSubmenu('filter', 'timesheet', ['title' => 'timesheet', 'translation_domain' => 'actions', 'url' => $this->path('admin_timesheet', ['customers[]' => $project->getCustomer()->getId(), 'projects[]' => $project->getId()])]);\n }", " if ($event->hasSubmenu('filter')) {\n $event->addDivider();\n }", " if (!$event->isView('project_details')) {\n if ($project->isVisible() && $project->getCustomer()->isVisible() && $this->isGranted('create_activity')) {\n $event->addAction('create-activity', [\n 'icon' => 'create',\n 'url' => $this->path('admin_activity_create_with_project', ['project' => $project->getId()]),\n 'class' => 'modal-ajax-form'\n ]);\n }\n }", " if ($this->isGranted('edit', $project) && $this->isGranted('create_project')) {\n $event->addAction(\n 'copy',", " ['url' => $this->path('admin_project_duplicate', ['id' => $project->getId(), 'token' => $payload['token']])]", " );\n }", " if (($event->isIndexView() || $event->isView('customer_details')) && $this->isGranted('delete', $project)) {\n $event->addDelete($this->path('admin_project_delete', ['id' => $project->getId()]));\n }", " if ($project->isVisible() && $this->isGranted('view_reporting') && $this->isGranted('details', $project)) {\n $event->addAction('report_project_details', ['url' => $this->path('report_project_details', ['project' => $project->getId()]), 'icon' => 'reporting', 'translation_domain' => 'reporting']);\n }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace App\\EventSubscriber\\Actions;", "use App\\Entity\\Team;\nuse App\\Event\\PageActionsEvent;", "class TeamSubscriber extends AbstractActionsSubscriber\n{\n public static function getActionName(): string\n {\n return 'team';\n }", " public function onActions(PageActionsEvent $event): void\n {\n $payload = $event->getPayload();", " /** @var Team $team */\n $team = $payload['team'];", " if ($team->getId() === null) {\n return;\n }", " if ($this->isGranted('edit', $team)) {\n $event->addAction('edit', ['url' => $this->path('admin_team_edit', ['id' => $team->getId()])]);", " if ($this->isGranted('create_team')) {", " $event->addAction('copy', ['url' => $this->path('team_duplicate', ['id' => $team->getId()])]);", " }\n }", " if ($event->isIndexView() && $this->isGranted('delete', $team)) {\n $event->addAction('trash', [\n 'url' => $this->path('delete_team', ['id' => $team->getId()]),\n 'class' => 'api-link',\n 'attr' => [\n 'data-event' => 'kimai.teamDelete kimai.teamUpdate',\n 'data-method' => 'DELETE',\n 'data-question' => 'confirm.delete',\n 'data-msg-error' => 'action.delete.error',\n 'data-msg-success' => 'action.delete.success'\n ]\n ]);\n }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace App\\EventSubscriber\\Actions;", "use App\\Entity\\Team;\nuse App\\Event\\PageActionsEvent;", "class TeamSubscriber extends AbstractActionsSubscriber\n{\n public static function getActionName(): string\n {\n return 'team';\n }", " public function onActions(PageActionsEvent $event): void\n {\n $payload = $event->getPayload();", " /** @var Team $team */\n $team = $payload['team'];", " if ($team->getId() === null) {\n return;\n }", " if ($this->isGranted('edit', $team)) {\n $event->addAction('edit', ['url' => $this->path('admin_team_edit', ['id' => $team->getId()])]);", " if ($this->isGranted('create_team')) {", " $event->addAction('copy', ['url' => $this->path('team_duplicate', ['id' => $team->getId(), 'token' => $payload['token']])]);", " }\n }", " if ($event->isIndexView() && $this->isGranted('delete', $team)) {\n $event->addAction('trash', [\n 'url' => $this->path('delete_team', ['id' => $team->getId()]),\n 'class' => 'api-link',\n 'attr' => [\n 'data-event' => 'kimai.teamDelete kimai.teamUpdate',\n 'data-method' => 'DELETE',\n 'data-question' => 'confirm.delete',\n 'data-msg-error' => 'action.delete.error',\n 'data-msg-success' => 'action.delete.success'\n ]\n ]);\n }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "declare(strict_types=1);", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace DoctrineMigrations;", "use App\\Doctrine\\AbstractMigration;\nuse Doctrine\\DBAL\\Schema\\Schema;", "/**\n * Initial database structure of Kimai 2.\n * This file is mainly required for testing the migrations.\n */\nfinal class Version20180701120000 extends AbstractMigration\n{\n public function up(Schema $schema): void\n {", " $users = 'kimai2_users';\n $userPreferences = 'kimai2_user_preferences';\n $customers = 'kimai2_customers';\n $projects = 'kimai2_projects';\n $activities = 'kimai2_activities';\n $timesheets = 'kimai2_timesheet';\n $invoiceTemplates = 'kimai2_invoice_templates';", " $this->addSql('CREATE TABLE ' . $users . ' (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(60) NOT NULL, mail VARCHAR(160) NOT NULL, password VARCHAR(254) DEFAULT NULL, alias VARCHAR(60) DEFAULT NULL, active TINYINT(1) NOT NULL, registration_date DATETIME DEFAULT NULL, title VARCHAR(50) DEFAULT NULL, avatar VARCHAR(255) DEFAULT NULL, roles LONGTEXT NOT NULL COMMENT \\'(DC2Type:array)\\', UNIQUE INDEX UNIQ_B9AC5BCE5E237E06 (name), UNIQUE INDEX UNIQ_B9AC5BCE5126AC48 (mail), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB');\n $this->addSql('CREATE TABLE ' . $userPreferences . ' (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, name VARCHAR(50) NOT NULL, value VARCHAR(255) DEFAULT NULL, INDEX IDX_8D08F631A76ED395 (user_id), UNIQUE INDEX UNIQ_8D08F631A76ED3955E237E06 (user_id, name), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB');\n $this->addSql('CREATE TABLE ' . $customers . ' (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(150) NOT NULL, number VARCHAR(50) DEFAULT NULL, comment TEXT DEFAULT NULL, visible TINYINT(1) NOT NULL, company VARCHAR(255) DEFAULT NULL, contact VARCHAR(255) DEFAULT NULL, address TEXT DEFAULT NULL, country VARCHAR(2) NOT NULL, currency VARCHAR(3) NOT NULL, phone VARCHAR(255) DEFAULT NULL, fax VARCHAR(255) DEFAULT NULL, mobile VARCHAR(255) DEFAULT NULL, mail VARCHAR(255) DEFAULT NULL, homepage VARCHAR(255) DEFAULT NULL, timezone VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB');\n $this->addSql('CREATE TABLE ' . $projects . ' (id INT AUTO_INCREMENT NOT NULL, customer_id INT DEFAULT NULL, name VARCHAR(150) NOT NULL, order_number TINYTEXT DEFAULT NULL, comment TEXT DEFAULT NULL, visible TINYINT(1) NOT NULL, budget NUMERIC(10, 2) NOT NULL, INDEX IDX_407F12069395C3F3 (customer_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB');\n $this->addSql('CREATE TABLE ' . $activities . ' (id INT AUTO_INCREMENT NOT NULL, project_id INT DEFAULT NULL, name VARCHAR(150) NOT NULL, comment TEXT DEFAULT NULL, visible TINYINT(1) NOT NULL, INDEX IDX_8811FE1C166D1F9C (project_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB');\n $this->addSql('CREATE TABLE ' . $timesheets . ' (id INT AUTO_INCREMENT NOT NULL, user INT DEFAULT NULL, activity_id INT DEFAULT NULL, start_time DATETIME NOT NULL, end_time DATETIME DEFAULT NULL, duration INT DEFAULT NULL, description TEXT DEFAULT NULL, rate NUMERIC(10, 2) NOT NULL, INDEX IDX_4F60C6B18D93D649 (user), INDEX IDX_4F60C6B181C06096 (activity_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB');\n $this->addSql('CREATE TABLE ' . $invoiceTemplates . ' (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(60) NOT NULL, title VARCHAR(255) NOT NULL, company VARCHAR(255) NOT NULL, address TEXT DEFAULT NULL, due_days INT NOT NULL, vat INT DEFAULT NULL, calculator VARCHAR(20) NOT NULL, number_generator VARCHAR(20) NOT NULL, renderer VARCHAR(20) NOT NULL, payment_terms TEXT DEFAULT NULL, UNIQUE INDEX UNIQ_1626CFE95E237E06 (name), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB');\n $this->addSql('ALTER TABLE ' . $userPreferences . ' ADD CONSTRAINT FK_8D08F631A76ED395 FOREIGN KEY (user_id) REFERENCES ' . $users . ' (id) ON DELETE CASCADE');\n $this->addSql('ALTER TABLE ' . $projects . ' ADD CONSTRAINT FK_407F12069395C3F3 FOREIGN KEY (customer_id) REFERENCES ' . $customers . ' (id) ON DELETE CASCADE');\n $this->addSql('ALTER TABLE ' . $activities . ' ADD CONSTRAINT FK_8811FE1C166D1F9C FOREIGN KEY (project_id) REFERENCES ' . $projects . ' (id) ON DELETE CASCADE');\n $this->addSql('ALTER TABLE ' . $timesheets . ' ADD CONSTRAINT FK_4F60C6B18D93D649 FOREIGN KEY (user) REFERENCES ' . $users . ' (id)');\n $this->addSql('ALTER TABLE ' . $timesheets . ' ADD CONSTRAINT FK_4F60C6B181C06096 FOREIGN KEY (activity_id) REFERENCES ' . $activities . ' (id) ON DELETE CASCADE');", " }", " public function down(Schema $schema): void\n {\n $schema->dropTable('kimai2_invoice_templates');\n $schema->dropTable('kimai2_timesheet');\n $schema->dropTable('kimai2_user_preferences');\n $schema->dropTable('kimai2_users');\n $schema->dropTable('kimai2_activities');\n $schema->dropTable('kimai2_projects');\n $schema->dropTable('kimai2_customers');\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "declare(strict_types=1);", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace DoctrineMigrations;", "use App\\Doctrine\\AbstractMigration;\nuse Doctrine\\DBAL\\Schema\\Schema;", "/**\n * Initial database structure of Kimai 2.\n * This file is mainly required for testing the migrations.\n */\nfinal class Version20180701120000 extends AbstractMigration\n{\n public function up(Schema $schema): void\n {", " $this->addSql('CREATE TABLE kimai2_users (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(60) NOT NULL, mail VARCHAR(160) NOT NULL, password VARCHAR(254) DEFAULT NULL, alias VARCHAR(60) DEFAULT NULL, active TINYINT(1) NOT NULL, registration_date DATETIME DEFAULT NULL, title VARCHAR(50) DEFAULT NULL, avatar VARCHAR(255) DEFAULT NULL, roles LONGTEXT NOT NULL COMMENT \\'(DC2Type:array)\\', UNIQUE INDEX UNIQ_B9AC5BCE5E237E06 (name), UNIQUE INDEX UNIQ_B9AC5BCE5126AC48 (mail), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB');\n $this->addSql('CREATE TABLE kimai2_user_preferences (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, name VARCHAR(50) NOT NULL, value VARCHAR(255) DEFAULT NULL, INDEX IDX_8D08F631A76ED395 (user_id), UNIQUE INDEX UNIQ_8D08F631A76ED3955E237E06 (user_id, name), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB');\n $this->addSql('CREATE TABLE kimai2_customers (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(150) NOT NULL, number VARCHAR(50) DEFAULT NULL, comment TEXT DEFAULT NULL, visible TINYINT(1) NOT NULL, company VARCHAR(255) DEFAULT NULL, contact VARCHAR(255) DEFAULT NULL, address TEXT DEFAULT NULL, country VARCHAR(2) NOT NULL, currency VARCHAR(3) NOT NULL, phone VARCHAR(255) DEFAULT NULL, fax VARCHAR(255) DEFAULT NULL, mobile VARCHAR(255) DEFAULT NULL, mail VARCHAR(255) DEFAULT NULL, homepage VARCHAR(255) DEFAULT NULL, timezone VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB');\n $this->addSql('CREATE TABLE kimai2_projects (id INT AUTO_INCREMENT NOT NULL, customer_id INT DEFAULT NULL, name VARCHAR(150) NOT NULL, order_number TINYTEXT DEFAULT NULL, comment TEXT DEFAULT NULL, visible TINYINT(1) NOT NULL, budget NUMERIC(10, 2) NOT NULL, INDEX IDX_407F12069395C3F3 (customer_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB');\n $this->addSql('CREATE TABLE kimai2_activities (id INT AUTO_INCREMENT NOT NULL, project_id INT DEFAULT NULL, name VARCHAR(150) NOT NULL, comment TEXT DEFAULT NULL, visible TINYINT(1) NOT NULL, INDEX IDX_8811FE1C166D1F9C (project_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB');\n $this->addSql('CREATE TABLE kimai2_timesheet (id INT AUTO_INCREMENT NOT NULL, user INT DEFAULT NULL, activity_id INT DEFAULT NULL, start_time DATETIME NOT NULL, end_time DATETIME DEFAULT NULL, duration INT DEFAULT NULL, description TEXT DEFAULT NULL, rate NUMERIC(10, 2) NOT NULL, INDEX IDX_4F60C6B18D93D649 (user), INDEX IDX_4F60C6B181C06096 (activity_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB');\n $this->addSql('CREATE TABLE kimai2_invoice_templates (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(60) NOT NULL, title VARCHAR(255) NOT NULL, company VARCHAR(255) NOT NULL, address TEXT DEFAULT NULL, due_days INT NOT NULL, vat INT DEFAULT NULL, calculator VARCHAR(20) NOT NULL, number_generator VARCHAR(20) NOT NULL, renderer VARCHAR(20) NOT NULL, payment_terms TEXT DEFAULT NULL, UNIQUE INDEX UNIQ_1626CFE95E237E06 (name), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB');\n $this->addSql('ALTER TABLE kimai2_user_preferences ADD CONSTRAINT FK_8D08F631A76ED395 FOREIGN KEY (user_id) REFERENCES kimai2_users (id) ON DELETE CASCADE');\n $this->addSql('ALTER TABLE kimai2_projects ADD CONSTRAINT FK_407F12069395C3F3 FOREIGN KEY (customer_id) REFERENCES kimai2_customers (id) ON DELETE CASCADE');\n $this->addSql('ALTER TABLE kimai2_activities ADD CONSTRAINT FK_8811FE1C166D1F9C FOREIGN KEY (project_id) REFERENCES kimai2_projects (id) ON DELETE CASCADE');\n $this->addSql('ALTER TABLE kimai2_timesheet ADD CONSTRAINT FK_4F60C6B18D93D649 FOREIGN KEY (user) REFERENCES kimai2_users (id)');\n $this->addSql('ALTER TABLE kimai2_timesheet ADD CONSTRAINT FK_4F60C6B181C06096 FOREIGN KEY (activity_id) REFERENCES kimai2_activities (id) ON DELETE CASCADE');", " }", " public function down(Schema $schema): void\n {\n $schema->dropTable('kimai2_invoice_templates');\n $schema->dropTable('kimai2_timesheet');\n $schema->dropTable('kimai2_user_preferences');\n $schema->dropTable('kimai2_users');\n $schema->dropTable('kimai2_activities');\n $schema->dropTable('kimai2_projects');\n $schema->dropTable('kimai2_customers');\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "declare(strict_types=1);", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace DoctrineMigrations;", "use App\\Doctrine\\AbstractMigration;\nuse Doctrine\\DBAL\\Schema\\Index;\nuse Doctrine\\DBAL\\Schema\\Schema;", "/**\n * Migration for FOSUserBundle\n *\n * Changes the table structure of \"users\" table and migrates from json_array type to serialized array,\n * probably also fixing the higher required MariaDB version.\n *\n * This was fixed in earlier migrations for new installations, but it is still in here for users migrating up from a lower version.\n */\nfinal class Version20180715160326 extends AbstractMigration\n{\n /**\n * @var Index[]\n */\n protected $indexesOld = [];", " /**\n * @param Schema $schema\n * @throws \\Doctrine\\DBAL\\DBALException\n * @throws \\Doctrine\\DBAL\\Schema\\SchemaException\n */\n public function up(Schema $schema): void\n {", " $users = 'kimai2_users';\n", " // delete all existing indexes", " $indexesOld = $schema->getTable($users)->getIndexes();", " foreach ($indexesOld as $index) {\n if (\\in_array('name', $index->getColumns()) || \\in_array('mail', $index->getColumns())) {\n $this->indexesOld[] = $index;", " $this->addSql('DROP INDEX ' . $index->getName() . ' ON ' . $users);", " }\n }\n", " $this->addSql('ALTER TABLE ' . $users . ' CHANGE name username VARCHAR(180) NOT NULL, ADD username_canonical VARCHAR(180) NOT NULL, CHANGE mail email VARCHAR(180) NOT NULL, ADD email_canonical VARCHAR(180) NOT NULL, ADD salt VARCHAR(255) DEFAULT NULL, ADD last_login DATETIME DEFAULT NULL, ADD confirmation_token VARCHAR(180) DEFAULT NULL, ADD password_requested_at DATETIME DEFAULT NULL, CHANGE password password VARCHAR(255) NOT NULL, CHANGE alias alias VARCHAR(60) DEFAULT NULL, CHANGE registration_date registration_date DATETIME DEFAULT NULL, CHANGE title title VARCHAR(50) DEFAULT NULL, CHANGE avatar avatar VARCHAR(255) DEFAULT NULL, CHANGE roles roles LONGTEXT NOT NULL COMMENT \\'(DC2Type:array)\\', CHANGE active enabled TINYINT(1) NOT NULL');\n $this->addSql('UPDATE ' . $users . ' set username_canonical = username');\n $this->addSql('UPDATE ' . $users . ' set email_canonical = email');", "", " $this->addSql('UPDATE ' . $users . ' SET roles = \\'a:1:{i:0;s:16:\"ROLE_SUPER_ADMIN\";}\\' WHERE roles LIKE \\'%ROLE_SUPER_ADMIN%\\'');\n $this->addSql('UPDATE ' . $users . ' SET roles = \\'a:1:{i:0;s:10:\"ROLE_ADMIN\";}\\' WHERE roles LIKE \\'%ROLE_ADMIN%\\'');\n $this->addSql('UPDATE ' . $users . ' SET roles = \\'a:1:{i:0;s:13:\"ROLE_TEAMLEAD\";}\\' WHERE roles LIKE \\'%ROLE_TEAMLEAD%\\'');\n $this->addSql('UPDATE ' . $users . ' SET roles = \\'a:0:{}\\' WHERE roles LIKE \\'%ROLE_USER%\\'');\n $this->addSql('UPDATE ' . $users . ' SET roles = \\'a:1:{i:0;s:13:\"ROLE_CUSTOMER\";}\\' WHERE roles LIKE \\'%ROLE_CUSTOMER%\\'');", "", " $this->addSql('CREATE UNIQUE INDEX UNIQ_B9AC5BCE92FC23A8 ON ' . $users . ' (username_canonical)');\n $this->addSql('CREATE UNIQUE INDEX UNIQ_B9AC5BCEA0D96FBF ON ' . $users . ' (email_canonical)');\n $this->addSql('CREATE UNIQUE INDEX UNIQ_B9AC5BCEC05FB297 ON ' . $users . ' (confirmation_token)');\n $this->addSql('CREATE UNIQUE INDEX UNIQ_B9AC5BCEF85E0677 ON ' . $users . ' (username)');\n $this->addSql('CREATE UNIQUE INDEX UNIQ_B9AC5BCEE7927C74 ON ' . $users . ' (email)');", " }", " /**\n * @param Schema $schema\n * @throws \\Doctrine\\DBAL\\DBALException\n * @throws \\Doctrine\\DBAL\\Schema\\SchemaException\n */\n public function down(Schema $schema): void\n {", " $users = 'kimai2_users';\n", " $indexToDelete = ['UNIQ_B9AC5BCE92FC23A8', 'UNIQ_B9AC5BCEA0D96FBF', 'UNIQ_B9AC5BCEC05FB297', 'UNIQ_B9AC5BCEF85E0677', 'UNIQ_B9AC5BCEE7927C74'];\n foreach ($indexToDelete as $indexName) {", " $this->addSql('DROP INDEX ' . $indexName . ' ON ' . $users);", " }\n", " $this->addSql('ALTER TABLE ' . $users . ' CHANGE username name VARCHAR(60) NOT NULL COLLATE utf8mb4_unicode_ci, CHANGE email mail VARCHAR(160) NOT NULL COLLATE utf8mb4_unicode_ci, DROP username_canonical, DROP email_canonical, DROP salt, DROP last_login, DROP confirmation_token, DROP password_requested_at, CHANGE password password VARCHAR(254) DEFAULT NULL COLLATE utf8mb4_unicode_ci, CHANGE roles roles LONGTEXT NOT NULL COMMENT \\'(DC2Type:array)\\', CHANGE alias alias VARCHAR(60) DEFAULT NULL COLLATE utf8mb4_unicode_ci, CHANGE registration_date registration_date DATETIME DEFAULT NULL, CHANGE title title VARCHAR(50) DEFAULT NULL COLLATE utf8mb4_unicode_ci, CHANGE avatar avatar VARCHAR(255) DEFAULT NULL COLLATE utf8mb4_unicode_ci, CHANGE enabled active TINYINT(1) NOT NULL');", "", " $this->addSql('UPDATE ' . $users . ' SET roles = \\'[\"ROLE_SUPER_ADMIN\"]\\' WHERE roles LIKE \\'%ROLE_SUPER_ADMIN%\\'');\n $this->addSql('UPDATE ' . $users . ' SET roles = \\'[\"ROLE_ADMIN\"]\\' WHERE roles LIKE \\'%ROLE_ADMIN%\\'');\n $this->addSql('UPDATE ' . $users . ' SET roles = \\'[\"ROLE_TEAMLEAD\"]\\' WHERE roles LIKE \\'%ROLE_TEAMLEAD%\\'');\n $this->addSql('UPDATE ' . $users . ' SET roles = \\'[\"ROLE_USER\"]\\' WHERE roles LIKE \\'%ROLE_USER%\\'');\n $this->addSql('UPDATE ' . $users . ' SET roles = \\'[\"ROLE_CUSTOMER\"]\\' WHERE roles LIKE \\'%ROLE_CUSTOMER%\\'');", "", " $this->addSql('CREATE UNIQUE INDEX UNIQ_B9AC5BCE5E237E06 ON ' . $users . ' (name)');\n $this->addSql('CREATE UNIQUE INDEX UNIQ_B9AC5BCE5126AC48 ON ' . $users . ' (mail)');", "", " $usersTable = $schema->getTable($users);", " foreach ($this->indexesOld as $index) {\n $usersTable->addIndex($index->getColumns(), $index->getName(), $index->getFlags(), $index->getOptions());\n }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "declare(strict_types=1);", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace DoctrineMigrations;", "use App\\Doctrine\\AbstractMigration;\nuse Doctrine\\DBAL\\Schema\\Index;\nuse Doctrine\\DBAL\\Schema\\Schema;", "/**\n * Migration for FOSUserBundle\n *\n * Changes the table structure of \"users\" table and migrates from json_array type to serialized array,\n * probably also fixing the higher required MariaDB version.\n *\n * This was fixed in earlier migrations for new installations, but it is still in here for users migrating up from a lower version.\n */\nfinal class Version20180715160326 extends AbstractMigration\n{\n /**\n * @var Index[]\n */\n protected $indexesOld = [];", " /**\n * @param Schema $schema\n * @throws \\Doctrine\\DBAL\\DBALException\n * @throws \\Doctrine\\DBAL\\Schema\\SchemaException\n */\n public function up(Schema $schema): void\n {", "", " // delete all existing indexes", " $indexesOld = $schema->getTable('kimai2_users')->getIndexes();", " foreach ($indexesOld as $index) {\n if (\\in_array('name', $index->getColumns()) || \\in_array('mail', $index->getColumns())) {\n $this->indexesOld[] = $index;", " $this->addSql('DROP INDEX ' . $index->getName() . ' ON kimai2_users');", " }\n }\n", " $this->addSql('ALTER TABLE kimai2_users CHANGE name username VARCHAR(180) NOT NULL, ADD username_canonical VARCHAR(180) NOT NULL, CHANGE mail email VARCHAR(180) NOT NULL, ADD email_canonical VARCHAR(180) NOT NULL, ADD salt VARCHAR(255) DEFAULT NULL, ADD last_login DATETIME DEFAULT NULL, ADD confirmation_token VARCHAR(180) DEFAULT NULL, ADD password_requested_at DATETIME DEFAULT NULL, CHANGE password password VARCHAR(255) NOT NULL, CHANGE alias alias VARCHAR(60) DEFAULT NULL, CHANGE registration_date registration_date DATETIME DEFAULT NULL, CHANGE title title VARCHAR(50) DEFAULT NULL, CHANGE avatar avatar VARCHAR(255) DEFAULT NULL, CHANGE roles roles LONGTEXT NOT NULL COMMENT \\'(DC2Type:array)\\', CHANGE active enabled TINYINT(1) NOT NULL');\n $this->addSql('UPDATE kimai2_users set username_canonical = username');\n $this->addSql('UPDATE kimai2_users set email_canonical = email');", "", " $this->addSql('UPDATE kimai2_users SET roles = \\'a:1:{i:0;s:16:\"ROLE_SUPER_ADMIN\";}\\' WHERE roles LIKE \\'%ROLE_SUPER_ADMIN%\\'');\n $this->addSql('UPDATE kimai2_users SET roles = \\'a:1:{i:0;s:10:\"ROLE_ADMIN\";}\\' WHERE roles LIKE \\'%ROLE_ADMIN%\\'');\n $this->addSql('UPDATE kimai2_users SET roles = \\'a:1:{i:0;s:13:\"ROLE_TEAMLEAD\";}\\' WHERE roles LIKE \\'%ROLE_TEAMLEAD%\\'');\n $this->addSql('UPDATE kimai2_users SET roles = \\'a:0:{}\\' WHERE roles LIKE \\'%ROLE_USER%\\'');\n $this->addSql('UPDATE kimai2_users SET roles = \\'a:1:{i:0;s:13:\"ROLE_CUSTOMER\";}\\' WHERE roles LIKE \\'%ROLE_CUSTOMER%\\'');", "", " $this->addSql('CREATE UNIQUE INDEX UNIQ_B9AC5BCE92FC23A8 ON kimai2_users (username_canonical)');\n $this->addSql('CREATE UNIQUE INDEX UNIQ_B9AC5BCEA0D96FBF ON kimai2_users (email_canonical)');\n $this->addSql('CREATE UNIQUE INDEX UNIQ_B9AC5BCEC05FB297 ON kimai2_users (confirmation_token)');\n $this->addSql('CREATE UNIQUE INDEX UNIQ_B9AC5BCEF85E0677 ON kimai2_users (username)');\n $this->addSql('CREATE UNIQUE INDEX UNIQ_B9AC5BCEE7927C74 ON kimai2_users (email)');", " }", " /**\n * @param Schema $schema\n * @throws \\Doctrine\\DBAL\\DBALException\n * @throws \\Doctrine\\DBAL\\Schema\\SchemaException\n */\n public function down(Schema $schema): void\n {", "", " $indexToDelete = ['UNIQ_B9AC5BCE92FC23A8', 'UNIQ_B9AC5BCEA0D96FBF', 'UNIQ_B9AC5BCEC05FB297', 'UNIQ_B9AC5BCEF85E0677', 'UNIQ_B9AC5BCEE7927C74'];\n foreach ($indexToDelete as $indexName) {", " $this->addSql('DROP INDEX ' . $indexName . ' ON kimai2_users');", " }\n", " $this->addSql('ALTER TABLE kimai2_users CHANGE username name VARCHAR(60) NOT NULL COLLATE utf8mb4_unicode_ci, CHANGE email mail VARCHAR(160) NOT NULL COLLATE utf8mb4_unicode_ci, DROP username_canonical, DROP email_canonical, DROP salt, DROP last_login, DROP confirmation_token, DROP password_requested_at, CHANGE password password VARCHAR(254) DEFAULT NULL COLLATE utf8mb4_unicode_ci, CHANGE roles roles LONGTEXT NOT NULL COMMENT \\'(DC2Type:array)\\', CHANGE alias alias VARCHAR(60) DEFAULT NULL COLLATE utf8mb4_unicode_ci, CHANGE registration_date registration_date DATETIME DEFAULT NULL, CHANGE title title VARCHAR(50) DEFAULT NULL COLLATE utf8mb4_unicode_ci, CHANGE avatar avatar VARCHAR(255) DEFAULT NULL COLLATE utf8mb4_unicode_ci, CHANGE enabled active TINYINT(1) NOT NULL');", "", " $this->addSql('UPDATE kimai2_users SET roles = \\'[\"ROLE_SUPER_ADMIN\"]\\' WHERE roles LIKE \\'%ROLE_SUPER_ADMIN%\\'');\n $this->addSql('UPDATE kimai2_users SET roles = \\'[\"ROLE_ADMIN\"]\\' WHERE roles LIKE \\'%ROLE_ADMIN%\\'');\n $this->addSql('UPDATE kimai2_users SET roles = \\'[\"ROLE_TEAMLEAD\"]\\' WHERE roles LIKE \\'%ROLE_TEAMLEAD%\\'');\n $this->addSql('UPDATE kimai2_users SET roles = \\'[\"ROLE_USER\"]\\' WHERE roles LIKE \\'%ROLE_USER%\\'');\n $this->addSql('UPDATE kimai2_users SET roles = \\'[\"ROLE_CUSTOMER\"]\\' WHERE roles LIKE \\'%ROLE_CUSTOMER%\\'');", "", " $this->addSql('CREATE UNIQUE INDEX UNIQ_B9AC5BCE5E237E06 ON kimai2_users (name)');\n $this->addSql('CREATE UNIQUE INDEX UNIQ_B9AC5BCE5126AC48 ON kimai2_users (mail)');", "", " $usersTable = $schema->getTable('kimai2_users');", " foreach ($this->indexesOld as $index) {\n $usersTable->addIndex($index->getColumns(), $index->getName(), $index->getFlags(), $index->getOptions());\n }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "declare(strict_types=1);", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace DoctrineMigrations;", "use App\\Doctrine\\AbstractMigration;\nuse Doctrine\\DBAL\\Schema\\Index;\nuse Doctrine\\DBAL\\Schema\\Schema;", "/**\n * Migrations fot the \"delete user\" feature.\n *\n * Adds constraints to the timesheet table, so all timesheet entries will be deleted when a user is deleted.\n */\nfinal class Version20180730044139 extends AbstractMigration\n{\n /**\n * @var Index[]\n */\n protected $indexesOld = [];", " /**\n * @param Schema $schema\n * @throws \\Doctrine\\DBAL\\DBALException\n */\n public function up(Schema $schema): void\n {", " $timesheet = 'kimai2_timesheet';\n $user = 'kimai2_users';\n $activity = 'kimai2_activities';", " $this->addSql('ALTER TABLE ' . $timesheet . ' DROP FOREIGN KEY FK_4F60C6B18D93D649');\n $this->addSql('ALTER TABLE ' . $timesheet . ' ADD CONSTRAINT FK_4F60C6B18D93D649 FOREIGN KEY (user) REFERENCES ' . $user . ' (id) ON DELETE CASCADE');", " }", " /**\n * @param Schema $schema\n * @throws \\Doctrine\\DBAL\\DBALException\n */\n public function down(Schema $schema): void\n {", " $timesheet = 'kimai2_timesheet';\n $user = 'kimai2_users';", " $this->addSql('ALTER TABLE ' . $timesheet . ' DROP FOREIGN KEY FK_4F60C6B18D93D649');\n $this->addSql('ALTER TABLE ' . $timesheet . ' ADD CONSTRAINT FK_4F60C6B18D93D649 FOREIGN KEY (user) REFERENCES ' . $user . ' (id)');", " }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "declare(strict_types=1);", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace DoctrineMigrations;", "use App\\Doctrine\\AbstractMigration;\nuse Doctrine\\DBAL\\Schema\\Index;\nuse Doctrine\\DBAL\\Schema\\Schema;", "/**\n * Migrations fot the \"delete user\" feature.\n *\n * Adds constraints to the timesheet table, so all timesheet entries will be deleted when a user is deleted.\n */\nfinal class Version20180730044139 extends AbstractMigration\n{\n /**\n * @var Index[]\n */\n protected $indexesOld = [];", " /**\n * @param Schema $schema\n * @throws \\Doctrine\\DBAL\\DBALException\n */\n public function up(Schema $schema): void\n {", " $this->addSql('ALTER TABLE kimai2_timesheet DROP FOREIGN KEY FK_4F60C6B18D93D649');\n $this->addSql('ALTER TABLE kimai2_timesheet ADD CONSTRAINT FK_4F60C6B18D93D649 FOREIGN KEY (user) REFERENCES kimai2_users (id) ON DELETE CASCADE');", " }", " /**\n * @param Schema $schema\n * @throws \\Doctrine\\DBAL\\DBALException\n */\n public function down(Schema $schema): void\n {", " $this->addSql('ALTER TABLE kimai2_timesheet DROP FOREIGN KEY FK_4F60C6B18D93D649');\n $this->addSql('ALTER TABLE kimai2_timesheet ADD CONSTRAINT FK_4F60C6B18D93D649 FOREIGN KEY (user) REFERENCES kimai2_users (id)');", " }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "declare(strict_types=1);", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace DoctrineMigrations;", "use App\\Doctrine\\AbstractMigration;\nuse Doctrine\\DBAL\\Schema\\Schema;", "/**\n * Changes the invoice templates table for:\n * - shorter template name and proper index name\n * - VAT supporting percentages\n */\nfinal class Version20180924111853 extends AbstractMigration\n{\n public function up(Schema $schema): void\n {", " $invoiceTemplates = 'kimai2_invoice_templates';", " $this->addSql('UPDATE ' . $invoiceTemplates . ' SET name=SUBSTRING(name, 1, 60)');\n $this->addSql('ALTER TABLE ' . $invoiceTemplates . ' CHANGE name name VARCHAR(60) NOT NULL, CHANGE vat vat DOUBLE PRECISION DEFAULT 0');", " }", " public function down(Schema $schema): void\n {", " $invoiceTemplates = 'kimai2_invoice_templates';", " $this->addSql('ALTER TABLE ' . $invoiceTemplates . ' CHANGE name name VARCHAR(255) NOT NULL COLLATE utf8mb4_unicode_ci, CHANGE vat vat INT DEFAULT NULL');", " }\n}" ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "declare(strict_types=1);", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace DoctrineMigrations;", "use App\\Doctrine\\AbstractMigration;\nuse Doctrine\\DBAL\\Schema\\Schema;", "/**\n * Changes the invoice templates table for:\n * - shorter template name and proper index name\n * - VAT supporting percentages\n */\nfinal class Version20180924111853 extends AbstractMigration\n{\n public function up(Schema $schema): void\n {", " $this->addSql('UPDATE kimai2_invoice_templates SET name=SUBSTRING(name, 1, 60)');\n $this->addSql('ALTER TABLE kimai2_invoice_templates CHANGE name name VARCHAR(60) NOT NULL, CHANGE vat vat DOUBLE PRECISION DEFAULT 0');", " }", " public function down(Schema $schema): void\n {", " $this->addSql('ALTER TABLE kimai2_invoice_templates CHANGE name name VARCHAR(255) NOT NULL COLLATE utf8mb4_unicode_ci, CHANGE vat vat INT DEFAULT NULL');", " }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "declare(strict_types=1);", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace DoctrineMigrations;", "use App\\Doctrine\\AbstractMigration;\nuse Doctrine\\DBAL\\Schema\\Schema;", "/**\n * Migration that adds the project column to timesheets table, to allow global activities.\n * It also fixes foreign-key columns on timesheet and projects table, which are not allowed.\n */\nfinal class Version20181031220003 extends AbstractMigration\n{\n public function up(Schema $schema): void\n {", " $timesheet = 'kimai2_timesheet';\n $projects = 'kimai2_projects';\n $activities = 'kimai2_activities';\n $users = 'kimai2_users';\n $customers = 'kimai2_customers';\n", " // project table", " $this->addSql('ALTER TABLE ' . $projects . ' DROP FOREIGN KEY FK_407F12069395C3F3');\n $this->addSql('ALTER TABLE ' . $projects . ' CHANGE customer_id customer_id INT NOT NULL');\n $this->addSql('ALTER TABLE ' . $projects . ' ADD CONSTRAINT FK_407F12069395C3F3 FOREIGN KEY (customer_id) REFERENCES ' . $customers . ' (id) ON DELETE CASCADE');", " // timesheet table", " $this->addSql('ALTER TABLE ' . $timesheet . ' ADD project_id INT DEFAULT NULL AFTER activity_id');\n $this->addSql('CREATE INDEX IDX_4F60C6B1166D1F9C ON ' . $timesheet . ' (project_id)');", "\n // update timesheet table and insert project_id from activity table", " $this->addSql('UPDATE ' . $timesheet . ' SET project_id = (SELECT project_id FROM ' . $activities . ' WHERE id = activity_id)');", "\n // now update the timesheet table and disallow null values for all required columns (that was a bug before)", " $this->addSql('ALTER TABLE ' . $timesheet . ' DROP FOREIGN KEY FK_4F60C6B18D93D649');\n $this->addSql('ALTER TABLE ' . $timesheet . ' DROP FOREIGN KEY FK_4F60C6B181C06096');\n $this->addSql('ALTER TABLE ' . $timesheet . ' CHANGE project_id project_id INT NOT NULL, CHANGE user user INT NOT NULL, CHANGE activity_id activity_id INT NOT NULL');\n $this->addSql('ALTER TABLE ' . $timesheet . ' ADD CONSTRAINT FK_4F60C6B1166D1F9C FOREIGN KEY (project_id) REFERENCES ' . $projects . ' (id) ON DELETE CASCADE');\n $this->addSql('ALTER TABLE ' . $timesheet . ' ADD CONSTRAINT FK_4F60C6B18D93D649 FOREIGN KEY (user) REFERENCES ' . $users . ' (id) ON DELETE CASCADE');\n $this->addSql('ALTER TABLE ' . $timesheet . ' ADD CONSTRAINT FK_4F60C6B181C06096 FOREIGN KEY (activity_id) REFERENCES ' . $activities . ' (id) ON DELETE CASCADE');", " }", " public function down(Schema $schema): void\n {", " $timesheet = 'kimai2_timesheet';\n $projects = 'kimai2_projects';\n $customers = 'kimai2_customers';\n", " // project table", " $this->addSql('ALTER TABLE ' . $projects . ' DROP FOREIGN KEY FK_407F12069395C3F3');\n $this->addSql('ALTER TABLE ' . $projects . ' CHANGE customer_id customer_id INT DEFAULT NULL');\n $this->addSql('ALTER TABLE ' . $projects . ' ADD CONSTRAINT FK_407F12069395C3F3 FOREIGN KEY (customer_id) REFERENCES ' . $customers . ' (id) ON DELETE CASCADE');", " // timesheet table", " $this->addSql('ALTER TABLE ' . $timesheet . ' DROP FOREIGN KEY FK_4F60C6B1166D1F9C');\n $this->addSql('DROP INDEX IDX_4F60C6B1166D1F9C ON ' . $timesheet);\n $this->addSql('ALTER TABLE ' . $timesheet . ' DROP project_id, CHANGE user user INT DEFAULT NULL, CHANGE activity_id activity_id INT DEFAULT NULL');", " }\n}" ]
[ 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "declare(strict_types=1);", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace DoctrineMigrations;", "use App\\Doctrine\\AbstractMigration;\nuse Doctrine\\DBAL\\Schema\\Schema;", "/**\n * Migration that adds the project column to timesheets table, to allow global activities.\n * It also fixes foreign-key columns on timesheet and projects table, which are not allowed.\n */\nfinal class Version20181031220003 extends AbstractMigration\n{\n public function up(Schema $schema): void\n {", "", " // project table", " $this->addSql('ALTER TABLE kimai2_projects DROP FOREIGN KEY FK_407F12069395C3F3');\n $this->addSql('ALTER TABLE kimai2_projects CHANGE customer_id customer_id INT NOT NULL');\n $this->addSql('ALTER TABLE kimai2_projects ADD CONSTRAINT FK_407F12069395C3F3 FOREIGN KEY (customer_id) REFERENCES kimai2_customers (id) ON DELETE CASCADE');", " // timesheet table", " $this->addSql('ALTER TABLE kimai2_timesheet ADD project_id INT DEFAULT NULL AFTER activity_id');\n $this->addSql('CREATE INDEX IDX_4F60C6B1166D1F9C ON kimai2_timesheet (project_id)');", "\n // update timesheet table and insert project_id from activity table", " $this->addSql('UPDATE kimai2_timesheet SET project_id = (SELECT project_id FROM kimai2_activities WHERE id = activity_id)');", "\n // now update the timesheet table and disallow null values for all required columns (that was a bug before)", " $this->addSql('ALTER TABLE kimai2_timesheet DROP FOREIGN KEY FK_4F60C6B18D93D649');\n $this->addSql('ALTER TABLE kimai2_timesheet DROP FOREIGN KEY FK_4F60C6B181C06096');\n $this->addSql('ALTER TABLE kimai2_timesheet CHANGE project_id project_id INT NOT NULL, CHANGE user user INT NOT NULL, CHANGE activity_id activity_id INT NOT NULL');\n $this->addSql('ALTER TABLE kimai2_timesheet ADD CONSTRAINT FK_4F60C6B1166D1F9C FOREIGN KEY (project_id) REFERENCES kimai2_projects (id) ON DELETE CASCADE');\n $this->addSql('ALTER TABLE kimai2_timesheet ADD CONSTRAINT FK_4F60C6B18D93D649 FOREIGN KEY (user) REFERENCES kimai2_users (id) ON DELETE CASCADE');\n $this->addSql('ALTER TABLE kimai2_timesheet ADD CONSTRAINT FK_4F60C6B181C06096 FOREIGN KEY (activity_id) REFERENCES kimai2_activities (id) ON DELETE CASCADE');", " }", " public function down(Schema $schema): void\n {", "", " // project table", " $this->addSql('ALTER TABLE kimai2_projects DROP FOREIGN KEY FK_407F12069395C3F3');\n $this->addSql('ALTER TABLE kimai2_projects CHANGE customer_id customer_id INT DEFAULT NULL');\n $this->addSql('ALTER TABLE kimai2_projects ADD CONSTRAINT FK_407F12069395C3F3 FOREIGN KEY (customer_id) REFERENCES kimai2_customers (id) ON DELETE CASCADE');", " // timesheet table", " $this->addSql('ALTER TABLE kimai2_timesheet DROP FOREIGN KEY FK_4F60C6B1166D1F9C');\n $this->addSql('DROP INDEX IDX_4F60C6B1166D1F9C ON kimai2_timesheet');\n $this->addSql('ALTER TABLE kimai2_timesheet DROP project_id, CHANGE user user INT DEFAULT NULL, CHANGE activity_id activity_id INT DEFAULT NULL');", " }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "declare(strict_types=1);", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace DoctrineMigrations;", "use App\\Doctrine\\AbstractMigration;\nuse Doctrine\\DBAL\\Schema\\Schema;", "/**\n * - rename mail to email in customer table\n * - converts all decimal to float values, as decimals are treated as string in PHP:\n * https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/types.html#decimal\n *\n * @version 0.9\n */\nfinal class Version20190305152308 extends AbstractMigration\n{\n public function up(Schema $schema): void\n {", " $customers = 'kimai2_customers';\n $projects = 'kimai2_projects';\n $activities = 'kimai2_activities';\n $timesheet = 'kimai2_timesheet';\n $users = 'kimai2_users';", " $this->addSql('ALTER TABLE ' . $activities . ' CHANGE fixed_rate fixed_rate DOUBLE PRECISION DEFAULT NULL, CHANGE hourly_rate hourly_rate DOUBLE PRECISION DEFAULT NULL');\n $this->addSql('ALTER TABLE ' . $customers . ' CHANGE mail email VARCHAR(255) DEFAULT NULL, CHANGE fixed_rate fixed_rate DOUBLE PRECISION DEFAULT NULL, CHANGE hourly_rate hourly_rate DOUBLE PRECISION DEFAULT NULL');\n $this->addSql('ALTER TABLE ' . $projects . ' CHANGE budget budget DOUBLE PRECISION NOT NULL, CHANGE fixed_rate fixed_rate DOUBLE PRECISION DEFAULT NULL, CHANGE hourly_rate hourly_rate DOUBLE PRECISION DEFAULT NULL');\n $this->addSql('ALTER TABLE ' . $timesheet . ' CHANGE rate rate DOUBLE PRECISION NOT NULL, CHANGE fixed_rate fixed_rate DOUBLE PRECISION DEFAULT NULL, CHANGE hourly_rate hourly_rate DOUBLE PRECISION DEFAULT NULL');", " }", " public function down(Schema $schema): void\n {", " $customers = 'kimai2_customers';\n $projects = 'kimai2_projects';\n $activities = 'kimai2_activities';\n $timesheet = 'kimai2_timesheet';", " $this->addSql('ALTER TABLE ' . $activities . ' CHANGE fixed_rate fixed_rate NUMERIC(10, 2) DEFAULT NULL, CHANGE hourly_rate hourly_rate NUMERIC(10, 2) DEFAULT NULL');\n $this->addSql('ALTER TABLE ' . $customers . ' CHANGE email mail VARCHAR(255) DEFAULT NULL, CHANGE fixed_rate fixed_rate NUMERIC(10, 2) DEFAULT NULL, CHANGE hourly_rate hourly_rate NUMERIC(10, 2) DEFAULT NULL');\n $this->addSql('ALTER TABLE ' . $projects . ' CHANGE budget budget NUMERIC(10, 2) NOT NULL, CHANGE fixed_rate fixed_rate NUMERIC(10, 2) DEFAULT NULL, CHANGE hourly_rate hourly_rate NUMERIC(10, 2) DEFAULT NULL');\n $this->addSql('ALTER TABLE ' . $timesheet . ' CHANGE rate rate NUMERIC(10, 2) NOT NULL, CHANGE fixed_rate fixed_rate NUMERIC(10, 2) DEFAULT NULL, CHANGE hourly_rate hourly_rate NUMERIC(10, 2) DEFAULT NULL');", " }\n}" ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "declare(strict_types=1);", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace DoctrineMigrations;", "use App\\Doctrine\\AbstractMigration;\nuse Doctrine\\DBAL\\Schema\\Schema;", "/**\n * - rename mail to email in customer table\n * - converts all decimal to float values, as decimals are treated as string in PHP:\n * https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/types.html#decimal\n *\n * @version 0.9\n */\nfinal class Version20190305152308 extends AbstractMigration\n{\n public function up(Schema $schema): void\n {", " $this->addSql('ALTER TABLE kimai2_activities CHANGE fixed_rate fixed_rate DOUBLE PRECISION DEFAULT NULL, CHANGE hourly_rate hourly_rate DOUBLE PRECISION DEFAULT NULL');\n $this->addSql('ALTER TABLE kimai2_customers CHANGE mail email VARCHAR(255) DEFAULT NULL, CHANGE fixed_rate fixed_rate DOUBLE PRECISION DEFAULT NULL, CHANGE hourly_rate hourly_rate DOUBLE PRECISION DEFAULT NULL');\n $this->addSql('ALTER TABLE kimai2_projects CHANGE budget budget DOUBLE PRECISION NOT NULL, CHANGE fixed_rate fixed_rate DOUBLE PRECISION DEFAULT NULL, CHANGE hourly_rate hourly_rate DOUBLE PRECISION DEFAULT NULL');\n $this->addSql('ALTER TABLE kimai2_timesheet CHANGE rate rate DOUBLE PRECISION NOT NULL, CHANGE fixed_rate fixed_rate DOUBLE PRECISION DEFAULT NULL, CHANGE hourly_rate hourly_rate DOUBLE PRECISION DEFAULT NULL');", " }", " public function down(Schema $schema): void\n {", " $this->addSql('ALTER TABLE kimai2_activities CHANGE fixed_rate fixed_rate NUMERIC(10, 2) DEFAULT NULL, CHANGE hourly_rate hourly_rate NUMERIC(10, 2) DEFAULT NULL');\n $this->addSql('ALTER TABLE kimai2_customers CHANGE email mail VARCHAR(255) DEFAULT NULL, CHANGE fixed_rate fixed_rate NUMERIC(10, 2) DEFAULT NULL, CHANGE hourly_rate hourly_rate NUMERIC(10, 2) DEFAULT NULL');\n $this->addSql('ALTER TABLE kimai2_projects CHANGE budget budget NUMERIC(10, 2) NOT NULL, CHANGE fixed_rate fixed_rate NUMERIC(10, 2) DEFAULT NULL, CHANGE hourly_rate hourly_rate NUMERIC(10, 2) DEFAULT NULL');\n $this->addSql('ALTER TABLE kimai2_timesheet CHANGE rate rate NUMERIC(10, 2) NOT NULL, CHANGE fixed_rate fixed_rate NUMERIC(10, 2) DEFAULT NULL, CHANGE hourly_rate hourly_rate NUMERIC(10, 2) DEFAULT NULL');", " }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "declare(strict_types=1);", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace DoctrineMigrations;", "use App\\Doctrine\\AbstractMigration;\nuse Doctrine\\DBAL\\Schema\\Schema;", "/**\n * @version 1.15\n */\nfinal class Version20210802152814 extends AbstractMigration\n{\n public function getDescription(): string\n {\n return 'Fills the new date column in the timesheet table';\n }", " public function up(Schema $schema): void\n {\n $fetch = $this->connection->prepare('SELECT id, start_time, timezone FROM kimai2_timesheet WHERE date_tz IS NULL');", " $timezones = [];\n foreach (\\DateTimeZone::listIdentifiers() as $tz) {\n $timezones[$tz] = new \\DateTimeZone($tz);\n }", " foreach ($fetch->executeQuery()->iterateAssociative() as $row) {\n if (!isset($timezones[$row['timezone']])) {\n $timezones[$row['timezone']] = new \\DateTimeZone($row['timezone']);\n }\n $date = new \\DateTime($row['start_time'], $timezones['UTC']);\n $date->setTimezone($timezones[$row['timezone']]);\n $this->addSql('UPDATE kimai2_timesheet SET date_tz = ? WHERE id = ?', [$date->format('Y-m-d'), $row['id']]);\n }", " $fetch->free();\n", " $this->preventEmptyMigrationWarning();", " }", " public function down(Schema $schema): void\n {\n $timesheet = $schema->getTable('kimai2_timesheet');\n $timesheet->changeColumn('date_tz', ['notnull' => false]);", " $this->preventEmptyMigrationWarning();\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "declare(strict_types=1);", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace DoctrineMigrations;", "use App\\Doctrine\\AbstractMigration;\nuse Doctrine\\DBAL\\Schema\\Schema;", "/**\n * @version 1.15\n */\nfinal class Version20210802152814 extends AbstractMigration\n{\n public function getDescription(): string\n {\n return 'Fills the new date column in the timesheet table';\n }", " public function up(Schema $schema): void\n {\n $fetch = $this->connection->prepare('SELECT id, start_time, timezone FROM kimai2_timesheet WHERE date_tz IS NULL');", " $timezones = [];\n foreach (\\DateTimeZone::listIdentifiers() as $tz) {\n $timezones[$tz] = new \\DateTimeZone($tz);\n }", " foreach ($fetch->executeQuery()->iterateAssociative() as $row) {\n if (!isset($timezones[$row['timezone']])) {\n $timezones[$row['timezone']] = new \\DateTimeZone($row['timezone']);\n }\n $date = new \\DateTime($row['start_time'], $timezones['UTC']);\n $date->setTimezone($timezones[$row['timezone']]);\n $this->addSql('UPDATE kimai2_timesheet SET date_tz = ? WHERE id = ?', [$date->format('Y-m-d'), $row['id']]);\n }", " $fetch->free();\n", " $this->addSql('ALTER TABLE kimai2_timesheet ALTER date_tz DROP DEFAULT');", " }", " public function down(Schema $schema): void\n {\n $timesheet = $schema->getTable('kimai2_timesheet');\n $timesheet->changeColumn('date_tz', ['notnull' => false]);", " $this->preventEmptyMigrationWarning();\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "declare(strict_types=1);", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace DoctrineMigrations;", "use App\\Doctrine\\AbstractMigration;\nuse Doctrine\\DBAL\\Schema\\Schema;", "/**\n * @version 1.16\n */\nfinal class Version20211008092010 extends AbstractMigration\n{\n public function getDescription(): string\n {\n return 'Extend field orderNumber from 20 to 50 characters.';\n }", " public function up(Schema $schema): void\n {\n $projects = $schema->getTable('kimai2_projects');\n $column = $projects->getColumn('order_number');\n $column->setOptions(['length' => 50]);", "", " }", " public function down(Schema $schema): void\n {\n $projects = $schema->getTable('kimai2_projects');\n $column = $projects->getColumn('order_number');\n $column->setOptions(['length' => 20]);\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "declare(strict_types=1);", "/*\n * This file is part of the Kimai time-tracking app.\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */", "namespace DoctrineMigrations;", "use App\\Doctrine\\AbstractMigration;\nuse Doctrine\\DBAL\\Schema\\Schema;", "/**\n * @version 1.16\n */\nfinal class Version20211008092010 extends AbstractMigration\n{\n public function getDescription(): string\n {\n return 'Extend field orderNumber from 20 to 50 characters.';\n }", " public function up(Schema $schema): void\n {\n $projects = $schema->getTable('kimai2_projects');\n $column = $projects->getColumn('order_number');\n $column->setOptions(['length' => 50]);", "\n $this->preventEmptyMigrationWarning();", " }", " public function down(Schema $schema): void\n {\n $projects = $schema->getTable('kimai2_projects');\n $column = $projects->getColumn('order_number');\n $column->setOptions(['length' => 20]);\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "{% extends \"@AdminLTE/layout/form-theme.html.twig\" %}", "{# Adds the help icon, including a link to the documentation #}\n{% block form_label %}\n {% if form.vars.docu_chapter is defined and form.vars.docu_chapter is not empty %}\n <a href=\"{{ form.vars.docu_chapter|docu_link }}\" target=\"_blank\"><i class=\"{{ 'help'|icon }}\"></i></a>\n {% endif %}\n {{ parent() }}\n{% endblock form_label %}", "{% block quick_entry_week_row %}\n <tr{% with {attr: row_attr|merge({class: (row_attr.class|default('') ~ ' form-group qe-entry-week-row' ~ (not valid ? ' has-error'))|trim})} %}{{ block('attributes') }}{% endwith %}>\n <td>\n {{ form_row(form.project) }}\n </td>\n <td>\n {{ form_row(form.activity) }}\n </td>\n {% for timesheet in form.timesheets %}\n <td class=\"text-center{% if timesheet.vars.data.begin is weekend %} weekend{% endif %}{% if timesheet.vars.data.begin is today %} today{% endif %}\">\n {{ form_row(timesheet) }}\n </td>\n {% endfor %}\n <td class=\"text-nowrap text-center total qe-totals-row\"></td>\n </tr>\n{% endblock %}", "{% block _team_edit_form_members_entry_user_widget %}\n {# this will convert the select box into a hidden field, which are exchangable from an HTML perspective #}\n {%- set type = 'hidden' -%}\n {{ block('form_widget_simple') }}\n{% endblock %}", "{% block team_member_widget %}\n <div class=\"row\">\n <div class=\"col-xs-7\">\n <div class=\"checkbox\">\n <button class=\"btn btn-default btn-xs\" onclick=\"jQuery(this).parent().parent().parent().remove();return false;\"><i class=\"{{ 'trash'|icon }}\"></i></button>\n {% if form.vars.data is not null and form.vars.data.user is not null %}\n {{ form.vars.data.user.displayName }}\n {% else %}\n __USERNAME__\n {% endif %}\n </div>\n {{ form_widget(form.user) }}\n {{ form_errors(form.user) }}\n </div>\n <div class=\"col-xs-5\">\n {{ form_widget(form.teamlead) }}\n </div>\n </div>\n{% endblock team_member_widget %}", "{% block daterange_widget %}\n <div class=\"input-group\">\n <div class=\"input-group-addon\">\n <i class=\"far fa-calendar-alt\"></i>\n </div>", " {% set attr = attr|merge({'data-daterangepickerenable':'on'}) %}", " {{ block('form_widget_simple') }}\n </div>\n{% endblock daterange_widget %}", "{% block duration_widget %}\n {% if (form.vars.duration_presets is defined and form.vars.duration_presets is not empty) and (form.vars.disabled is same as (false)) %}\n <div class=\"input-group\">\n {{ block('form_widget_simple') }}\n <div class=\"input-group-btn\">\n <button type=\"button\" class=\"btn btn-default dropdown-toggle\" data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\"><span class=\"caret\"></span></button>\n <ul class=\"dropdown-menu dropdown-menu-right pre-scrollable\">\n {% for value in form.vars.duration_presets %}\n <li class=\"text-center\">\n <a href=\"#\" onclick=\"jQuery('#{{ form.vars.id }}').val('{{ value }}').trigger('change');return false;\">{{ value }}</a>\n </li>\n {% endfor %}\n </ul>\n </div>\n </div>\n {% else %}\n {{ block('form_widget_simple') }}\n {% endif %}\n{% endblock duration_widget %}", "{% block datetime_widget -%}\n <div class=\"input-group\">\n <div class=\"input-group-addon\">\n <a href=\"#\" onclick=\"if (!jQuery('#{{ id }}').is(':disabled')) { jQuery('#{{ id }}').val(moment().format('{{ attr['data-format'] }}')).change(); }return false;\"><i class=\"{{ 'calendar'|icon }}\"></i></a>\n </div>\n {{ block('form_widget_simple') }}\n </div>\n{%- endblock datetime_widget %}", "{% block date_widget -%}\n <div class=\"input-group\">\n <div class=\"input-group-addon\">\n <a href=\"#\" onclick=\"if (!jQuery('#{{ id }}').is(':disabled')) { jQuery('#{{ id }}').val(moment().format('{{ attr['data-format'] }}')).change(); }return false;\"><i class=\"{{ 'calendar'|icon }}\"></i></a>\n </div>\n {{ block('form_widget_simple') }}\n </div>\n{%- endblock date_widget %}", "{% block text_widget -%}\n {% if icon is not empty %}\n <div class=\"input-group\">\n <div class=\"input-group-addon\">\n <i class=\"{{ icon|icon }}\"></i>\n </div>\n {{ block('form_widget_simple') }}\n </div>\n {% else %}\n {{ block('form_widget_simple') }}\n {% endif %}\n{%- endblock text_widget %}", "{% block yearpicker_widget -%}\n <div class=\"btn-group\">\n <a class=\"btn btn-default btn-left\" href=\"#\" onclick=\"jQuery('#{{ form.vars.id }}').val('{{ previousYear|report_date }}').change()\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"{{ previousYear|date_short }}\">\n <i class=\"{{ 'left'|icon }}\"></i>\n </a>\n <a class=\"btn btn-default\" href=\"#\" onclick=\"return false;\">\n <span id=\"{{ form.vars.id }}_month_name\">\n {% if show_range %}\n {{ year|date_short }} &ndash; {{ nextYear|date_short }}\n {% else %}\n {{ year|date_format('Y') }}\n {% endif %}\n </span>\n </a>\n <a class=\"btn btn-default btn-right\" href=\"#\" onclick=\"jQuery('#{{ form.vars.id }}').val('{{ nextYear|report_date }}').change()\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"{{ nextYear|date_short }}\">\n <i class=\"{{ 'right'|icon }}\"></i>\n </a>\n </div>\n {{ block('hidden_widget') }}\n{%- endblock yearpicker_widget %}", "{% block monthpicker_widget -%}\n <div class=\"btn-group\">\n <a class=\"btn btn-default btn-left\" href=\"#\" onclick=\"jQuery('#{{ form.vars.id }}').val('{{ previousMonth|report_date }}').change()\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"{{ previousMonth|month_name(true) }}\">\n <i class=\"{{ 'left'|icon }}\"></i>\n </a>\n <a class=\"btn btn-default\" href=\"#\" onclick=\"return false;\">\n <span id=\"{{ form.vars.id }}_month_name\">{{ month|month_name(true) }}</span>\n </a>\n <a class=\"btn btn-default btn-right\" href=\"#\" onclick=\"jQuery('#{{ form.vars.id }}').val('{{ nextMonth|report_date }}').change()\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"{{ nextMonth|month_name(true) }}\">\n <i class=\"{{ 'right'|icon }}\"></i>\n </a>\n </div>\n {{ block('hidden_widget') }}\n{%- endblock monthpicker_widget %}", "{% block weekpicker_widget -%}\n <div class=\"btn-group week-picker-btn-group\">\n <a class=\"btn btn-default btn-left\" href=\"#\" onclick=\"jQuery('#{{ form.vars.id }}').val('{{ previousWeek|report_date }}').change()\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"{{ 'stats.workingTimeWeek'|trans({'%week%': previousWeek|date_format('W')}) }}\">\n <i class=\"{{ 'left'|icon }}\"></i>\n </a>\n <a class=\"btn btn-default\" href=\"#\" onclick=\"return false;\">\n <span id=\"{{ form.vars.id }}_week_number\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"{{ 'stats.workingTimeWeek'|trans({'%week%': week|date_format('W')}) }}\">\n {{ week|month_name(true) }}", " {% if week|date_format('m') != nextWeek|date_format('m') %}\n &ndash;\n {{ nextWeek|month_name(true) }}\n {% endif %}", " </span>\n </a>\n <a class=\"btn btn-default btn-right\" href=\"#\" onclick=\"jQuery('#{{ form.vars.id }}').val('{{ nextWeek|report_date }}').change()\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"{{ 'stats.workingTimeWeek'|trans({'%week%': nextWeek|date_format('W')}) }}\">\n <i class=\"{{ 'right'|icon }}\"></i>\n </a>\n </div>\n {{ block('hidden_widget') }}\n{%- endblock weekpicker_widget %}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "{% extends \"@AdminLTE/layout/form-theme.html.twig\" %}", "{# Adds the help icon, including a link to the documentation #}\n{% block form_label %}\n {% if form.vars.docu_chapter is defined and form.vars.docu_chapter is not empty %}\n <a href=\"{{ form.vars.docu_chapter|docu_link }}\" target=\"_blank\"><i class=\"{{ 'help'|icon }}\"></i></a>\n {% endif %}\n {{ parent() }}\n{% endblock form_label %}", "{% block quick_entry_week_row %}\n <tr{% with {attr: row_attr|merge({class: (row_attr.class|default('') ~ ' form-group qe-entry-week-row' ~ (not valid ? ' has-error'))|trim})} %}{{ block('attributes') }}{% endwith %}>\n <td>\n {{ form_row(form.project) }}\n </td>\n <td>\n {{ form_row(form.activity) }}\n </td>\n {% for timesheet in form.timesheets %}\n <td class=\"text-center{% if timesheet.vars.data.begin is weekend %} weekend{% endif %}{% if timesheet.vars.data.begin is today %} today{% endif %}\">\n {{ form_row(timesheet) }}\n </td>\n {% endfor %}\n <td class=\"text-nowrap text-center total qe-totals-row\"></td>\n </tr>\n{% endblock %}", "{% block _team_edit_form_members_entry_user_widget %}\n {# this will convert the select box into a hidden field, which are exchangable from an HTML perspective #}\n {%- set type = 'hidden' -%}\n {{ block('form_widget_simple') }}\n{% endblock %}", "{% block team_member_widget %}\n <div class=\"row\">\n <div class=\"col-xs-7\">\n <div class=\"checkbox\">\n <button class=\"btn btn-default btn-xs\" onclick=\"jQuery(this).parent().parent().parent().remove();return false;\"><i class=\"{{ 'trash'|icon }}\"></i></button>\n {% if form.vars.data is not null and form.vars.data.user is not null %}\n {{ form.vars.data.user.displayName }}\n {% else %}\n __USERNAME__\n {% endif %}\n </div>\n {{ form_widget(form.user) }}\n {{ form_errors(form.user) }}\n </div>\n <div class=\"col-xs-5\">\n {{ form_widget(form.teamlead) }}\n </div>\n </div>\n{% endblock team_member_widget %}", "{% block daterange_widget %}\n <div class=\"input-group\">\n <div class=\"input-group-addon\">\n <i class=\"far fa-calendar-alt\"></i>\n </div>", " {% set attr = attr|merge({'data-daterangepickerenable':'on'}) %}", " {{ block('form_widget_simple') }}\n </div>\n{% endblock daterange_widget %}", "{% block duration_widget %}\n {% if (form.vars.duration_presets is defined and form.vars.duration_presets is not empty) and (form.vars.disabled is same as (false)) %}\n <div class=\"input-group\">\n {{ block('form_widget_simple') }}\n <div class=\"input-group-btn\">\n <button type=\"button\" class=\"btn btn-default dropdown-toggle\" data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\"><span class=\"caret\"></span></button>\n <ul class=\"dropdown-menu dropdown-menu-right pre-scrollable\">\n {% for value in form.vars.duration_presets %}\n <li class=\"text-center\">\n <a href=\"#\" onclick=\"jQuery('#{{ form.vars.id }}').val('{{ value }}').trigger('change');return false;\">{{ value }}</a>\n </li>\n {% endfor %}\n </ul>\n </div>\n </div>\n {% else %}\n {{ block('form_widget_simple') }}\n {% endif %}\n{% endblock duration_widget %}", "{% block datetime_widget -%}\n <div class=\"input-group\">\n <div class=\"input-group-addon\">\n <a href=\"#\" onclick=\"if (!jQuery('#{{ id }}').is(':disabled')) { jQuery('#{{ id }}').val(moment().format('{{ attr['data-format'] }}')).change(); }return false;\"><i class=\"{{ 'calendar'|icon }}\"></i></a>\n </div>\n {{ block('form_widget_simple') }}\n </div>\n{%- endblock datetime_widget %}", "{% block date_widget -%}\n <div class=\"input-group\">\n <div class=\"input-group-addon\">\n <a href=\"#\" onclick=\"if (!jQuery('#{{ id }}').is(':disabled')) { jQuery('#{{ id }}').val(moment().format('{{ attr['data-format'] }}')).change(); }return false;\"><i class=\"{{ 'calendar'|icon }}\"></i></a>\n </div>\n {{ block('form_widget_simple') }}\n </div>\n{%- endblock date_widget %}", "{% block text_widget -%}\n {% if icon is not empty %}\n <div class=\"input-group\">\n <div class=\"input-group-addon\">\n <i class=\"{{ icon|icon }}\"></i>\n </div>\n {{ block('form_widget_simple') }}\n </div>\n {% else %}\n {{ block('form_widget_simple') }}\n {% endif %}\n{%- endblock text_widget %}", "{% block yearpicker_widget -%}\n <div class=\"btn-group\">\n <a class=\"btn btn-default btn-left\" href=\"#\" onclick=\"jQuery('#{{ form.vars.id }}').val('{{ previousYear|report_date }}').change()\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"{{ previousYear|date_short }}\">\n <i class=\"{{ 'left'|icon }}\"></i>\n </a>\n <a class=\"btn btn-default\" href=\"#\" onclick=\"return false;\">\n <span id=\"{{ form.vars.id }}_month_name\">\n {% if show_range %}\n {{ year|date_short }} &ndash; {{ nextYear|date_short }}\n {% else %}\n {{ year|date_format('Y') }}\n {% endif %}\n </span>\n </a>\n <a class=\"btn btn-default btn-right\" href=\"#\" onclick=\"jQuery('#{{ form.vars.id }}').val('{{ nextYear|report_date }}').change()\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"{{ nextYear|date_short }}\">\n <i class=\"{{ 'right'|icon }}\"></i>\n </a>\n </div>\n {{ block('hidden_widget') }}\n{%- endblock yearpicker_widget %}", "{% block monthpicker_widget -%}\n <div class=\"btn-group\">\n <a class=\"btn btn-default btn-left\" href=\"#\" onclick=\"jQuery('#{{ form.vars.id }}').val('{{ previousMonth|report_date }}').change()\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"{{ previousMonth|month_name(true) }}\">\n <i class=\"{{ 'left'|icon }}\"></i>\n </a>\n <a class=\"btn btn-default\" href=\"#\" onclick=\"return false;\">\n <span id=\"{{ form.vars.id }}_month_name\">{{ month|month_name(true) }}</span>\n </a>\n <a class=\"btn btn-default btn-right\" href=\"#\" onclick=\"jQuery('#{{ form.vars.id }}').val('{{ nextMonth|report_date }}').change()\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"{{ nextMonth|month_name(true) }}\">\n <i class=\"{{ 'right'|icon }}\"></i>\n </a>\n </div>\n {{ block('hidden_widget') }}\n{%- endblock monthpicker_widget %}", "{% block weekpicker_widget -%}\n <div class=\"btn-group week-picker-btn-group\">\n <a class=\"btn btn-default btn-left\" href=\"#\" onclick=\"jQuery('#{{ form.vars.id }}').val('{{ previousWeek|report_date }}').change()\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"{{ 'stats.workingTimeWeek'|trans({'%week%': previousWeek|date_format('W')}) }}\">\n <i class=\"{{ 'left'|icon }}\"></i>\n </a>\n <a class=\"btn btn-default\" href=\"#\" onclick=\"return false;\">\n <span id=\"{{ form.vars.id }}_week_number\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"{{ 'stats.workingTimeWeek'|trans({'%week%': week|date_format('W')}) }}\">\n {{ week|month_name(true) }}", " &ndash;\n {{ 'stats.workingTimeWeekShort'|trans({'%week%': week|date_format('W')}) }}", " </span>\n </a>\n <a class=\"btn btn-default btn-right\" href=\"#\" onclick=\"jQuery('#{{ form.vars.id }}').val('{{ nextWeek|report_date }}').change()\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"{{ 'stats.workingTimeWeek'|trans({'%week%': nextWeek|date_format('W')}) }}\">\n <i class=\"{{ 'right'|icon }}\"></i>\n </a>\n </div>\n {{ block('hidden_widget') }}\n{%- endblock weekpicker_widget %}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "{% macro projects(view, query) %}\n {% import \"macros/widgets.html.twig\" as widgets %}\n {% set event = actions(app.user, 'projects', view, {'query': query}) %}\n {{ widgets.page_actions(event.actions) }}\n{% endmacro %}", "{% macro project(project, view, isTable) %}\n {% import \"macros/widgets.html.twig\" as widgets %}", " {% set event = actions(app.user, 'project', view, {'project': project}) %}", " {% if view == 'index' or view == 'custom' or isTable is not null %}\n {{ widgets.table_actions(event.actions) }}\n {% else %}\n {{ widgets.page_actions(event.actions) }}\n {% endif %}\n{% endmacro %}" ]
[ 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "{% macro projects(view, query) %}\n {% import \"macros/widgets.html.twig\" as widgets %}\n {% set event = actions(app.user, 'projects', view, {'query': query}) %}\n {{ widgets.page_actions(event.actions) }}\n{% endmacro %}", "{% macro project(project, view, isTable) %}\n {% import \"macros/widgets.html.twig\" as widgets %}", " {% set event = actions(app.user, 'project', view, {'project': project, 'token': csrf_token('project.duplicate')}) %}", " {% if view == 'index' or view == 'custom' or isTable is not null %}\n {{ widgets.table_actions(event.actions) }}\n {% else %}\n {{ widgets.page_actions(event.actions) }}\n {% endif %}\n{% endmacro %}" ]
[ 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "{% macro teams(view, query) %}\n {% import \"macros/widgets.html.twig\" as widgets %}\n {% set event = actions(app.user, 'teams', view, {'query': query}) %}\n {{ widgets.page_actions(event.actions) }}\n{% endmacro %}", "{% macro team(team, view) %}\n {% import \"macros/widgets.html.twig\" as widgets %}", " {% set event = actions(app.user, 'team', view, {'team': team}) %}", " {% if view == 'index' %}\n {{ widgets.table_actions(event.actions) }}\n {% else %}\n {{ widgets.page_actions(event.actions) }}\n {% endif %}\n{% endmacro %}" ]
[ 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "{% macro teams(view, query) %}\n {% import \"macros/widgets.html.twig\" as widgets %}\n {% set event = actions(app.user, 'teams', view, {'query': query}) %}\n {{ widgets.page_actions(event.actions) }}\n{% endmacro %}", "{% macro team(team, view) %}\n {% import \"macros/widgets.html.twig\" as widgets %}", " {% set event = actions(app.user, 'team', view, {'team': team, 'token': csrf_token('team.duplicate')}) %}", " {% if view == 'index' %}\n {{ widgets.table_actions(event.actions) }}\n {% else %}\n {{ widgets.page_actions(event.actions) }}\n {% endif %}\n{% endmacro %}" ]
[ 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "{% macro timesheets_team(view, query) %}\n {% import \"macros/widgets.html.twig\" as widgets %}\n {% set event = actions(app.user, 'timesheets_team', view, {'query': query}) %}\n {{ widgets.page_actions(event.actions) }}\n{% endmacro %}", "{% macro timesheet_team(timesheet, view) %}\n {% import \"macros/widgets.html.twig\" as widgets %}", " {% set event = actions(app.user, 'timesheet_team', view, {'timesheet': timesheet}) %}", " {% if view == 'index' or view == 'custom' %}\n {{ widgets.table_actions(event.actions) }}\n {% else %}\n {{ widgets.page_actions(event.actions) }}\n {% endif %}\n{% endmacro %}", "{% macro timesheets_team_multi_update(view) %}\n {% import \"macros/widgets.html.twig\" as widgets %}\n {% set event = actions(app.user, 'timesheets_team_multi_update', view) %}\n {{ widgets.page_actions(event.actions) }}\n{% endmacro %}" ]
[ 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "{% macro timesheets_team(view, query) %}\n {% import \"macros/widgets.html.twig\" as widgets %}\n {% set event = actions(app.user, 'timesheets_team', view, {'query': query}) %}\n {{ widgets.page_actions(event.actions) }}\n{% endmacro %}", "{% macro timesheet_team(timesheet, view) %}\n {% import \"macros/widgets.html.twig\" as widgets %}", " {% set event = actions(app.user, 'timesheet_team', view, {'timesheet': timesheet, 'token': csrf_token('admin_timesheet.duplicate')}) %}", " {% if view == 'index' or view == 'custom' %}\n {{ widgets.table_actions(event.actions) }}\n {% else %}\n {{ widgets.page_actions(event.actions) }}\n {% endif %}\n{% endmacro %}", "{% macro timesheets_team_multi_update(view) %}\n {% import \"macros/widgets.html.twig\" as widgets %}\n {% set event = actions(app.user, 'timesheets_team_multi_update', view) %}\n {{ widgets.page_actions(event.actions) }}\n{% endmacro %}" ]
[ 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "{% macro timesheets(view, query) %}\n {% import \"macros/widgets.html.twig\" as widgets %}\n {% set event = actions(app.user, 'timesheets', view, {'query': query}) %}\n {{ widgets.page_actions(event.actions) }}\n{% endmacro %}", "{% macro timesheet(timesheet, view, options) %}\n {% import \"macros/widgets.html.twig\" as widgets %}", " {% set event = actions(app.user, 'timesheet', view, {'timesheet': timesheet}) %}", " {% if view == 'index' or view == 'custom' %}\n {{ widgets.table_actions(event.actions) }}\n {% else %}\n {{ widgets.page_actions(event.actions) }}\n {% endif %}\n{% endmacro %}", "{% macro timesheets_multi_update(view) %}\n {% import \"macros/widgets.html.twig\" as widgets %}\n {% set event = actions(app.user, 'timesheets_multi_update', view) %}\n {{ widgets.page_actions(event.actions) }}\n{% endmacro %}" ]
[ 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211
Determine whether the {function_name} code is vulnerable or not.
[ "{% macro timesheets(view, query) %}\n {% import \"macros/widgets.html.twig\" as widgets %}\n {% set event = actions(app.user, 'timesheets', view, {'query': query}) %}\n {{ widgets.page_actions(event.actions) }}\n{% endmacro %}", "{% macro timesheet(timesheet, view, options) %}\n {% import \"macros/widgets.html.twig\" as widgets %}", " {% set event = actions(app.user, 'timesheet', view, {'timesheet': timesheet, 'token': csrf_token('timesheet.duplicate')}) %}", " {% if view == 'index' or view == 'custom' %}\n {{ widgets.table_actions(event.actions) }}\n {% else %}\n {{ widgets.page_actions(event.actions) }}\n {% endif %}\n{% endmacro %}", "{% macro timesheets_multi_update(view) %}\n {% import \"macros/widgets.html.twig\" as widgets %}\n {% set event = actions(app.user, 'timesheets_multi_update', view) %}\n {{ widgets.page_actions(event.actions) }}\n{% endmacro %}" ]
[ 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [25, 429, 89, 616, 106, 201, 43, 77, 38, 45, 94, 55, 37, 65, 51, 48, 31, 165, 10, 10, 10, 10, 427, 36, 226, 215, 732, 452, 32, 56, 56, 56, 56, 56, 56, 794, 794], "buggy_code_start_loc": [20, 424, 24, 214, 23, 30, 42, 76, 37, 25, 40, 36, 26, 25, 28, 47, 31, 161, 9, 9, 9, 9, 427, 36, 219, 209, 711, 431, 1, 1, 56, 56, 56, 56, 56, 794, 794], "filenames": ["src/Constants.php", "src/Controller/ProjectController.php", "src/Controller/TeamController.php", "src/Controller/TimesheetAbstractController.php", "src/Controller/TimesheetController.php", "src/Controller/TimesheetTeamController.php", "src/EventSubscriber/Actions/AbstractTimesheetSubscriber.php", "src/EventSubscriber/Actions/ProjectSubscriber.php", "src/EventSubscriber/Actions/TeamSubscriber.php", "src/Migrations/Version20180701120000.php", "src/Migrations/Version20180715160326.php", "src/Migrations/Version20180730044139.php", "src/Migrations/Version20180924111853.php", "src/Migrations/Version20181031220003.php", "src/Migrations/Version20190305152308.php", "src/Migrations/Version20210802152814.php", "src/Migrations/Version20211008092010.php", "templates/form/kimai-theme.html.twig", "templates/project/actions.html.twig", "templates/team/actions.html.twig", "templates/timesheet-team/actions.html.twig", "templates/timesheet/actions.html.twig", "tests/Controller/ControllerBaseTest.php", "tests/Controller/DoctorControllerTest.php", "tests/Controller/ProjectControllerTest.php", "tests/Controller/TeamControllerTest.php", "tests/Controller/TimesheetControllerTest.php", "tests/Controller/TimesheetTeamControllerTest.php", "translations/about.ja.xlf", "translations/flashmessages.el.xlf", "translations/flashmessages.fr.xlf", "translations/flashmessages.he.xlf", "translations/flashmessages.pt.xlf", "translations/flashmessages.pt_BR.xlf", "translations/flashmessages.tr.xlf", "translations/messages.de.xlf", "translations/messages.en.xlf"], "fixing_code_end_loc": [25, 440, 99, 616, 116, 211, 43, 77, 38, 37, 90, 48, 33, 55, 40, 48, 34, 163, 10, 10, 10, 10, 438, 44, 248, 225, 764, 484, 32, 61, 61, 61, 61, 61, 61, 799, 799], "fixing_code_start_loc": [20, 424, 25, 214, 24, 31, 42, 76, 37, 25, 39, 36, 26, 24, 28, 47, 32, 161, 9, 9, 9, 9, 428, 37, 219, 209, 711, 431, 1, 1, 57, 57, 57, 57, 57, 795, 795], "message": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:kimai:kimai_2:*:*:*:*:*:*:*:*", "matchCriteriaId": "18DE946F-C2DA-4605-B44E-49B5DC42961C", "versionEndExcluding": "1.16.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "kimai2 is vulnerable to Cross-Site Request Forgery (CSRF)"}, {"lang": "es", "value": "kimai2 es vulnerable a un ataque de tipo Cross-Site Request Forgery (CSRF)"}], "evaluatorComment": null, "id": "CVE-2021-3976", "lastModified": "2021-11-23T17:25:49.577", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-11-19T11:15:07.880", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/0567048a-118c-42ec-9f94-b55533017406"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/kevinpapst/kimai2/commit/b28e9c120c87222e21a238f1b03a609d6a5d506e"}, "type": "CWE-352"}
211